"""
ui/competitor_page.py
- Feature 7: Competitor Spy (Advanced)
"""

import streamlit as st
import pandas as pd
import plotly.express as px
from core.youtube_channel import (
    resolve_channel, get_recent_videos, spy_competitor,
)
from core.database import save_entry
from core.ai_analyzer import (
    analyze_single_thumbnail,
    compare_two_thumbnails,
    analyze_description_strategy,
    analyze_hashtag_strategy,
    analyze_channel_profile,
)


# =====================================================
# Helpers
# =====================================================
def _fmt_hour_12h(h: int) -> str:
    if h == 0:
        return "12:00 AM"
    if h < 12:
        return f"{h}:00 AM"
    if h == 12:
        return "12:00 PM"
    return f"{h-12}:00 PM"


def _country_code_to_name(code: str) -> str:
    codes = {
        "US": "🇺🇸 United States", "KH": "🇰🇭 Cambodia", "TH": "🇹🇭 Thailand",
        "VN": "🇻🇳 Vietnam", "GB": "🇬🇧 United Kingdom", "IN": "🇮🇳 India",
        "JP": "🇯🇵 Japan", "KR": "🇰🇷 South Korea", "FR": "🇫🇷 France",
        "DE": "🇩🇪 Germany", "CN": "🇨🇳 China", "ID": "🇮🇩 Indonesia",
        "PH": "🇵🇭 Philippines", "MY": "🇲🇾 Malaysia", "SG": "🇸🇬 Singapore",
        "AU": "🇦🇺 Australia", "CA": "🇨🇦 Canada", "BR": "🇧🇷 Brazil",
    }
    return codes.get(code.upper(), f"🌍 {code}")


# =====================================================
# Main Render
# =====================================================
def render_competitor():
    st.subheader("🕵️ Competitor Spy")
    st.caption("Advanced competitor analysis — thumbnails, hashtags, descriptions, audience")

    col1, col2, col3 = st.columns([2, 1, 1])
    url = col1.text_input(
        "Competitor Channel URL or @handle",
        placeholder="https://youtube.com/@competitor",
        key="cp_input",
    )
    days = col2.selectbox("Period", [7, 30, 90, 180], index=1,
                          format_func=lambda x: f"Last {x} days", key="cp_days")
    max_v = col3.slider("Videos", 20, 50, 30, step=10, key="cp_max")

    if st.button("🕵️ Spy Now", use_container_width=True, key="cp_btn"):
        if not url.strip():
            st.warning("Please enter a channel URL")
            return

        with st.spinner("Resolving competitor..."):
            channel = resolve_channel(url)
        if not channel:
            st.error("❌ Channel not found")
            return

        with st.spinner(f"Fetching {max_v} videos..."):
            videos = get_recent_videos(channel["id"], channel["uploads_playlist"], max_v)

        with st.spinner("Analyzing..."):
            spy = spy_competitor(channel, videos, days)

        save_entry("competitor", channel["title"],
                   {"channel": channel, "videos": videos, "spy": spy})
        st.session_state.competitor_result = {
            "channel": channel, "videos": videos, "spy": spy
        }
        st.rerun()

    res = st.session_state.get("competitor_result")
    if not res:
        return
    _render(res["channel"], res["videos"], res["spy"])


def _render(channel, videos, spy):
    st.markdown("---")

    # Header
    c1, c2 = st.columns([1, 3])
    with c1:
        if channel.get("thumbnail"):
            st.image(channel["thumbnail"], width=150)
    with c2:
        st.markdown(f"## 🎯 {channel['title']}")
        if channel.get("custom_url"):
            st.caption(f"@{channel['custom_url'].lstrip('@')}")
        st.markdown(channel.get("description", "")[:200])

    # Quick stats
    m1, m2, m3, m4 = st.columns(4)
    m1.metric("👥 Subs", channel["subs_fmt"])
    m2.metric("🎬 Total Videos", channel["videos_fmt"])
    m3.metric("👁 Total Views", channel["views_fmt"])
    m4.metric("📊 Avg/Video", channel["avg_views_fmt"])

    st.markdown("---")

    # Recent activity
    st.markdown(f"### 📅 Last {spy['days']} Days Activity")
    m5, m6, m7 = st.columns(3)
    m5.metric("🆕 Videos Posted", spy["recent_count"])
    m6.metric(
        "⏱ Frequency",
        f"{spy['upload_frequency_days']} days" if spy.get("upload_frequency_days") else "—",
    )
    m7.metric(
        "📊 Recent Avg Views",
        f"{sum(v['views'] for v in spy['recent_videos']) // max(len(spy['recent_videos']), 1):,}"
        if spy["recent_videos"] else "0",
    )

    st.markdown("---")

    # Tabs
    t1, t2, t3, t4, t5, t6, t7, t8 = st.tabs([
        "🔥 Best Performers",
        "🏷 Tag Strategy",
        "📅 Schedule",
        "🖼 Thumbnails + AI",
        "#️⃣ Hashtags + AI",
        "📝 Descriptions + AI",
        "🔑 Channel Keywords",
        "🎯 Channel Profile + AI",
    ])

    # ===== 1. Best Performers =====
    with t1:
        st.markdown("### 🔥 Top 10 Best Performing Videos")
        for i, v in enumerate(spy["best_performers"]):
            with st.container(border=True):
                c1, c2 = st.columns([1, 4])
                with c1:
                    if v.get("thumbnail"):
                        st.image(v["thumbnail"], use_container_width=True)
                with c2:
                    st.markdown(f"**#{i+1}** — {v['title']}")
                    st.caption(f"{v['published_at'][:10]}")
                    m1, m2, m3 = st.columns(3)
                    m1.metric("👁", v["views_fmt"])
                    m2.metric("👍", v["likes_fmt"])
                    m3.metric("💬", v["comments_fmt"])

    # ===== 2. Tag Strategy =====
    with t2:
        st.markdown("### 🏷 Their Top Tags")
        if spy["top_tags"]:
            df = pd.DataFrame(spy["top_tags"], columns=["Tag", "Count"])
            fig = px.bar(df.head(15), x="Count", y="Tag", orientation="h",
                         color="Count", color_continuous_scale="reds",
                         title="Most Used Tags")
            fig.update_layout(height=500, yaxis=dict(autorange="reversed"))
            st.plotly_chart(fig, use_container_width=True)
            st.markdown("**Copy all tags:**")
            st.code(", ".join([t for t, _ in spy["top_tags"]]), language=None)
        else:
            st.info("No tags found")

    # ===== 3. Schedule =====
    with t3:
        st.info(
            f"⏰ YouTube API returns times in **UTC**. "
            f"Your local timezone: **{spy['local_tz_name']}**"
        )

        tz_mode = st.radio(
            "Show times in:",
            [f"🌍 Local ({spy['local_tz_name']})", "🌐 UTC"],
            horizontal=True,
            key="cp_tz_mode",
        )
        show_local = tz_mode.startswith("🌍")

        days_data = spy["top_days_local"] if show_local else spy["top_days_utc"]
        hours_data = spy["top_hours_local"] if show_local else spy["top_hours_utc"]

        c1, c2 = st.columns(2)
        with c1:
            st.markdown("### 📅 Best Days to Post")
            df = pd.DataFrame(days_data, columns=["Day", "Count"])
            if not df.empty:
                fig = px.bar(df, x="Day", y="Count", color="Count",
                             color_continuous_scale="blues")
                fig.update_layout(height=400)
                st.plotly_chart(fig, use_container_width=True)
        with c2:
            st.markdown("### 🕐 Best Hours")
            df = pd.DataFrame(hours_data, columns=["Hour", "Count"])
            if not df.empty:
                df["Time"] = df["Hour"].apply(_fmt_hour_12h)
                df["Hour24"] = df["Hour"].apply(lambda x: f"{x:02d}:00")
                df = df.sort_values("Hour")
                fig = px.bar(df, x="Time", y="Count", color="Count",
                             color_continuous_scale="greens")
                fig.update_layout(
                    height=400,
                    xaxis_title=f"Hour ({'Local ' + spy['local_tz_name'] if show_local else 'UTC'})",
                    yaxis_title="Videos Posted",
                )
                st.plotly_chart(fig, use_container_width=True)

                with st.expander("📋 Hour breakdown table"):
                    df_view = df[["Hour24", "Time", "Count"]].copy()
                    df_view.columns = ["24h", "12h (AM/PM)", "Count"]
                    st.dataframe(df_view, use_container_width=True, hide_index=True)

        st.success(
            f"💡 Peak hours shown in **{spy['local_tz_name'] if show_local else 'UTC'}**. "
            f"Try posting at those hours to compete!"
        )

    # ===== 4. Thumbnails + AI =====
    with t4:
        st.markdown("### 🖼 Thumbnail Analysis + AI")

        if not spy["thumbnails"]:
            st.info("No thumbnails found")
        else:
            st.markdown("#### 🎬 Grid View")
            n_cols = 3
            for i in range(0, len(spy["thumbnails"][:18]), n_cols):
                cols = st.columns(n_cols)
                for j, col in enumerate(cols):
                    if i + j < len(spy["thumbnails"][:18]):
                        t = spy["thumbnails"][i + j]
                        with col:
                            st.image(t["url"], use_container_width=True)
                            st.caption(f"👁 {t['views']:,}")

            sorted_thumbs = sorted(spy["thumbnails"], key=lambda x: x["views"], reverse=True)
            best = sorted_thumbs[0]
            worst = sorted_thumbs[-1]

            st.markdown("---")
            st.markdown("### 🏆 AI Compare: Best vs Worst")
            c1, c2 = st.columns(2)
            with c1:
                st.markdown("**🏆 Best (HIGH views)**")
                st.image(best["url"], use_container_width=True)
                st.caption(best["title"][:60])
                st.metric("👁", f"{best['views']:,}")
            with c2:
                st.markdown("**📉 Worst (LOW views)**")
                st.image(worst["url"], use_container_width=True)
                st.caption(worst["title"][:60])
                st.metric("👁", f"{worst['views']:,}")

            if st.button("🤖 Analyze WHY one wins (AI)", key="cp_ai_thumb_cmp",
                         use_container_width=True):
                with st.spinner("AI is comparing thumbnails..."):
                    result = compare_two_thumbnails(best, worst)
                st.session_state.cp_thumb_cmp = result

            if st.session_state.get("cp_thumb_cmp"):
                st.markdown(st.session_state.cp_thumb_cmp)

            st.markdown("---")
            st.markdown("### 🔍 Analyze Single Thumbnail")
            options = {f"{i+1}. {t['title'][:60]} ({t['views']:,} views)": t
                       for i, t in enumerate(spy["thumbnails"][:15])}
            sel = st.selectbox("Choose thumbnail", list(options.keys()),
                               key="cp_thumb_single_sel")

            if st.button("🤖 AI Analyze This Thumbnail", key="cp_ai_thumb_single",
                         use_container_width=True):
                t = options[sel]
                with st.spinner("AI analyzing..."):
                    result = analyze_single_thumbnail(t["url"], t["title"], t["views"])
                st.session_state.cp_thumb_single = result

            if st.session_state.get("cp_thumb_single"):
                st.markdown(st.session_state.cp_thumb_single)

    # ===== 5. Hashtags + AI =====
    with t5:
        st.markdown("### #️⃣ Hashtag Analysis")

        top_hashtags = spy.get("top_hashtags", [])
        title_hashtags = spy.get("title_hashtags", [])
        videos_with_hashtags = spy.get("videos_with_hashtags", 0)
        hashtag_per_video = spy.get("hashtag_per_video", {})
        total_videos = len(videos)

        # Metrics
        c1, c2, c3 = st.columns(3)
        c1.metric("Videos with Hashtags", f"{videos_with_hashtags} / {total_videos}")
        c2.metric("Unique Hashtags", len(top_hashtags))
        c3.metric("Total Uses", sum(n for _, n in top_hashtags))

        st.markdown("---")

        if top_hashtags:
            # Chart
            st.markdown("### 📊 Most Used Hashtags")
            df = pd.DataFrame(top_hashtags, columns=["Hashtag", "Count"])
            df["Hashtag"] = "#" + df["Hashtag"]
            df["% of Videos"] = (df["Count"] / total_videos * 100).round(1).astype(str) + "%"

            fig = px.bar(df.head(20), x="Count", y="Hashtag", orientation="h",
                         color="Count", color_continuous_scale="purples",
                         title=f"Hashtag Usage ({total_videos} videos)")
            fig.update_layout(height=500, yaxis=dict(autorange="reversed"))
            st.plotly_chart(fig, use_container_width=True)

            # Table
            st.dataframe(df, use_container_width=True, hide_index=True)

            # Copy + Download
            hashtags_str = " ".join([f"#{h}" for h, _ in top_hashtags])
            st.text_area("Copy all hashtags ↓", hashtags_str,
                         height=80, key="cp_hash_copy")

            st.download_button(
                "⬇️ Download Hashtags",
                hashtags_str.encode("utf-8"),
                file_name=f"hashtags_{channel['id']}.txt",
                mime="text/plain",
            )
        else:
            st.info(
                f"📌 **This channel hasn't used hashtags in the last "
                f"{total_videos} videos.**"
            )
            st.caption(
                "Hashtags appear in the video Description or Title. "
                "If the channel doesn't include them, they can't be extracted."
            )

        # Title hashtags
        if title_hashtags:
            st.markdown("---")
            st.markdown("### 📛 Hashtags in Titles")
            st.code(" ".join(set(title_hashtags)), language=None)

        # Per-video breakdown
        if any(hashtag_per_video.values()):
            st.markdown("---")
            st.markdown("### 🎬 Hashtags Per Video")
            for v in videos[:15]:
                hs = hashtag_per_video.get(v["id"], [])
                if not hs:
                    continue
                with st.expander(f"📹 {v['title'][:60]} — {len(hs)} hashtags"):
                    st.markdown(" ".join([f"`#{h}`" for h in hs]))

        # AI Analysis
        if top_hashtags:
            st.markdown("---")
            if st.button("🤖 AI Analyze Hashtag Strategy", key="cp_ai_hash",
                         use_container_width=True):
                with st.spinner("AI analyzing..."):
                    result = analyze_hashtag_strategy(top_hashtags, title_hashtags)
                st.session_state.cp_hash_ai = result

            if st.session_state.get("cp_hash_ai"):
                st.markdown(st.session_state.cp_hash_ai)

    # ===== 6. Descriptions + AI =====
    with t6:
        st.markdown("### 📝 Description Strategy")

        c1, c2 = st.columns(2)
        c1.metric("📏 Avg Description Length", f"{spy['avg_desc_length']} chars")
        c2.metric("🔗 Unique Link Domains", len(spy["top_link_domains"]))

        st.markdown("---")
        st.markdown("#### 📄 Sample Descriptions (raw)")
        for v in videos[:3]:
            desc = v.get("description", "") or "(empty)"
            with st.expander(f"📌 {v['title'][:60]} — {len(desc)} chars"):
                st.text_area("Description", desc[:1500], height=200,
                             key=f"cp_desc_{v['id']}", disabled=True)

        st.markdown("---")
        if st.button("🤖 AI Analyze Description Formula", key="cp_ai_desc",
                     use_container_width=True):
            with st.spinner("AI analyzing descriptions..."):
                result = analyze_description_strategy(videos)
            st.session_state.cp_desc_ai = result

        if st.session_state.get("cp_desc_ai"):
            st.markdown(st.session_state.cp_desc_ai)

    # ===== 7. Channel Keywords =====
    with t7:
        st.markdown("### 🔑 Channel Keywords (YouTube Studio)")
        kws = spy.get("channel_keywords", [])
        if kws:
            st.success(f"**{len(kws)} keywords found**")
            kws_str = ", ".join(kws)
            st.text_area("Copy keywords ↓", kws_str, height=150, key="cp_kws_copy")
            for k in kws:
                st.markdown(f"- `{k}`")
        else:
            st.info("⚠️ No public channel keywords visible via API")

    # ===== 8. Channel Profile + AI =====
    with t8:
        st.markdown("### 🎯 Channel Profile + AI Analysis")

        c1, c2 = st.columns(2)

        with c1:
            st.markdown("#### 📋 From YouTube API")

            country_code = channel.get("country", "")
            country_name = _country_code_to_name(country_code) if country_code else "❌ Not set by channel"

            st.markdown(f"**🌍 Country:** {country_name}")
            if not country_code:
                st.caption("Channel មិនបាន Set Country ក្នុង YouTube Studio")

            st.markdown(f"**📅 Created:** {channel.get('published_at', '')[:10]}")

            default_lang = channel.get("default_language", "")
            st.markdown(f"**🗣️ Default Language:** {default_lang or 'not set'}")

            st.markdown(f"**🔗 Handle:** @{channel.get('custom_url', '').lstrip('@')}")
            st.markdown(f"**🆔 Channel ID:** `{channel['id']}`")

        with c2:
            st.markdown("#### 📊 Video Categories (from their videos)")
            cat_breakdown = spy.get("category_breakdown", [])
            if cat_breakdown:
                from core.youtube_api import get_video_categories
                try:
                    cat_map = {c["id"]: c["title"] for c in get_video_categories()}
                except Exception:
                    cat_map = {}

                df = pd.DataFrame([
                    {"Category": cat_map.get(cid, f"Category {cid}"), "Count": n}
                    for cid, n in cat_breakdown
                ])
                st.dataframe(df, use_container_width=True, hide_index=True)

                if len(df) > 1:
                    fig = px.pie(df, names="Category", values="Count",
                                 title="Videos by Category")
                    st.plotly_chart(fig, use_container_width=True)
            else:
                st.caption("No category data available")

        st.markdown("---")
        if st.button("🤖 AI Analyze Channel Profile + Audience",
                     key="cp_ai_profile", use_container_width=True):
            with st.spinner("AI analyzing channel profile (30-60s)..."):
                result = analyze_channel_profile(channel, videos)
            st.session_state.cp_profile_ai = result

        if st.session_state.get("cp_profile_ai"):
            st.markdown(st.session_state.cp_profile_ai)