"""
ui/upload_page.py
- Feature 1: Full data extraction + Category Name + Tags + Hashtags
"""

import re
import streamlit as st
from core.youtube_api import (
    get_video_details, extract_video_id, get_video_categories
)
from core.ai_analyzer import analyze_video
from core.database import save_entry
from core.export import to_pdf, to_txt


# =====================================================
# Category ID → Name (cache per session)
# =====================================================
@st.cache_data(ttl=3600, show_spinner=False)
def _get_category_map(region: str = "US") -> dict:
    """Cache category map for 1 hour"""
    try:
        cats = get_video_categories(region)
        return {c["id"]: c["title"] for c in cats}
    except Exception:
        return {}


def _category_name(cat_id: str, region: str = "US") -> str:
    if not cat_id:
        return "—"
    m = _get_category_map(region)
    return m.get(str(cat_id), f"Category {cat_id}")


# =====================================================
# Hashtag extraction
# =====================================================
def _extract_hashtags(description: str, tags: list[str]) -> dict:
    """
    Extract hashtags from description text.
    Returns {"from_desc": [...], "from_tags": [...], "all": [...]}
    """
    desc = description or ""
    # Regex supports letters, numbers, underscore, and Khmer/Unicode
    from_desc = re.findall(r"#([\w\u1780-\u17FF]+)", desc)
    from_desc = [f"#{h}" for h in from_desc]

    # Generate hashtag suggestions from tags
    from_tags = []
    if tags:
        for t in tags[:20]:
            clean = re.sub(r"[^A-Za-z0-9]", "", t)
            if clean and len(clean) > 2:
                from_tags.append(f"#{clean}")

    # Dedupe (keep order)
    seen = set()
    all_tags = []
    for h in from_desc + from_tags:
        hl = h.lower()
        if hl not in seen:
            seen.add(hl)
            all_tags.append(h)

    return {
        "from_desc": from_desc,
        "from_tags": from_tags,
        "all": all_tags[:20],
    }


def _stat_card(label, value, col):
    col.metric(label, value)


# =====================================================
# Main
# =====================================================
def render_upload():
    st.subheader("📥 Feature 1 — Full Video Data Extraction")
    st.caption("Paste YouTube URL → Title, Description, Category, Tags, Hashtags, Stats")

    url = st.text_input("YouTube URL or Video ID",
                        placeholder="https://www.youtube.com/watch?v=...")

    c1, c2, _ = st.columns([1, 1, 3])
    fetch = c1.button("🔍 Fetch Data", use_container_width=True)
    with_ai = c2.button("🤖 Fetch + AI", use_container_width=True)

    if not (fetch or with_ai):
        if "last_video" in st.session_state:
            _render_result(
                st.session_state.last_video,
                st.session_state.get("last_ai"),
            )
        return

    vid = extract_video_id(url)
    if not vid:
        st.error("❌ Invalid YouTube URL")
        return

    with st.spinner("Fetching video data..."):
        try:
            video = get_video_details(vid)
        except Exception as e:
            st.error(f"Error: {e}")
            return

    if not video:
        st.error("Video not found or unavailable")
        return

    ai = None
    if with_ai:
        with st.spinner("Analyzing with AI..."):
            try:
                ai = analyze_video(video)
            except Exception as e:
                st.warning(f"AI failed: {e}")

    st.session_state.last_video = video
    st.session_state.last_ai = ai
    save_entry("video", video["title"], {"video": video, "ai": ai}, url=video["url"])
    _render_result(video, ai)


def _render_result(video, ai):
    st.success("✅ Data fetched")

    # ============ Header ============
    c1, c2 = st.columns([1, 2])
    with c1:
        if video.get("thumbnail"):
            st.image(video["thumbnail"], use_container_width=True)
    with c2:
        st.markdown(f"### {video['title']}")
        st.markdown(f"**Channel:** {video['channel_title']}")
        st.markdown(f"**URL:** {video['url']}")

    # ============ Stats ============
    s1, s2, s3, s4 = st.columns(4)
    _stat_card("👁 Views", video["views_fmt"], s1)
    _stat_card("👍 Likes", video["likes_fmt"], s2)
    _stat_card("💬 Comments", video["comments_fmt"], s3)
    _stat_card("⏱ Duration", video["duration"], s4)

    # ============ ⭐ CATEGORY HIGHLIGHT ============
    cat_id = video.get("category_id", "")
    cat_name = _category_name(cat_id)
    st.markdown("---")
    cat_col1, cat_col2, cat_col3 = st.columns([2, 1, 1])
    with cat_col1:
        st.markdown(f"### 📂 Category: **{cat_name}**")
    with cat_col2:
        st.metric("Category ID", cat_id or "—")
    with cat_col3:
        st.metric("Language", video.get("default_language") or "—")

    # ============ Tabs ============
    st.markdown("---")
    tab1, tab2, tab3, tab4, tab5 = st.tabs(
        ["📌 Title", "📝 Description", "🏷 Tags", "#️⃣ Hashtags", "🔧 Raw Data"]
    )

    with tab1:
        st.markdown("### 📌 Title")
        st.text_area("Copy Title ↓", video["title"], height=70,
                     key=f"copy_title_{video['id']}")
        tl = len(video["title"])
        st.caption(f"📏 {tl} chars {'✅' if 40 <= tl <= 70 else '⚠️ ideal: 40-70'}")

    with tab2:
        st.markdown("### 📝 Description")
        desc = video.get("description", "") or "(empty)"
        st.caption(f"📏 {len(desc)} characters")
        st.text_area("Copy Description ↓", desc, height=350,
                     key=f"copy_desc_url_{video['id']}")
        st.download_button(
            "⬇️ Download .txt",
            desc.encode("utf-8"),
            file_name=f"description_{video['id']}.txt",
            mime="text/plain",
        )

    with tab3:
        st.markdown("### 🏷 Tags")
        tags = video.get("tags", [])
        if tags:
            st.caption(f"**{len(tags)} tags** • {sum(len(t) for t in tags)} chars total")
            st.text_area("Copy Tags (comma-separated) ↓", ", ".join(tags),
                         height=150, key=f"copy_tags_{video['id']}")
            st.markdown("**Individual tags:**")
            st.markdown(" ".join([f"`{t}`" for t in tags]))
            st.download_button(
                "⬇️ Download .txt",
                ", ".join(tags).encode("utf-8"),
                file_name=f"tags_{video['id']}.txt",
                mime="text/plain",
            )
        else:
            st.info("No tags on this video")

    with tab4:
        st.markdown("### #️⃣ Hashtags")
        hdata = _extract_hashtags(
            video.get("description", ""),
            video.get("tags", []),
        )

        # From description (REAL)
        st.markdown("#### 📄 From Description (Real)")
        if hdata["from_desc"]:
            st.success(f"**{len(hdata['from_desc'])} hashtags found in description**")
            st.text_area("Copy ↓", " ".join(hdata["from_desc"]),
                         height=80, key=f"copy_hash_desc_{video['id']}")
        else:
            st.info("⚠️ គ្មាន `#hashtag` ក្នុង Description")

        # From tags (SUGGESTED)
        st.markdown("---")
        st.markdown("#### 💡 Suggested (from Tags)")
        st.caption("⚠️ Suggest ពី Tags — មិនមែន Hashtag ពិតទេ")
        if hdata["from_tags"]:
            st.code(" ".join(hdata["from_tags"][:10]), language=None)
        else:
            st.info("No tags to generate from")

        # All combined
        if hdata["all"]:
            st.markdown("---")
            st.markdown("#### 🎯 Copy All (Desc + Suggested)")
            st.text_area("Combined ↓", " ".join(hdata["all"]),
                         height=100, key=f"copy_hash_all_{video['id']}")

    with tab5:
        st.markdown("### 🔧 Raw JSON")
        st.json(video)

    # ============ Preview ============
    st.markdown("---")
    with st.expander("▶️ Preview video"):
        st.video(video["url"])

    # ============ AI Insights ============
    if ai:
        st.markdown("---")
        st.markdown("## 🤖 AI Insights")
        st.metric("SEO Score", f"{ai.get('score', 0)}/100")
        st.info(ai.get("summary", ""))

        with st.expander("✨ Recommended Titles", expanded=True):
            for t in ai.get("recommended_titles", []):
                st.markdown(f"- {t}")

        with st.expander("📄 Recommended Description"):
            st.text_area("Copy", ai.get("recommended_description", ""),
                         height=200, key="ai_desc_up")

        with st.expander("🏷 Recommended Tags"):
            st.code(", ".join(ai.get("recommended_tags", [])), language=None)

        with st.expander("#️⃣ Recommended Hashtags"):
            st.write(" ".join(ai.get("recommended_hashtags", [])))

    # ============ Export ============
    st.markdown("---")
    e1, e2, _ = st.columns([1, 1, 3])
    e1.download_button("⬇️ PDF", to_pdf(video, ai),
                       file_name=f"{video['id']}.pdf", mime="application/pdf")
    e2.download_button("⬇️ TXT", to_txt(video, ai),
                       file_name=f"{video['id']}.txt", mime="text/plain")