"""
core/ai_analyzer.py
- Google Gemini AI with multi-key + multi-model + bilingual reports
- Supports user-provided keys (BYOK)
"""

import os
import re
import json
import requests as _requests
from datetime import datetime
from dotenv import load_dotenv
from google import genai

load_dotenv()

# =====================================================
# Models (2026)
# =====================================================
MODELS = [
    "gemini-3.8-flash",
    "gemini-3.7-flash",
    "gemini-3.6-flash",
    "gemini-3.5-flash",
    "gemini-2.5-flash",
    "gemini-2.0-flash",
]


# =====================================================
# Multi-Key Loading (User Keys → .env Fallback)
# =====================================================
def _load_keys() -> list[str]:
    """Load keys — user keys first, then .env fallback"""
    # Priority 1: User keys
    try:
        from core.user_keys import load_user_keys
        user = load_user_keys()
        user_gm = [k for k in (user.get("gemini_keys") or []) if k and k.strip()]
        if user_gm:
            return user_gm
    except Exception:
        pass

    # Priority 2: .env keys
    keys = []
    multi = os.getenv("GEMINI_API_KEYS", "")
    if multi:
        keys.extend([k.strip() for k in multi.split(",") if k.strip()])

    i = 1
    while True:
        k = os.getenv(f"GEMINI_API_KEY_{i}")
        if not k:
            break
        keys.append(k.strip())
        i += 1

    single = os.getenv("GEMINI_API_KEY", "")
    if single and single.strip() and single.strip() not in keys:
        keys.append(single.strip())

    seen, unique = set(), []
    for k in keys:
        if k not in seen:
            seen.add(k)
            unique.append(k)
    return unique


_KEYS = _load_keys()
_current_key_idx = 0
_clients: dict[str, genai.Client] = {}


def reload_keys():
    """Reload keys (called after user saves new keys)"""
    global _KEYS, _current_key_idx, _clients
    _KEYS = _load_keys()
    _current_key_idx = 0
    _clients = {}


def get_keys_status() -> dict:
    return {
        "total": len(_KEYS),
        "current": _current_key_idx,
        "masked": [(k[:6] + "..." + k[-4:]) if len(k) > 12 else "***" for k in _KEYS],
        "models": MODELS,
    }


def _get_client(key: str) -> genai.Client:
    if key not in _clients:
        _clients[key] = genai.Client(api_key=key)
    return _clients[key]


def _rotate_key() -> bool:
    global _current_key_idx
    if len(_KEYS) <= 1:
        return False
    _current_key_idx = (_current_key_idx + 1) % len(_KEYS)
    return True


def _is_rate_error(e):
    s = str(e).lower()
    return any(x in s for x in ["429", "quota", "rate limit", "resource_exhausted"])


def _is_model_error(e):
    s = str(e).lower()
    return any(x in s for x in ["404", "not_found", "not found", "not supported"])


def _is_auth_error(e):
    s = str(e).lower()
    return any(x in s for x in ["401", "403", "invalid api key", "api key not valid"])


# =====================================================
# Raw text call
# =====================================================
def _call_text(prompt: str, temperature: float = 0.7, max_tokens: int = 8192) -> str:
    if not _KEYS:
        raise RuntimeError("No Gemini API keys. Add in ⚙️ Settings or .env")

    errors = []
    for _ in range(len(_KEYS)):
        key = _KEYS[_current_key_idx]
        try:
            client = _get_client(key)
        except Exception as e:
            errors.append(f"client init key#{_current_key_idx+1}: {e}")
            _rotate_key()
            continue

        for model in MODELS:
            try:
                resp = client.models.generate_content(
                    model=model,
                    contents=prompt,
                    config={
                        "temperature": temperature,
                        "max_output_tokens": max_tokens,
                    },
                )
                return resp.text or ""
            except Exception as e:
                errors.append(f"[k#{_current_key_idx+1}/{model}] {str(e)[:120]}")
                if _is_model_error(e):
                    continue
                elif _is_rate_error(e) or _is_auth_error(e):
                    break
                else:
                    continue
        if not _rotate_key():
            break

    raise RuntimeError("All Gemini keys/models failed:\n" + "\n".join(errors[-6:]))


# =====================================================
# JSON call
# =====================================================
def _clean_json(text: str) -> str:
    text = (text or "").strip()
    text = re.sub(r"^```(?:json)?\s*", "", text)
    text = re.sub(r"\s*```$", "", text)
    return text.strip()


def _call_json(prompt: str, temperature: float = 0.7) -> dict:
    if not _KEYS:
        raise RuntimeError("No Gemini API keys.")
    errors = []
    for _ in range(len(_KEYS)):
        key = _KEYS[_current_key_idx]
        try:
            client = _get_client(key)
        except Exception as e:
            errors.append(str(e))
            _rotate_key()
            continue
        for model in MODELS:
            try:
                resp = client.models.generate_content(
                    model=model,
                    contents=prompt,
                    config={
                        "temperature": temperature,
                        "response_mime_type": "application/json",
                    },
                )
                raw = resp.text or ""
                try:
                    return json.loads(_clean_json(raw))
                except Exception:
                    return {"raw": raw}
            except Exception as e:
                errors.append(f"[{model}] {str(e)[:120]}")
                if _is_model_error(e):
                    continue
                elif _is_rate_error(e) or _is_auth_error(e):
                    break
                else:
                    continue
        if not _rotate_key():
            break
    raise RuntimeError("All Gemini keys/models failed:\n" + "\n".join(errors[-6:]))


# =====================================================
# Helper: video context
# =====================================================
def _video_context(v: dict, label: str = "") -> str:
    prefix = f"{label}:\n" if label else ""
    return f"""{prefix}
- Title: {v.get('title','')}
- Channel: {v.get('channel_title','')}
- URL: {v.get('url','')}
- Published: {v.get('published_at','')}
- Duration: {v.get('duration','')}
- Views: {v.get('views_fmt','')} ({v.get('views',0)})
- Likes: {v.get('likes_fmt','')} ({v.get('likes',0)})
- Comments: {v.get('comments_fmt','')} ({v.get('comments',0)})
- Category ID: {v.get('category_id','')}
- Language: {v.get('default_language') or v.get('default_audio_language') or 'unknown'}
- Tags: {', '.join(v.get('tags', [])[:30]) or '(none)'}
- Description: {v.get('description','')[:2500] or '(empty)'}
- Topics: {', '.join(v.get('topics', [])) or '(none)'}
""".strip()


# =====================================================
# Feature 4: Full Detailed Video Analysis Report
# =====================================================
def analyze_video_full(video: dict, niche: str = "", language: str = "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: For EVERY section title and bullet, "
            "write Khmer first, then English in parentheses or below."
        ),
    }.get(language, "both")

    prompt = f"""You are a world-class YouTube Content Strategist, SEO Analyst, and VIDEO EDITOR.
Analyze the following YouTube video and produce a DETAILED MARKDOWN REPORT.

{lang_instruction}

# Report Structure (MUST follow EXACTLY these 9 sections)

## ១. ទិដ្ឋភាពទូទៅ (Overview)
- 3 Suggested Titles (video's original language)
- Content Type / Niche
- Target Audience
- Pacing & Duration

## ២. ចំណុចខ្លាំង ✅ (Strengths) — 5-7 points with timestamps

## ៣. ចំណុចខ្សោយ ⚠️ (Weaknesses) — 5-7 points with timestamps

## ៤. ⭐ ការវិភាគចលនាវីដេអូ (Video Motion & Pacing)
### ៤.១ Shot Duration
### ៤.២ Editing Rhythm
### ៤.៣ Boring Risk Zones (with timestamps)
### ៤.៤ Optimal Cut Timing
### ៤.៥ Transition Quality
### ៤.៦ Motion Score Table (X/40)

## ៥. ការវិភាគលម្អិត (Detailed Criteria) — Table
## ៦. ពិន្ទុ (Scoring) — Table
## ៧. អនុសាសន៍កែលម្អ (Action Plan) — 5 steps
## ៨. កម្រិតទុកចិត្ត (Confidence)
## ៩. DESCRIPTION ថ្មី — Wrap between BEGIN_DESCRIPTION and END_DESCRIPTION

# Video Data

{_video_context(video)}

Niche hint: {niche or 'auto-detect'}

Output MARKDOWN only. Be specific, technical, and actionable.
"""
    return _call_text(prompt, temperature=0.75, max_tokens=8192)


# =====================================================
# Feature 5: Full Detailed Compare Report
# =====================================================
def compare_videos_full(v1: dict, v2: dict, language: str = "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(language, "both")

    prompt = f"""You are a world-class YouTube Content Strategist and SEO Analyst.
Compare these TWO YouTube videos and produce a DETAILED MARKDOWN REPORT.

{lang_instruction}

# Report Structure (9 sections)

## ១. តារាងប្រៀបធៀបរហ័ស (Quick Comparison Table)
## ២. ចំណុចឈ្នះ ✅ (My Strengths) — 5-7 points
## ៣. ចំណុចចាញ់ ❌ (My Weaknesses) — 5-7 points
## ៤. ⭐ ការវិភាគចលនាប្រៀបធៀប (Motion & Pacing Comparison)
### ៤.១ Shot Duration  ### ៤.២ Editing Rhythm  ### ៤.៣ Boring Zones
### ៤.៤ Pattern Interrupt  ### ៤.៥ Transition Quality  ### ៤.៦ Motion Verdict
## ៥. Gap Analysis — 3-4 gaps
## ៦. ពិន្ទុប្រៀបធៀប (Scores 1-10) — Table
## ៧. ផែនការកែលម្អ (Action Plan) — 5 steps
## ៨. កម្រិតទុកចិត្ត (Confidence)
## ៩. DESCRIPTION ថ្មី — Wrap between BEGIN_DESCRIPTION and END_DESCRIPTION

# Video A (MY VIDEO)
{_video_context(v1, "VIDEO A")}

# Video B (COMPETITOR)
{_video_context(v2, "VIDEO B")}

Output MARKDOWN only.
"""
    return _call_text(prompt, temperature=0.7, max_tokens=8192)


# =====================================================
# Legacy quick JSON analysis
# =====================================================
def analyze_video(video: dict, niche: str = "") -> dict:
    prompt = f"""Return JSON only:
{{"score": <0-100>, "summary": "<2-3 sentences>",
"strengths": ["..."], "weaknesses": ["..."],
"recommended_titles": ["..."], "recommended_description": "...",
"recommended_tags": ["..."], "recommended_hashtags": ["..."],
"keywords": ["..."], "long_tail_keywords": ["..."],
"content_ideas": ["..."]}}

{_video_context(video)}
Niche: {niche or 'auto'}
"""
    return _call_json(prompt)


def generate_keywords(query: str) -> dict:
    prompt = f"""Return JSON only:
{{"keywords": ["...15 short"], "long_tail_keywords": ["...10"],
"tags": ["...20"], "hashtags": ["#...15"],
"recommendations": ["...6"], "search_intent": "...",
"competition_level": "low|medium|high"}}

Topic: {query}
"""
    return _call_json(prompt, temperature=0.8)


def compare_videos(v1: dict, v2: dict) -> dict:
    prompt = f"""Return JSON only:
{{"winner": "A|B|tie", "reason": "...",
"video_a_score": <0-100>, "video_b_score": <0-100>,
"video_a_pros": ["..."], "video_a_cons": ["..."],
"video_b_pros": ["..."], "video_b_cons": ["..."],
"improvements_for_a": ["..."], "improvements_for_b": ["..."]}}

VIDEO A:
{_video_context(v1)}

VIDEO B:
{_video_context(v2)}
"""
    return _call_json(prompt, temperature=0.5)


# =====================================================
# Report saver
# =====================================================
def save_report(content: str, prefix: str = "report") -> str:
    from pathlib import Path
    d = Path.home() / ".yt_analyzer_pro" / "reports"
    d.mkdir(parents=True, exist_ok=True)
    ts = int(datetime.now().timestamp())
    fn = d / f"{prefix}_{ts}.md"
    fn.write_text(content, encoding="utf-8", errors="replace")
    return str(fn)


# =====================================================
# IMAGE / MULTIMODAL ANALYSIS
# =====================================================
def _call_multimodal(parts: list, temperature: float = 0.6, max_tokens: int = 4096) -> str:
    if not _KEYS:
        raise RuntimeError("No Gemini API keys")

    errors = []
    for _ in range(len(_KEYS)):
        key = _KEYS[_current_key_idx]
        try:
            client = _get_client(key)
        except Exception as e:
            errors.append(str(e))
            _rotate_key()
            continue

        for model in MODELS:
            try:
                resp = client.models.generate_content(
                    model=model,
                    contents=parts,
                    config={
                        "temperature": temperature,
                        "max_output_tokens": max_tokens,
                    },
                )
                return resp.text or ""
            except Exception as e:
                errors.append(f"[{model}] {str(e)[:120]}")
                if _is_model_error(e):
                    continue
                elif _is_rate_error(e) or _is_auth_error(e):
                    break
                else:
                    continue
        if not _rotate_key():
            break

    raise RuntimeError("Multimodal call failed:\n" + "\n".join(errors[-6:]))


def _download_image(url: str) -> bytes | None:
    try:
        r = _requests.get(url, timeout=15)
        r.raise_for_status()
        return r.content
    except Exception:
        return None


# =====================================================
# THUMBNAIL ANALYSIS
# =====================================================
def analyze_single_thumbnail(image_url: str, title: str, views: int) -> str:
    from google.genai import types

    img_bytes = _download_image(image_url)
    if not img_bytes:
        return "❌ Could not download thumbnail image."

    prompt = f"""Analyze this YouTube thumbnail image carefully.
Base your analysis ONLY on what you SEE in the image. Do NOT invent anything.

# Context (real data)
- Video Title: {title}
- Views: {views:,}

Return MARKDOWN with these sections:

## ១. អ្វីដែលឃើញ (What I Actually See)
## ២. ចំណុចល្អ ✅ (Strengths)
## ៣. ចំណុចខ្សោយ ⚠️ (Weaknesses)
## ៤. ពិន្ទុ (Score X/10) — Table
## ៥. ដំបូន្មាន ៣ ចំណុច (3 Improvements)
"""
    try:
        return _call_multimodal([
            types.Part.from_bytes(data=img_bytes, mime_type="image/jpeg"),
            prompt,
        ])
    except Exception as e:
        return f"❌ AI error: {e}"


def compare_two_thumbnails(best: dict, worst: dict) -> str:
    from google.genai import types

    b1 = _download_image(best["url"])
    b2 = _download_image(worst["url"])
    if not b1 or not b2:
        return "❌ Could not download one or both thumbnails."

    prompt = f"""Compare these TWO YouTube thumbnails from the SAME channel.
Explain WHY one gets more clicks than the other.

# Thumbnail A (HIGHER Views: {best['views']:,})
Title: {best['title']}

# Thumbnail B (LOWER Views: {worst['views']:,})
Title: {worst['title']}

Return MARKDOWN:

## ១. ភាពខុសគ្នាចម្បង (Key Differences)
## ២. ហេតុអ្វី Thumbnail A បាន CTR ខ្ពស់?
## ៣. ហេតុអ្វី Thumbnail B បាន CTR ទាប?
## ៤. រូបមន្ត Thumbnail ល្អ (Winning Formula)
## ៥. ដំបូន្មានជាក់ស្តែង (Actionable Tips)
"""
    try:
        return _call_multimodal([
            "THUMBNAIL A (HIGHER VIEWS):",
            types.Part.from_bytes(data=b1, mime_type="image/jpeg"),
            "THUMBNAIL B (LOWER VIEWS):",
            types.Part.from_bytes(data=b2, mime_type="image/jpeg"),
            prompt,
        ], temperature=0.5)
    except Exception as e:
        return f"❌ AI error: {e}"


# =====================================================
# DESCRIPTION STRATEGY ANALYSIS
# =====================================================
def analyze_description_strategy(videos: list[dict]) -> str:
    samples = []
    for i, v in enumerate(videos[:5]):
        desc = (v.get("description") or "").strip()
        if desc:
            samples.append(
                f"--- VIDEO {i+1} ---\n"
                f"Title: {v['title']}\n"
                f"Length: {len(desc)} chars\n"
                f"Description:\n{desc[:1800]}\n"
            )
    if not samples:
        return "❌ No descriptions found in the fetched videos."

    prompt = f"""Analyze how this YouTube channel writes video descriptions.

CRITICAL: Base your analysis ONLY on the actual descriptions below.

REAL DESCRIPTIONS FROM THEIR VIDEOS:
{chr(10).join(samples)}

# Return MARKDOWN

## ១. រចនាសម្ព័ន្ធ Description (Structure)
## ២. រូបមន្តពិតរបស់គេ (Their Actual Formula)
## ៣. Keywords ដែលគេដាក់ច្រើន
## ៤. ចំណុចល្អ ✅
## ៥. ចំណុចខ្សោយ ⚠️
## ៦. អ្វីដែលអ្នកគួរយកតាម
"""
    return _call_text(prompt, temperature=0.5, max_tokens=4096)


# =====================================================
# HASHTAG STRATEGY ANALYSIS
# =====================================================
def analyze_hashtag_strategy(top_hashtags: list, title_hashtags: list) -> str:
    if not top_hashtags and not title_hashtags:
        return "❌ No hashtags found."

    ctx = "REAL DATA FROM THEIR VIDEOS:\n"
    if top_hashtags:
        ctx += f"\nTop Hashtags (from descriptions):\n"
        ctx += "\n".join([f"  #{h} — used {n} times" for h, n in top_hashtags[:25]])
    if title_hashtags:
        ctx += f"\n\nHashtags in Titles:\n  " + ", ".join(title_hashtags)

    prompt = f"""Analyze this channel's HASHTAG STRATEGY.

CRITICAL: Only use the REAL data below.

{ctx}

# Return MARKDOWN

## ១. Hashtags ដែលគេប្រើច្រើន
## ២. ប្រភេទ Hashtag (Broad / Niche / Branded)
## ៣. យុទ្ធសាស្ត្រ (Strategy)
## ៤. Hashtags ដែលអ្នកគួរយកតាម
## ៥. Hashtags ដែលគួរចៀសវាង
"""
    return _call_text(prompt, temperature=0.5, max_tokens=3000)


# =====================================================
# CHANNEL TYPE + AUDIENCE ANALYSIS
# =====================================================
def analyze_channel_profile(channel: dict, videos: list[dict]) -> str:
    from collections import Counter

    titles = [v["title"] for v in videos[:20]]
    all_tags = []
    for v in videos[:20]:
        all_tags.extend(v.get("tags", []))
    tag_freq = Counter([t.lower() for t in all_tags]).most_common(30)

    all_desc = " ".join([v.get("description", "")[:500] for v in videos[:10]])

    ctx = f"""# REAL DATA (from YouTube API)

## Channel Info
- Name: {channel.get('title', '')}
- Description: {channel.get('description', '')[:600]}
- Country (from API): {channel.get('country', 'not set')}
- Subs: {channel['subs_fmt']}
- Total Videos: {channel['videos_fmt']}
- Total Views: {channel['views_fmt']}
- Created: {channel.get('published_at', '')[:10]}

## Recent Video Titles ({len(titles)}):
{chr(10).join(f'- {t}' for t in titles)}

## Top Tags Used:
{', '.join([f'{t}({n})' for t, n in tag_freq[:30]]) or '(no tags)'}

## Sample Description Text:
{all_desc[:800]}
"""

    prompt = f"""Analyze this YouTube channel based STRICTLY on the real data below.

CRITICAL RULES:
- DO NOT invent information
- If not enough data, say "not enough data"

{ctx}

# Return MARKDOWN

## ១. ប្រភេទ Channel (Channel Category/Niche)
**Evidence**: (mention specific titles/tags)

## ២. ទស្សនិកជនគោលដៅ (Target Audience)
## ៣. ភាសាដែលគេប្រើ (Language)
## ៤. ប្រធានបទចម្បង (Main Topics)
## ៥. ស្ទីលនៃការធ្វើ Content (Style)
## ៦. ឱកាសសម្រាប់អ្នក (Opportunity for You)
## ៧. កម្រិតទុកចិត្ត (Confidence) — X% + Reason
"""
    return _call_text(prompt, temperature=0.5, max_tokens=4096)