"""
Sezen & Cemre: Content, Script & Comment Engine
Supports Hybrid execution: Gemini Ultra/Flash API + Local Ollama RTX 3070 GPU ($0 cost)
Generates high-retention YouTube Shorts (30-45s), Long-form Videos (8-12m), and Comment Replies.
"""
import os
import sys
import io
import json
import time
import urllib.request
import urllib.error

# Ensure UTF-8 output on Windows
if sys.stdout.encoding != 'utf-8':
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CREDENTIALS_DIR = os.path.join(BASE_DIR, 'credentials')
KEY_FILE = os.path.join(CREDENTIALS_DIR, 'google-gemini-api.txt')

CANDIDATE_MODELS = [
    "gemini-2.5-flash",
    "gemini-2.0-flash",
    "gemini-3.6-flash",
    "gemini-3.5-flash",
    "gemini-flash-lite-latest",
    "gemini-3.5-flash-lite"
]

def get_api_key():
    for candidate in [
        KEY_FILE,
        "/opt/data/ai/credentials/google-gemini-api.txt",
        "/home/yunganc/.hermes/ai/credentials/google-gemini-api.txt",
        "/home/yunganc/public_html/ai/credentials/google-gemini-api.txt"
    ]:
        if os.path.exists(candidate):
            with open(candidate, 'r', encoding='utf-8') as f:
                return f.read().strip()
    return os.environ.get("GEMINI_API_KEY", "")

def _call_gemini_json(prompt: str) -> dict:
    api_key = get_api_key()
    if not api_key:
        raise ValueError("Gemini API key not found in credentials/google-gemini-api.txt")

    req_body = {
        "contents": [{"parts": [{"text": prompt}]}],
        "generationConfig": {
            "temperature": 0.7,
            "responseMimeType": "application/json"
        }
    }

    last_error = None
    for model in CANDIDATE_MODELS:
        url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}"
        req = urllib.request.Request(
            url,
            data=json.dumps(req_body).encode('utf-8'),
            headers={'Content-Type': 'application/json'}
        )
        try:
            print(f"[*] Sezen deniyor: model={model}...", flush=True)
            with urllib.request.urlopen(req, timeout=25) as resp:
                data = json.loads(resp.read().decode('utf-8'))
                text = data['candidates'][0]['content']['parts'][0]['text']
                res_json = json.loads(text)
                res_json["_model_used"] = model
                print(f"[+] Basarili! Model: {model}", flush=True)
                return res_json
        except Exception as e:
            last_error = e
            continue

    raise RuntimeError(f"Gemini models failed: {last_error}")

def _call_local_ollama_json(prompt: str, model: str = None) -> dict:
    from engine.local_llm import generate_local_text, load_settings
    settings = load_settings()
    used_model = model or settings.get("active_local_model", "llama3.2:3b")
    print(f"[*] Sezen/Cem Yerel RTX 3070 Modelini kullaniyor: {used_model}...", flush=True)
    raw = generate_local_text(prompt, model=used_model, json_mode=True, timeout=120)
    data = json.loads(raw)
    data["_model_used"] = f"ollama/{used_model} (RTX 3070)"
    return data

def generate_bible_short_script(topic_or_theme: str = "peace and hope in difficult times", engine_mode: str = None) -> dict:
    prompt = f"""
You are Sezen, an elite YouTube strategist and scriptwriter specializing in Christian inspiration and Bible verses for the channel '@HolyBibleForWorld'.
Create a viral, high-retention YouTube Short script based on the theme: '{topic_or_theme}'.

Guidelines:
1. Target length: 30 to 45 seconds when spoken slowly and reverently (~65-85 words).
2. The Hook (first 3-5 seconds) must grab attention immediately with deep emotional resonance.
3. Scripture Verse: Pick an authentic, powerful verse from the Holy Bible (NIV, ESV, or KJV) and clearly state the reference.
4. Reflection/Prayer: A brief, uplifting reflection that brings peace to the viewer.
5. Call to Action: End with an encouraging call to action (e.g., 'Type Amen if you receive this blessing. Subscribe to hear God's word daily.').
6. Provide a high-CTR title with emojis and #shorts, description with relevant tags, and 10 tags.

Return ONLY a valid JSON object with this exact structure (no markdown fences, just raw JSON):
{{
  "theme": "{topic_or_theme}",
  "video_type": "short",
  "verse_reference": "Book Chapter:Verse",
  "title": "Compelling Title With Emoji and #shorts",
  "description": "Full YouTube description with hashtags",
  "tags": ["bible", "faith", "jesus", "prayer", "shorts"],
  "voiceover_text": "Complete spoken text for the voiceover without sound cues or brackets.",
  "visual_prompt": "cinematic golden light breaking through dramatic clouds over peaceful mountains, sacred atmosphere, 8k masterpiece, no text"
}}
"""
    mode = engine_mode
    if not mode:
        try:
            from engine.local_llm import load_settings
            mode = load_settings().get("sezen_engine", "hybrid")
        except Exception:
            mode = "gemini"

    if mode == "local":
        try:
            return _call_local_ollama_json(prompt)
        except Exception as e:
            print(f"[-] Yerel model hatasi ({e}), Gemini API'ye geciliyor...", flush=True)
            return _call_gemini_json(prompt)
    else:
        try:
            return _call_gemini_json(prompt)
        except Exception as e:
            print(f"[-] Gemini API hatasi ({e}), Yerel RTX 3070 Ollama modeline geciliyor...", flush=True)
            return _call_local_ollama_json(prompt)

def generate_bible_long_script(topic_or_theme: str = "Overcoming Fear and Anxiety Through God's Promises", engine_mode: str = None) -> dict:
    """Generates a comprehensive Long-form (horizontal 16:9) devotional video script."""
    prompt = f"""
You are Sezen, lead scriptwriter for '@HolyBibleForWorld'.
Create a deeply moving, comprehensive devotional YouTube video script on the theme: '{topic_or_theme}'.

Guidelines:
1. Structure the spoken voiceover into 5 rich sections:
   - Deep Emotional Opening Hook
   - Scripture Reading 1 & Reflection
   - Scripture Reading 2 & Life Application
   - Scripture Reading 3 & Comforting Message
   - Closing Prayer & Blessing (ending with 'Type Amen in the comments and subscribe for daily scripture')
2. Total spoken text should be 450 to 650 words of continuous, reverent spoken English (without stage directions or brackets).
3. Provide a high-CTR YouTube Title, comprehensive SEO Description with timestamps/chapters, and 12 SEO tags.

Return ONLY a valid JSON object with this exact structure:
{{
  "theme": "{topic_or_theme}",
  "video_type": "long",
  "verse_reference": "Multiple Scriptures (Psalms, Isaiah, Philippians)",
  "title": "Powerful Devotional Title | Christian Motivation & Prayer",
  "description": "Full YouTube SEO description with chapters and hashtags",
  "tags": ["bible verses", "christian motivation", "morning prayer", "gods promises", "peace", "faith"],
  "voiceover_text": "Full continuous spoken text for the voiceover without brackets or sound cues.",
  "visual_prompt": "cinematic serene sunrise over ancient olive trees and tranquil lake, warm divine golden rays, ultra detailed 8k, no text"
}}
"""
    mode = engine_mode
    if not mode:
        try:
            from engine.local_llm import load_settings
            mode = load_settings().get("sezen_engine", "hybrid")
        except Exception:
            mode = "gemini"

    if mode == "local":
        try:
            return _call_local_ollama_json(prompt)
        except Exception:
            return _call_gemini_json(prompt)
    else:
        try:
            return _call_gemini_json(prompt)
        except Exception:
            return _call_local_ollama_json(prompt)

def generate_comment_reply(comment_text: str, author_name: str = "Friend") -> str:
    """Cemre: Generates a warm, faith-affirming reply using Local RTX 3070 first ($0 cost), fallback to Gemini."""
    prompt = f"""You are Cemre, the warm and caring community manager for the Christian YouTube channel '@HolyBibleForWorld'.
Viewer '{author_name}' left this comment on our video:
"{comment_text}"

Write a short, heartfelt, encouraging, faith-filled reply in English (1 to 2 sentences, with 1 or 2 gentle emojis like 🙏✨).
Return ONLY JSON: {{"reply": "your reply text here"}}"""

    try:
        res = _call_local_ollama_json(prompt)
        if res.get("reply"):
            return res["reply"]
    except Exception:
        pass

    try:
        res = _call_gemini_json(prompt)
        if res.get("reply"):
            return res["reply"]
    except Exception:
        pass

    return f"God bless you abundantly, {author_name}! Thank you for sharing your faith with our community. 🙏✨"

if __name__ == '__main__':
    print("[*] Sezen is generating a Bible Short script...")
    script = generate_bible_short_script("God will never leave you")
    print("\n" + json.dumps(script, indent=2, ensure_ascii=False))
