"""
ui/keywords_page.py
- Feature 2: Trending Keywords + VPH + Time/Duration Filter + Sort
"""

import streamlit as st
import pandas as pd
from datetime import datetime, timedelta, timezone

from core.youtube_api import search_videos, get_video_details, get_client
from core.ai_analyzer import generate_keywords
from core.database import save_entry


# =====================================================
# Helpers
# =====================================================
def _parse_duration_iso(iso: str) -> int:
    """PT15M33S → 933 (seconds)"""
    import re
    if not iso:
        return 0
    m = re.match(r"PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?", iso)
    if not m:
        return 0
    h = int(m.group(1) or 0)
    mi = int(m.group(2) or 0)
    s = int(m.group(3) or 0)
    return h * 3600 + mi * 60 + s


def _fmt_duration(sec: int) -> str:
    if sec < 60:
        return f"{sec}s"
    if sec < 3600:
        m, s = divmod(sec, 60)
        return f"{m}m{s}s" if s else f"{m}m"
    h, r = divmod(sec, 3600)
    m = r // 60
    return f"{h}h{m}m" if m else f"{h}h"


def _calc_vph(views: int, published_at: str) -> int:
    """Views Per Hour"""
    try:
        pub = datetime.fromisoformat(published_at.replace("Z", "+00:00"))
        now = datetime.now(timezone.utc)
        hours = (now - pub).total_seconds() / 3600
        if hours < 1:
            hours = 1
        return round(views / hours)
    except Exception:
        return 0


def _fmt_num(n) -> str:
    try:
        n = int(n)
        if n >= 1_000_000_000:
            return f"{n/1_000_000_000:.1f}B"
        if n >= 1_000_000:
            return f"{n/1_000_000:.1f}M"
        if n >= 1_000:
            return f"{n/1_000:.1f}K"
        return str(n)
    except Exception:
        return str(n)


def _get_published_after(time_range: str) -> str | None:
    """Convert time range → ISO date string"""
    if time_range == "all":
        return None
    now = datetime.now(timezone.utc)
    if time_range == "48h":
        dt = now - timedelta(hours=48)
    elif time_range == "7d":
        dt = now - timedelta(days=7)
    elif time_range == "28d":
        dt = now - timedelta(days=28)
    elif time_range == "90d":
        dt = now - timedelta(days=90)
    else:
        return None
    return dt.isoformat()


def _search_with_filters(query: str, region: str, time_range: str,
                          max_results: int) -> list[dict]:
    """Search videos with time filter applied"""
    from core.youtube_api import _execute

    params = {
        "part": "snippet",
        "type": "video",
        "q": query,
        "maxResults": min(max_results, 50),
        "order": "viewCount",
        "regionCode": region,
    }

    after = _get_published_after(time_range)
    if after:
        params["publishedAfter"] = after

    def _req(service):
        return service.search().list(**params)

    resp = _execute(_req)
    out = []
    for it in resp.get("items", []):
        sn = it["snippet"]
        out.append({
            "id": it["id"]["videoId"],
            "url": f"https://www.youtube.com/watch?v={it['id']['videoId']}",
            "title": sn.get("title", ""),
            "channel": sn.get("channelTitle", ""),
            "published_at": sn.get("publishedAt", ""),
            "description": sn.get("description", ""),
            "thumbnail": sn.get("thumbnails", {}).get("medium", {}).get("url", ""),
        })
    return out


def _get_details_batch(ids: list[str]) -> list[dict]:
    """Get full details for batch of video IDs"""
    from core.youtube_api import _execute

    if not ids:
        return []

    def _req(service):
        return service.videos().list(
            part="snippet,statistics,contentDetails",
            id=",".join(ids[:50]),
        )

    resp = _execute(_req)
    out = []
    for v in resp.get("items", []):
        sn = v["snippet"]
        st = v.get("statistics", {})
        cd = v.get("contentDetails", {})

        views = int(st.get("viewCount", 0) or 0)
        likes = int(st.get("likeCount", 0) or 0)
        comments = int(st.get("commentCount", 0) or 0)
        duration_sec = _parse_duration_iso(cd.get("duration", ""))

        out.append({
            "id": v["id"],
            "url": f"https://www.youtube.com/watch?v={v['id']}",
            "title": sn.get("title", ""),
            "channel": sn.get("channelTitle", ""),
            "published_at": sn.get("publishedAt", ""),
            "description": sn.get("description", ""),
            "thumbnail": sn.get("thumbnails", {}).get("medium", {}).get("url", ""),
            "tags": sn.get("tags", []),
            "views": views,
            "likes": likes,
            "comments": comments,
            "views_fmt": _fmt_num(views),
            "likes_fmt": _fmt_num(likes),
            "comments_fmt": _fmt_num(comments),
            "duration_sec": duration_sec,
            "duration_fmt": _fmt_duration(duration_sec),
            "vph": _calc_vph(views, sn.get("publishedAt", "")),
            "vph_fmt": _fmt_num(_calc_vph(views, sn.get("publishedAt", ""))),
            "engagement": likes + comments,
        })
    return out


def _apply_duration_filter(videos: list[dict], duration_filter: str) -> list[dict]:
    """Filter by duration"""
    if duration_filter == "all":
        return videos
    out = []
    for v in videos:
        sec = v.get("duration_sec", 0)
        if duration_filter == "shorts" and 0 < sec < 60:
            out.append(v)
        elif duration_filter == "medium" and 60 <= sec <= 600:
            out.append(v)
        elif duration_filter == "long" and sec > 600:
            out.append(v)
    return out


def _apply_sort(videos: list[dict], sort_by: str) -> list[dict]:
    """Sort videos"""
    if sort_by == "vph":
        return sorted(videos, key=lambda x: x.get("vph", 0), reverse=True)
    if sort_by == "views":
        return sorted(videos, key=lambda x: x.get("views", 0), reverse=True)
    if sort_by == "recent":
        return sorted(videos, key=lambda x: x.get("published_at", ""), reverse=True)
    if sort_by == "engagement":
        return sorted(videos, key=lambda x: x.get("engagement", 0), reverse=True)
    return videos


# =====================================================
# Main Render
# =====================================================
def render_keywords():
    st.subheader("🔑 Feature 2 — Trending Keywords")
    st.caption("Find keywords + tags + hashtags from top videos with VPH analysis")

    # ===== Input =====
    col1, col2 = st.columns([3, 1])
    query = col1.text_input(
        "Topic or Keyword",
        placeholder="e.g. AI tools, cooking, fitness",
    )
    region = col2.selectbox(
        "Region",
        ["KH", "US", "TH", "VN", "GB", "IN", "JP", "KR", "ID", "PH"],
        index=0,
    )

    # ===== Filters Row 1 =====
    st.markdown("##### 🎛️ Filters")
    c1, c2, c3, c4 = st.columns(4)

    time_range = c1.selectbox(
        "📅 Time Range",
        ["all", "48h", "7d", "28d", "90d"],
        index=2,
        format_func=lambda x: {
            "all": "All Time",
            "48h": "Last 48 Hours",
            "7d": "Last 7 Days",
            "28d": "Last 28 Days",
            "90d": "Last 90 Days",
        }[x],
    )

    duration_filter = c2.selectbox(
        "⏱️ Duration",
        ["all", "shorts", "medium", "long"],
        index=0,
        format_func=lambda x: {
            "all": "All Durations",
            "shorts": "📱 Shorts (<1m)",
            "medium": "🎬 Medium (1-10m)",
            "long": "🎥 Long (>10m)",
        }[x],
    )

    sort_by = c3.selectbox(
        "📊 Sort By",
        ["vph", "views", "recent", "engagement"],
        index=0,
        format_func=lambda x: {
            "vph": "⚡ VPH (Views/Hour)",
            "views": "👁️ Views",
            "recent": "🕐 Most Recent",
            "engagement": "❤️ Engagement",
        }[x],
    )

    max_v = c4.selectbox("🎬 Videos", [25, 50, 100], index=1)

    # ===== Analyze Button =====
    if st.button("🚀 Find Trending Keywords", use_container_width=True, type="primary"):
        if not query.strip():
            st.warning("Please enter a topic")
            return

        # ===== Step 1: Search videos =====
        with st.spinner(f"🔍 Searching top-viewed videos..."):
            try:
                results = _search_with_filters(query, region, time_range, max_v)
            except Exception as e:
                st.error(f"❌ Search error: {e}")
                return

        if not results:
            st.error("❌ No videos found. Try a different topic or wider Time Range.")
            return

        ids = [r["id"] for r in results]

        # ===== Step 2: Get details =====
        with st.spinner(f"📊 Fetching details ({len(ids)} videos)..."):
            try:
                videos = _get_details_batch(ids)
            except Exception as e:
                st.error(f"❌ Details error: {e}")
                return

        # ===== Step 3: Apply filters =====
        videos = _apply_duration_filter(videos, duration_filter)
        if not videos:
            st.warning("⚠️ No videos match the Duration filter. Try 'All Durations'.")
            return

        videos = _apply_sort(videos, sort_by)

        # ===== Step 4: AI Keywords =====
        with st.spinner("🧠 Generating AI keywords..."):
            try:
                kw_data = generate_keywords(query)
            except Exception as e:
                st.warning(f"⚠️ AI failed: {e}")
                kw_data = {}

        # Save to history
        try:
            save_entry("keywords", query, {
                "query": query,
                "videos": videos[:20],
                "kw_data": kw_data,
                "filters": {
                    "region": region,
                    "time_range": time_range,
                    "duration": duration_filter,
                    "sort_by": sort_by,
                },
            })
        except Exception:
            pass

        # Cache for display
        st.session_state.kw_result = {
            "query": query,
            "videos": videos,
            "kw_data": kw_data,
            "filters": {
                "region": region,
                "time_range": time_range,
                "duration": duration_filter,
                "sort_by": sort_by,
            },
        }
        st.rerun()

    # ===== Render Result =====
    res = st.session_state.get("kw_result")
    if not res:
        return

    _render_result(res)


# =====================================================
# Render Result
# =====================================================
def _render_result(res: dict):
    videos = res["videos"]
    kw_data = res["kw_data"]
    query = res["query"]

    st.success(f"✅ Found **{len(videos)}** videos for **{query}**")

    # ===== VPH Stats Grid =====
    total_views = sum(v["views"] for v in videos)
    total_vph = sum(v["vph"] for v in videos)
    total_eng = sum(v["engagement"] for v in videos)
    avg_vph = round(total_vph / len(videos)) if videos else 0
    avg_views = round(total_views / len(videos)) if videos else 0
    avg_eng = round(total_eng / len(videos)) if videos else 0

    m1, m2, m3, m4, m5 = st.columns(5)
    m1.metric("🎬 Videos", len(videos))
    m2.metric("👁️ Total Views", _fmt_num(total_views))
    m3.metric("📊 Avg Views", _fmt_num(avg_views))
    m4.metric("⚡ Avg VPH", _fmt_num(avg_vph))
    m5.metric("❤️ Avg Engagement", _fmt_num(avg_eng))

    st.markdown("---")

    # ===== Tabs =====
    t1, t2, t3, t4, t5, t6 = st.tabs([
        "🎯 Keywords",
        "⭐ Long-Tail",
        "🏷 Tags",
        "#️⃣ Hashtags",
        "📺 Top Videos (VPH)",
        "💡 Recommendations",
    ])

    with t1:
        st.markdown("### 🎯 Trending Keywords")
        kws = kw_data.get("keywords", [])
        if kws:
            for k in kws:
                st.markdown(f"- `{k}`")
            st.markdown("**Copy:**")
            st.code(", ".join(kws), language=None)
        else:
            st.info("No keywords returned")

    with t2:
        st.markdown("### ⭐ Long-Tail Keywords")
        lts = kw_data.get("long_tail_keywords", [])
        if lts:
            for k in lts:
                st.markdown(f"- {k}")
            st.code("\n".join(lts), language=None)
        else:
            st.info("No long-tail keywords")

    with t3:
        st.markdown("### 🏷 Recommended Tags")
        tags = kw_data.get("tags", [])
        if tags:
            st.code(", ".join(tags), language=None)
            st.download_button(
                "⬇️ Download Tags .txt",
                "\n".join(tags).encode("utf-8"),
                file_name=f"tags_{query}.txt",
                mime="text/plain",
            )
        else:
            st.info("No tags")

    with t4:
        st.markdown("### #️⃣ Hashtags")
        hts = kw_data.get("hashtags", [])
        if hts:
            st.write(" ".join(hts))
            st.code(" ".join(hts), language=None)
        else:
            st.info("No hashtags")

    with t5:
        st.markdown("### 📺 Top Videos by VPH")
        st.caption("Sorted by your selection — showing all fetched videos")

        # Table view
        df_data = []
        for i, v in enumerate(videos[:30], 1):
            df_data.append({
                "#": i,
                "Title": v["title"][:55],
                "Channel": v["channel"][:20],
                "Duration": v["duration_fmt"],
                "👁 Views": v["views_fmt"],
                "⚡ VPH": v["vph_fmt"],
                "👍": v["likes_fmt"],
                "💬": v["comments_fmt"],
                "📅": v["published_at"][:10],
            })
        df = pd.DataFrame(df_data)
        st.dataframe(df, use_container_width=True, hide_index=True, height=400)

        # Download CSV
        csv_full = pd.DataFrame([{
            "Title": v["title"],
            "Channel": v["channel"],
            "Views": v["views"],
            "VPH": v["vph"],
            "Likes": v["likes"],
            "Comments": v["comments"],
            "Duration": v["duration_fmt"],
            "Published": v["published_at"],
            "URL": v["url"],
        } for v in videos])

        st.download_button(
            "⬇️ Download All (CSV)",
            csv_full.to_csv(index=False).encode("utf-8-sig"),
            file_name=f"videos_{query}.csv",
            mime="text/csv",
        )

        st.markdown("---")
        st.markdown("#### 🎬 Video Cards")

        # Grid view
        for v in videos[:20]:
            with st.container(border=True):
                c1, c2, c3 = st.columns([1, 3, 1])
                with c1:
                    if v.get("thumbnail"):
                        st.image(v["thumbnail"], use_container_width=True)
                with c2:
                    st.markdown(f"**{v['title']}**")
                    st.caption(f"📺 {v['channel']} · 📅 {v['published_at'][:10]} · ⏱️ {v['duration_fmt']}")
                    if v.get("tags"):
                        st.caption("🏷 " + ", ".join(v["tags"][:5]))
                with c3:
                    st.metric("👁", v["views_fmt"])
                    st.metric("⚡ VPH", v["vph_fmt"])

    with t6:
        st.markdown("### 💡 Recommendations")
        recs = kw_data.get("recommendations", [])
        for r in recs:
            st.markdown(f"- {r}")

        st.markdown("---")
        st.markdown(f"**Search Intent:** {kw_data.get('search_intent', '')}")
        st.markdown(f"**Competition:** `{kw_data.get('competition_level', '—')}`")