"""
ui/compare_page.py
- Feature 5: Compare Videos — URL + Upload (mixed)
- Includes Motion & Pacing comparison
"""

import re
import streamlit as st
from datetime import datetime
from core.youtube_api import get_video_details, extract_video_id
from core.ai_analyzer import compare_videos_full, _call_text
from core.gemini_video import analyze_video_file
from core.database import save_entry


def _extract_description(report: str) -> str:
    m = re.search(r"BEGIN_DESCRIPTION\s*(.*?)\s*END_DESCRIPTION", report, re.DOTALL)
    return m.group(1).strip() if m else ""


def _compare_prompt(va: dict, vb: dict, lang="both") -> str:
    lang_instruction = {
        "kh": "Write the ENTIRE report in KHMER language ONLY.",
        "en": "Write the ENTIRE report in ENGLISH language ONLY.",
        "both": "Write a BILINGUAL report (Khmer + English).",
    }.get(lang, "both")

    return f"""You are a world-class YouTube Content Strategist, SEO Analyst, and VIDEO EDITOR.
Compare TWO videos and produce a DETAILED MARKDOWN REPORT.

{lang_instruction}

# Report Structure (MUST follow EXACTLY these 9 sections)

## ១. តារាងប្រៀបធៀប (Quick Comparison Table)
| លក្ខណៈវិនិច្ឆ័យ (Criteria) | Video A | Video B |
|---|---|---|
| Topic | ... | ... |
| Hook | ... | ... |
| Description | ... | ... |
| SEO Tags | ... | ... |
| Links | ... | ... |
| Visual/Audio Quality | ... | ... |
| Shot Duration (avg) | ... | ... |
| Editing Rhythm | ... | ... |
| Pattern Interrupt | ... | ... |
Each cell ends with "**Verdict: ...**"

## ២. ចំណុចឈ្នះ ✅ (My Strengths) — 5-7 points with evidence

## ៣. ចំណុចចាញ់ ❌ (My Weaknesses) — 5-7 points with evidence

## ៤. ⭐ ការវិភាគចលនាប្រៀបធៀប (Motion & Pacing Comparison)
### ៤.១ Shot Duration Comparison
- Video A: មធ្យម X វិនាទី/Shot
- Video B: មធ្យម X វិនាទី/Shot
- **Winner + Reason**

### ៤.២ Editing Rhythm Comparison
- Video A vs Video B
- **Winner + Reason**

### ៤.៣ Boring Zones Comparison
- Video A មាន X ចំណុចធុញ
- Video B មាន X ចំណុចធុញ
- **Winner + Reason**

### ៤.៤ Pattern Interrupt Comparison
- **Winner + Reason**

### ៤.៥ Transition Quality Comparison
- **Winner + Reason**

### ៤.៦ សេចក្តីសន្និដ្ឋាន (Motion Verdict)
តើវីដេអូណាមានចលនាទាក់ទាញជាង? ហេតុអ្វី?

## ៥. Gap Analysis — 3-4 gaps
Format:
* **ចំណុចទី X: <title>**
  * *គូប្រជែងធ្វើ:* ...
  * *គួរធ្វើតាម:* ...
**ត្រូវរួមបញ្ចូល Motion/Pacing Gap ផង**

## ៦. ពិន្ទុប្រៀបធៀប (Comparative Scores 1-10)
| លក្ខណៈវិនិច្ឆ័យ | Video A | Video B |
|---|---|---|
| Content | X/10 | X/10 |
| Editing | X/10 | X/10 |
| Audio | X/10 | X/10 |
| Visual | X/10 | X/10 |
| Hook | X/10 | X/10 |
| SEO | X/10 | X/10 |
| Thumbnail | X/10 | X/10 |
| **Motion/Pacing** | X/10 | X/10 |
| **TOTAL** | **X/80** | **X/80** |

## ៧. ផែនការកែលម្អ (Action Plan) — 5 steps
**ជំហានទី ១ ត្រូវផ្តោតលើការកែចលនាវីដេអូ**:
- កន្លែងណាត្រូវកាត់អោយខ្លី
- កន្លែងណាត្រូវបន្ថែម B-Roll
- កន្លែងណាត្រូវបន្ថែម Motion
- របៀបរៀបចំ Pacing

## ៨. កម្រិតទុកចិត្ត (Confidence) — X% + Reason

## ៩. DESCRIPTION ថ្មីសម្រាប់ VIDEO A
Wrap between BEGIN_DESCRIPTION and END_DESCRIPTION.

# VIDEO A (mine)
- Title: {va.get('title','')}
- Channel: {va.get('channel_title','')}
- Duration: {va.get('duration','')}
- Views: {va.get('views_fmt','')}
- Likes: {va.get('likes_fmt','')}
- Tags: {', '.join(va.get('tags', [])[:20])}
- Description: {va.get('description','')[:1500]}

# VIDEO B (competitor)
- Title: {vb.get('title','')}
- Channel: {vb.get('channel_title','')}
- Duration: {vb.get('duration','')}
- Views: {vb.get('views_fmt','')}
- Likes: {vb.get('likes_fmt','')}
- Tags: {', '.join(vb.get('tags', [])[:20])}
- Description: {vb.get('description','')[:1500]}

Output MARKDOWN only.
"""


def _get_video_source(label: str, key_prefix: str) -> dict | None:
    """UI for getting a video from URL or Upload"""
    st.markdown(f"#### {label}")

    mode = st.radio(
        "Source", ["🔗 URL", "📤 Upload"],
        key=f"{key_prefix}_mode", horizontal=True, label_visibility="collapsed"
    )

    video = {}

    if mode == "🔗 URL":
        url = st.text_input("YouTube URL", key=f"{key_prefix}_url")
        if url:
            vid = extract_video_id(url)
            if vid:
                if st.button("Fetch", key=f"{key_prefix}_fetch"):
                    with st.spinner("Fetching..."):
                        try:
                            video = get_video_details(vid) or {}
                            st.session_state[f"{key_prefix}_video"] = video
                        except Exception as e:
                            st.error(f"Error: {e}")
                video = st.session_state.get(f"{key_prefix}_video", {})
            else:
                st.warning("Invalid URL")
    else:  # Upload
        up = st.file_uploader(
            f"Video file",
            type=["mp4", "mov", "webm", "avi", "mkv"],
            key=f"{key_prefix}_file",
        )
        title = st.text_input("Title (required for upload)", key=f"{key_prefix}_title")
        desc = st.text_area("Description (optional)", height=60, key=f"{key_prefix}_desc")
        tags = st.text_input("Tags (optional, comma separated)", key=f"{key_prefix}_tags")

        if up and title:
            video = {
                "id": key_prefix,
                "title": title,
                "channel_title": "(uploaded)",
                "duration": "—",
                "views_fmt": "—",
                "likes_fmt": "—",
                "comments_fmt": "—",
                "tags": [t.strip() for t in tags.split(",") if t.strip()] if tags else [],
                "description": desc or "",
                "url": "",
                "thumbnail": "",
                "_upload_file": up,
            }
            st.session_state[f"{key_prefix}_video"] = video

    return video if video else None


def render_compare():
    st.subheader("⚖️ Feature 5 — Compare Videos")
    st.caption("Compare URL vs URL, URL vs Upload, or Upload vs Upload — with Motion Analysis")

    c1, c2 = st.columns(2)
    with c1:
        va = _get_video_source("🎬 Video A", "cmpA")
    with c2:
        vb = _get_video_source("🎯 Video B", "cmpB")

    lang = st.selectbox("Report Language", ["both", "kh", "en"],
                        format_func=lambda x: {"both": "🇰🇭+🇬🇧", "kh": "🇰🇭", "en": "🇬🇧"}[x],
                        key="cmp_lang")

    if st.button("🔍 Compare", use_container_width=True, key="cmp_btn"):
        if not va or not vb:
            st.error("Please provide BOTH videos")
            return

        # Case: Both URLs → text-based compare
        if not va.get("_upload_file") and not vb.get("_upload_file"):
            with st.spinner("🧠 AI comparing..."):
                try:
                    prompt = _compare_prompt(va, vb, lang)
                    report = _call_text(prompt, temperature=0.7, max_tokens=8192)
                except Exception as e:
                    st.error(f"AI error: {e}")
                    return
        else:
            # At least one upload → use video file analysis
            with st.spinner("📤 Uploading & analyzing video(s)..."):
                try:
                    prompt = _compare_prompt(va, vb, lang)

                    upload_v = va.get("_upload_file") or vb.get("_upload_file")
                    upload_v.seek(0)
                    file_bytes = upload_v.read()

                    report = analyze_video_file(
                        file_bytes=file_bytes,
                        filename=upload_v.name,
                        prompt=prompt,
                        mime_type=upload_v.type or "video/mp4",
                        temperature=0.7,
                    )
                except Exception as e:
                    st.error(f"Error: {e}")
                    return

        save_entry("compare", f"{va.get('title','A')[:40]} vs {vb.get('title','B')[:40]}",
                   {"a": va, "b": vb, "report": report})
        st.session_state.compare_result = {"a": va, "b": vb, "report": report}
        st.rerun()

    # Render
    res = st.session_state.get("compare_result")
    if not res:
        return

    va, vb, report = res["a"], res["b"], res["report"]

    st.markdown("---")
    c1, c2 = st.columns(2)
    for col, v, label, emoji in [(c1, va, "Video A", "🎬"), (c2, vb, "Video B", "🎯")]:
        with col:
            if v.get("thumbnail"):
                st.image(v["thumbnail"], use_container_width=True)
            st.markdown(f"### {emoji} {label}")
            st.markdown(f"**{v.get('title','')}**")
            st.caption(v.get("channel_title", ""))

    st.markdown("---")
    desc_ready = _extract_description(report)
    if desc_ready:
        st.markdown("### ✨ AI Recommended Description (Video A)")
        st.text_area("📄 Copy here ↓", desc_ready, height=280, key="cmp_copy_desc")
        st.download_button("⬇️ Description .txt", desc_ready.encode("utf-8"),
                           file_name="compare_description.txt", mime="text/plain")

    with st.expander("📄 Copy Full Report (Markdown)", expanded=False):
        st.text_area("Markdown", report, height=300, key="cmp_copy_report")

    st.download_button("⬇️ Report .md", report.encode("utf-8"),
                       file_name=f"compare_{datetime.now():%Y%m%d_%H%M%S}.md",
                       mime="text/markdown")

    st.markdown("---")
    st.markdown(report)