"""
core/gemini_video.py
- Upload video files to Gemini File API (Free Tier supported)
- Analyze video content using gemini-3.8-flash via Interactions API
"""

import os
import time
import tempfile
from pathlib import Path
from dotenv import load_dotenv
from google import genai

load_dotenv()

# === ប្រើម៉ូដែលថ្មីបំផុតដែល Google ណែនាំ ===
MODEL = "gemini-3.8-flash"
MAX_WAIT_SECONDS = 300


def _load_keys() -> list[str]:
    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_idx = 0
_clients: dict[str, genai.Client] = {}


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_idx
    if len(_KEYS) <= 1:
        return False
    _current_idx = (_current_idx + 1) % len(_KEYS)
    return True


def _is_quota_error(e: Exception) -> bool:
    s = str(e).lower()
    return any(x in s for x in ["429", "quota", "rate", "resource_exhausted", "too many"])


def upload_video(file_bytes: bytes, filename: str, mime_type: str = "video/mp4"):
    """Upload video bytes to Gemini File API"""
    if not _KEYS:
        raise RuntimeError("No Gemini API keys. Add GEMINI_API_KEY_1=... to .env")

    last_err = None
    for _ in range(len(_KEYS)):
        key = _KEYS[_current_idx]
        try:
            client = _get_client(key)
            suffix = Path(filename).suffix or ".mp4"
            with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
                tmp.write(file_bytes)
                tmp_path = tmp.name
            try:
                file_obj = client.files.upload(
                    file=tmp_path,
                    config={"mime_type": mime_type},
                )
            finally:
                try:
                    os.unlink(tmp_path)
                except Exception:
                    pass
            return client, file_obj
        except Exception as e:
            last_err = e
            if _is_quota_error(e):
                if _rotate_key():
                    continue
            break
    raise RuntimeError(f"Upload failed: {last_err}")


def wait_for_active(client, file_obj, timeout: int = MAX_WAIT_SECONDS):
    """Wait until file state is ACTIVE"""
    start = time.time()
    while True:
        try:
            f = client.files.get(name=file_obj.name)
        except Exception as e:
            raise RuntimeError(f"File status check failed: {e}")
        state = getattr(f.state, "name", str(f.state))
        if state == "ACTIVE":
            return f
        if state == "FAILED":
            raise RuntimeError("Gemini file processing FAILED")
        if time.time() - start > timeout:
            raise RuntimeError(f"File processing timed out ({timeout}s)")
        time.sleep(2)


def delete_file(client, file_obj):
    """Cleanup"""
    try:
        client.files.delete(name=file_obj.name)
    except Exception:
        pass


def analyze_video_file(
    file_bytes: bytes,
    filename: str,
    prompt: str,
    mime_type: str = "video/mp4",
    temperature: float = 0.7,
    max_tokens: int = 8192,
) -> str:
    """
    Upload video → wait → analyze via Interactions API (gemini-3.8-flash)
    """
    client, file_obj = upload_video(file_bytes, filename, mime_type)
    try:
        active_file = wait_for_active(client, file_obj)
        # === ប្រើ Interactions API ថ្មី ===
        interaction = client.interactions.create(
            model=MODEL,
            input=[
                {
                    "type": "video",
                    "uri": active_file.uri,
                    "mime_type": active_file.mime_type,
                },
                {"type": "text", "text": prompt},
            ],
        )
        return interaction.output_text or ""
    finally:
        delete_file(client, file_obj)