"""
core/user_keys.py
- Manage user-provided API keys (BYOK — Bring Your Own Key)
- Encrypted storage in user home directory
"""

import os
import json
import base64
import hashlib
import platform
from pathlib import Path


STORAGE = Path.home() / ".yt_analyzer_pro" / "user_keys.json"
STORAGE.parent.mkdir(exist_ok=True, parents=True)


def _get_cipher():
    """Derive encryption key from machine ID"""
    try:
        from cryptography.fernet import Fernet
    except ImportError:
        raise RuntimeError("Install: pip install cryptography")

    machine = f"{platform.node()}-{platform.machine()}-{platform.system()}"
    key_bytes = hashlib.sha256(machine.encode()).digest()
    return Fernet(base64.urlsafe_b64encode(key_bytes))


def _encrypt(text: str) -> str:
    if not text:
        return ""
    try:
        return _get_cipher().encrypt(text.encode()).decode()
    except Exception:
        return ""


def _decrypt(token: str) -> str:
    if not token:
        return ""
    try:
        return _get_cipher().decrypt(token.encode()).decode()
    except Exception:
        return ""


def load_user_keys() -> dict:
    """Load user keys (decrypted)"""
    if not STORAGE.exists():
        return {}
    try:
        raw = json.loads(STORAGE.read_text(encoding="utf-8"))
        out = {}
        for k, v in raw.items():
            if isinstance(v, str):
                out[k] = _decrypt(v)
            elif isinstance(v, list):
                out[k] = [_decrypt(x) for x in v]
        return out
    except Exception:
        return {}


def save_user_keys(data: dict) -> None:
    """Save user keys (encrypted)"""
    enc = {}
    for k, v in data.items():
        if isinstance(v, str):
            enc[k] = _encrypt(v)
        elif isinstance(v, list):
            enc[k] = [_encrypt(x) for x in v]
    STORAGE.write_text(json.dumps(enc, indent=2), encoding="utf-8")


def clear_user_keys() -> None:
    if STORAGE.exists():
        STORAGE.unlink()


def has_user_keys() -> bool:
    """Check if user has saved their own keys"""
    user = load_user_keys()
    return bool(user.get("youtube_keys") or user.get("gemini_keys"))


def get_effective_keys() -> dict:
    """
    Return effective keys with priority:
    1. User keys (if set)
    2. .env keys (fallback)
    """
    from dotenv import load_dotenv
    load_dotenv()

    user = load_user_keys()

    yt_keys = [k for k in (user.get("youtube_keys") or []) if k.strip()]
    gemini_keys = [k for k in (user.get("gemini_keys") or []) if k.strip()]

    using_user = bool(yt_keys or gemini_keys)

    # Fallback to .env for YouTube
    if not yt_keys:
        i = 1
        while True:
            k = os.getenv(f"YOUTUBE_API_KEY_{i}")
            if not k:
                break
            yt_keys.append(k.strip())
            i += 1
        single = os.getenv("YOUTUBE_API_KEY", "")
        if single and single.strip():
            yt_keys.append(single.strip())

    # Fallback to .env for Gemini
    if not gemini_keys:
        i = 1
        while True:
            k = os.getenv(f"GEMINI_API_KEY_{i}")
            if not k:
                break
            gemini_keys.append(k.strip())
            i += 1
        single = os.getenv("GEMINI_API_KEY", "")
        if single and single.strip():
            gemini_keys.append(single.strip())

    return {
        "youtube_keys": yt_keys,
        "gemini_keys": gemini_keys,
        "using_user_keys": using_user,
    }


def test_youtube_key(key: str) -> dict:
    """Test if YouTube API key works"""
    if not key or not key.strip():
        return {"valid": False, "message": "❌ Empty key"}
    try:
        from googleapiclient.discovery import build
        yt = build("youtube", "v3", developerKey=key.strip(), cache_discovery=False)
        resp = yt.videos().list(part="snippet", id="dQw4w9WgXcQ").execute()
        if resp.get("items"):
            return {"valid": True, "message": "✅ Works"}
        return {"valid": False, "message": "❌ No response"}
    except Exception as e:
        return {"valid": False, "message": f"❌ {str(e)[:100]}"}


def test_gemini_key(key: str) -> dict:
    """Test if Gemini API key works (tries multiple models)"""
    if not key or not key.strip():
        return {"valid": False, "message": "❌ Empty key"}

    # Try these models in order (2026)
    MODELS = [
        "gemini-3.8-flash",
        "gemini-3.7-flash",
        "gemini-3.6-flash",
        "gemini-3.5-flash",
        "gemini-2.5-flash",
        "gemini-2.5-flash-latest",
        "gemini-flash-latest",
    ]

    try:
        from google import genai
        client = genai.Client(api_key=key.strip())

        last_error = "Unknown error"
        for model in MODELS:
            try:
                resp = client.models.generate_content(
                    model=model,
                    contents="Reply with: OK",
                )
                if resp.text:
                    return {
                        "valid": True,
                        "message": f"✅ Works ({model})",
                    }
            except Exception as e:
                err = str(e).lower()
                # Model not found → try next
                if "not found" in err or "404" in err or "not supported" in err:
                    last_error = f"Model {model} unavailable"
                    continue
                # Auth error → stop trying
                if "invalid" in err or "401" in err or "403" in err or "api key not valid" in err:
                    return {"valid": False, "message": "❌ Invalid API key"}
                # Rate limit → stop
                if "429" in err or "quota" in err:
                    return {"valid": True, "message": f"✅ Key valid ({model}) — rate limited"}
                # Other → try next model
                last_error = str(e)[:100]
                continue

        return {"valid": False, "message": f"❌ All models failed: {last_error}"}
    except Exception as e:
        return {"valid": False, "message": f"❌ {str(e)[:100]}"}