"""
ui/analyze_page.py
- Feature 4: Video Analyzer — Upload OR YouTube URL
- Includes VIDEO MOTION & PACING analysis
"""

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 analyze_video_full
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 _build_report_prompt(title="", desc="", tags="", niche="", lang="both"):
    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: For every section title and bullet, "
            "write Khmer first, then English in parentheses."
        ),
    }.get(lang, "both")

    return f"""You are a world-class YouTube Content Strategist, SEO Analyst, and VIDEO EDITOR.
Watch the ENTIRE uploaded video (visuals + audio + motion + pacing) and produce a DETAILED MARKDOWN REPORT.

{lang_instruction}

# Report Structure (MUST follow EXACTLY these 9 sections)

## ១. ទិដ្ឋភាពទូទៅ (Overview)
- 3 Suggested Titles (in video's original language)
- Content Type / Niche
- Target Audience
- Total Duration + Pacing Analysis

## ២. ចំណុចខ្លាំង ✅ (Strengths) — 5-7 points with timestamps

## ៣. ចំណុចខ្សោយ ⚠️ (Weaknesses) — 5-7 points with timestamps

## ៤. ⭐ ការវិភាគចលនាវីដេអូ (Video Motion & Pacing Analysis)
នេះជាផ្នែកសំខាន់ — ត្រូវវិភាគលម្អិត:

### ៤.១ រយៈពេលនៃការផ្លាស់ប្តូរ (Shot Duration)
- មធ្យមប៉ុន្មានវិនាទី/រូប ឬ /Scene?
- រូបណាដែលនៅយូរពេក (> 10 វិនាទី)?
- រូបណាដែលលឿនពេក (< 1 វិនាទី)?
- តើ Shot Duration សមស្របនឹងប្រភេទ Content ឬអត់?

### ៤.២ ចង្វាក់នៃការកាត់ត (Editing Rhythm)
- តើ Cut/Transition លឿន ឬយឺត?
- ចំណុចណាដែល Pacing ល្អ?
- ចំណុចណាដែល Pacing ខូច?
- តើមាន Pattern Interrupt (ចលនា/សំឡេងប្តូរ) គ្រប់គ្រាន់ទេ?

### ៤.៣ ចំណុចដែលអ្នកមើលអាចធុញ (Boring Risk Zones)
រាយចំណុចដែល Static ពេក ជាមួយ Timestamp ជាក់លាក់:
- [MM:SS] — មូលហេតុ + របៀបកែ
- [MM:SS] — មូលហេតុ + របៀបកែ
- [MM:SS] — មូលហេតុ + របៀបកែ

### ៤.៤ ពេលវេលាល្អបំផុតសម្រាប់ផ្លាស់ប្តូរ (Optimal Cut Timing)
ផ្អែកលើប្រភេទវីដេអូនេះ ណែនាំ:
- **Intro (0-30s)**: គួរកាត់រៀងរាល់ X វិនាទី
- **Main Content**: គួរកាត់រៀងរាល់ X វិនាទី
- **Slow/Emotional Parts**: គួរកាត់រៀងរាល់ X វិនាទី
- **Pattern Interrupt**: គួរដាក់រៀងរាល់ X វិនាទី

### ៤.៥ ការផ្លាស់ប្តូរ Transition Quality
- តើ Transition រលូន ឬរឹង?
- តើមាន Jump Cut ដែលមើលទៅអាក្រក់ទេ?
- តើ Zoom/Pan/Text Animation ប្រើបានល្អទេ?

### ៤.៦ ពិន្ទុចលនាវីដេអូ (Motion Score)
| លក្ខណៈវិនិច្ឆ័យ | ពិន្ទុ (x/10) | មតិយោបល់ |
|---|---|---|
| Shot Duration | X/10 | ... |
| Editing Rhythm | X/10 | ... |
| Pattern Interrupt | X/10 | ... |
| Transition Quality | X/10 | ... |
| **សរុបចលនា** | **X/40** | **...** |

## ៥. ការវិភាគលម្អិត (Detailed Criteria) — Table
Rows: Content, Editing, Audio, Visual, Hook (30s), SEO, Thumbnail, Viral Potential
Each row ends with "**Verdict: ...**"

## ៦. ពិន្ទុ (Detailed Scoring) — Table: Criteria | Score (x/10) | Comment

## ៧. អនុសាសន៍កែលម្អ (Actionable Improvement Plan) — 5 steps
**សំខាន់**: ជំហានទី ១ ត្រូវផ្តោតលើ **ការកែចលនាវីដេអូ** អោយទាក់ទាញជាងនេះ:
- កន្លែងណាដែលត្រូវកាត់អោយខ្លី
- កន្លែងណាដែលត្រូវបន្ថែម B-Roll
- កន្លែងណាដែលត្រូវបន្ថែម Motion/Animation
- របៀបរៀបចំ Pacing អោយសមស្រប

## ៨. កម្រិតទុកចិត្ត (Confidence) — X% + Reason

## ៩. DESCRIPTION ថ្មី (Ready-to-Copy Description)
Write in the SAME LANGUAGE AS THE VIDEO.
Wrap between BEGIN_DESCRIPTION and END_DESCRIPTION.

# Extra Metadata
- Title hint: {title or '(none)'}
- Description hint: {desc[:500] if desc else '(none)'}
- Tags hint: {tags or '(none)'}
- Niche: {niche or 'auto-detect'}

Output MARKDOWN only.
"""


def _build_url_prompt(video: dict, niche: str = "", lang="both") -> str:
    """For YouTube URL analysis — text-based (metadata)"""
    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.
Analyze this YouTube video and produce a DETAILED MARKDOWN REPORT.

{lang_instruction}

# Report Structure (MUST follow EXACTLY these 9 sections)

## ១. ទិដ្ឋភាពទូទៅ (Overview)
- 3 Suggested Titles
- Content Type / Niche
- Target Audience
- Pacing & Duration

## ២. ចំណុចខ្លាំង ✅ (Strengths) — 5-7 points

## ៣. ចំណុចខ្សោយ ⚠️ (Weaknesses) — 5-7 points

## ៤. ⭐ ការវិភាគចលនាវីដេអូ (Video Motion & Pacing) — estimated
### ៤.១ Shot Duration Estimate
### ៤.២ Editing Rhythm Estimate
### ៤.៣ Boring Risk Zones (based on metadata)
### ៤.៤ Optimal Cut Timing
### ៤.៥ Transition Quality (estimated)
### ៤.៦ Motion Score Table

## ៥. ការវិភាគលម្អិត (Detailed Criteria) — Table
## ៦. ពិន្ទុ (Scoring) — Table
## ៧. អនុសាសន៍កែលម្អ (Action Plan) — 5 steps
## ៨. កម្រិតទុកចិត្ត (Confidence)
## ៩. DESCRIPTION ថ្មី
Wrap between BEGIN_DESCRIPTION and END_DESCRIPTION.

# Video Info
- Title: {video.get('title','')}
- Channel: {video.get('channel_title','')}
- Duration: {video.get('duration','')}
- Views: {video.get('views_fmt','')}
- Likes: {video.get('likes_fmt','')}
- Comments: {video.get('comments_fmt','')}
- Published: {video.get('published_at','')}
- Tags: {', '.join(video.get('tags', [])[:30])}
- Description: {video.get('description','')[:2000]}
- Niche: {niche or 'auto-detect'}

Output MARKDOWN only.
"""


def render_analyze():
    st.subheader("🧠 Feature 4 — Video Analyzer (AI)")
    st.caption("Analyze via Upload Video OR YouTube URL — with Motion & Pacing analysis")

    tab_url, tab_upload = st.tabs(["🔗 YouTube URL", "📤 Upload Video"])

    # =====================================================
    # TAB 1: YouTube URL
    # =====================================================
    with tab_url:
        col1, col2 = st.columns([3, 1])
        url = col1.text_input("YouTube URL", placeholder="https://youtube.com/watch?v=...", key="an_url")
        lang = col2.selectbox("Report Language", ["both", "kh", "en"],
                              format_func=lambda x: {"both": "🇰🇭+🇬🇧", "kh": "🇰🇭", "en": "🇬🇧"}[x],
                              key="an_lang_url")
        niche = st.text_input("Niche (optional)", key="an_niche_url")

        if st.button("🔬 Analyze URL", use_container_width=True, key="an_btn_url"):
            vid = extract_video_id(url)
            if not vid:
                st.error("❌ Invalid URL")
                return
            with st.spinner("Fetching video..."):
                try:
                    video = get_video_details(vid)
                except Exception as e:
                    st.error(f"Error: {e}")
                    return
            if not video:
                st.error("Video not found")
                return

            with st.spinner("🧠 AI generating report..."):
                try:
                    prompt = _build_url_prompt(video, niche, lang)
                    report = analyze_video_full(video, niche, lang) if False else None
                    # Use custom prompt via gemini
                    from core.ai_analyzer import _call_text
                    report = _call_text(prompt, temperature=0.7, max_tokens=8192)
                except Exception as e:
                    st.error(f"AI error: {e}")
                    return

            save_entry("analyze", video["title"], {"video": video, "report": report},
                       url=video["url"])
            st.session_state.analyze_result = {"video": video, "report": report}
            st.rerun()

    # =====================================================
    # TAB 2: Upload Video
    # =====================================================
    with tab_upload:
        st.info("📤 Upload a video file (MP4, MOV, WebM). AI will watch the entire video with motion analysis.")

        up = st.file_uploader(
            "Choose video file",
            type=["mp4", "mov", "webm", "avi", "mkv"],
            key="an_upload_file",
        )

        c1, c2 = st.columns([3, 1])
        title_hint = c1.text_input("Title hint (optional)", key="an_up_title")
        lang2 = c2.selectbox("Report Language", ["both", "kh", "en"],
                             format_func=lambda x: {"both": "🇰🇭+🇬🇧", "kh": "🇰🇭", "en": "🇬🇧"}[x],
                             key="an_lang_up")
        desc_hint = st.text_area("Description hint (optional)", height=80, key="an_up_desc")
        tags_hint = st.text_input("Tags hint (comma separated, optional)", key="an_up_tags")
        niche2 = st.text_input("Niche (optional)", key="an_up_niche")

        if st.button("🎬 Analyze Uploaded Video", use_container_width=True, key="an_btn_up"):
            if not up:
                st.error("Please upload a video file first")
                return

            file_bytes = up.read()
            size_mb = len(file_bytes) / (1024 * 1024)
            if size_mb > 1500:
                st.error(f"File too large ({size_mb:.1f}MB). Max ~1.5GB")
                return

            with st.spinner(f"📤 Uploading {size_mb:.1f}MB + analyzing motion..."):
                try:
                    prompt = _build_report_prompt(title_hint, desc_hint, tags_hint, niche2, lang2)
                    report = analyze_video_file(
                        file_bytes=file_bytes,
                        filename=up.name,
                        prompt=prompt,
                        mime_type=up.type or "video/mp4",
                        temperature=0.7,
                        max_tokens=8192,
                    )
                except Exception as e:
                    st.error(f"❌ Error: {e}")
                    return

            video_meta = {
                "id": "upload",
                "title": title_hint or up.name,
                "channel_title": "(uploaded)",
                "url": "",
                "duration": "—",
                "views_fmt": "—",
                "likes_fmt": "—",
                "comments_fmt": "—",
                "thumbnail": "",
                "published_at": datetime.now().isoformat(),
            }
            save_entry("analyze", video_meta["title"], {"video": video_meta, "report": report})
            st.session_state.analyze_result = {"video": video_meta, "report": report}
            st.rerun()

    # =====================================================
    # Render Result
    # =====================================================
    res = st.session_state.get("analyze_result")
    if not res:
        return

    video = res["video"]
    report = res["report"]

    st.markdown("---")

    c1, c2 = st.columns([1, 3])
    with c1:
        if video.get("thumbnail"):
            st.image(video["thumbnail"], use_container_width=True)
    with c2:
        st.markdown(f"### {video['title']}")
        st.caption(f"{video.get('channel_title','')} • {video.get('duration','')}")
        m1, m2, m3 = st.columns(3)
        m1.metric("👁", video.get("views_fmt", "—"))
        m2.metric("👍", video.get("likes_fmt", "—"))
        m3.metric("💬", video.get("comments_fmt", "—"))

    # Description copy box
    desc_ready = _extract_description(report)
    if desc_ready:
        st.markdown("---")
        st.markdown("### ✨ AI Recommended Description")
        st.text_area("📄 Copy here ↓", desc_ready, height=280, key="an_copy_desc")
        st.download_button("⬇️ Download .txt", desc_ready.encode("utf-8"),
                           file_name=f"description_{video.get('id','v')}.txt",
                           mime="text/plain")

    with st.expander("📄 Copy Full Report (Markdown)", expanded=False):
        st.text_area("Markdown", report, height=300, key="an_copy_report")

    st.download_button("⬇️ Download Report .md", report.encode("utf-8"),
                       file_name=f"report_{video.get('id','v')}.md",
                       mime="text/markdown")

    st.markdown("---")
    st.markdown(report)

    if video.get("url"):
        with st.expander("▶️ Preview video"):
            st.video(video["url"])