"""
core/usage_limiter.py
- Track daily usage per feature
- Skip limits if user provides own API keys (BYOK)
- Anti-tamper: HMAC signature on usage file
"""

import json
import hmac
import hashlib
from pathlib import Path
from datetime import datetime, date
from functools import wraps

# =====================================================
# Config
# =====================================================
USAGE_FILE = Path.home() / ".yt_analyzer_pro" / "usage.json"
USAGE_FILE.parent.mkdir(exist_ok=True, parents=True)

# ⚠️ Change this to your own random string
SECRET = b"ytkeys-usage-secret-2026-CHANGE-THIS-TO-RANDOM"


# Feature → (limit_per_day, label)
LIMITS = {
    "video_analyzer":    (10,  "🧠 Video Analyzer"),
    "compare_videos":    (10,  "⚖️ Compare Videos"),
    "channel_analyzer":  (3,   "📈 Channel Analyzer"),
    "competitor_spy":    (3,   "🕵️ Competitor Spy"),
    "trending_keywords": (15,  "🔑 Trending Keywords"),
    "trending_videos":   (15,  "🔥 Trending Videos"),
    "analyze_url":       (999, "📥 Analyze Video (URL)"),
    "history":           (999, "📚 History"),
}


# =====================================================
# HMAC signature (anti-tamper)
# =====================================================
def _sig(data: dict) -> str:
    payload = json.dumps(data, sort_keys=True)
    return hmac.new(SECRET, payload.encode(), hashlib.sha256).hexdigest()[:16]


# =====================================================
# Load / Save
# =====================================================
def _load() -> dict:
    today = date.today().isoformat()
    if not USAGE_FILE.exists():
        return {"date": today, "counters": {}}

    try:
        raw = json.loads(USAGE_FILE.read_text(encoding="utf-8"))
        stored_sig = raw.pop("_sig", "")

        if stored_sig != _sig(raw):
            return {"date": today, "counters": {}}

        if raw.get("date") != today:
            return {"date": today, "counters": {}}

        return raw
    except Exception:
        return {"date": today, "counters": {}}


def _save(data: dict):
    out = dict(data)
    out["_sig"] = _sig(data)
    try:
        USAGE_FILE.write_text(json.dumps(out, indent=2), encoding="utf-8")
    except Exception:
        pass


# =====================================================
# Check if user has own keys → skip limits
# =====================================================
def _has_user_keys() -> bool:
    try:
        from core.user_keys import has_user_keys
        return has_user_keys()
    except Exception:
        return False


# =====================================================
# Public API
# =====================================================
def get_usage() -> dict:
    """Get all features with usage/limit/remaining"""
    # If user has own keys → show unlimited
    if _has_user_keys():
        out = {}
        for feat, (limit, label) in LIMITS.items():
            out[feat] = {
                "used": 0,
                "limit": 999999,
                "remaining": 999999,
                "label": label,
                "unlimited": True,
            }
        return out

    data = _load()
    counters = data.get("counters", {})

    out = {}
    for feat, (limit, label) in LIMITS.items():
        used = counters.get(feat, 0)
        out[feat] = {
            "used": used,
            "limit": limit,
            "remaining": max(0, limit - used),
            "label": label,
            "unlimited": limit >= 999,
        }
    return out


def check_limit(feature: str) -> dict:
    """Check if user can use feature. Unlimited if user has own keys."""
    # ⭐ Skip limits if user provides own API keys
    if _has_user_keys():
        return {
            "allowed": True,
            "used": 0,
            "limit": 999999,
            "remaining": 999999,
            "unlimited": True,
        }

    if feature not in LIMITS:
        return {"allowed": True, "remaining": 999, "limit": 999, "used": 0}

    limit = LIMITS[feature][0]
    data = _load()
    used = data.get("counters", {}).get(feature, 0)

    return {
        "allowed": used < limit,
        "used": used,
        "limit": limit,
        "remaining": max(0, limit - used),
    }


def increment(feature: str) -> dict:
    """Increment usage. Skipped if user has own keys."""
    if _has_user_keys():
        return {"used": 0, "limit": 999999, "remaining": 999999}

    if feature not in LIMITS:
        return {"used": 0, "limit": 999, "remaining": 999}

    data = _load()
    counters = data.setdefault("counters", {})
    counters[feature] = counters.get(feature, 0) + 1
    _save(data)

    limit = LIMITS[feature][0]
    return {
        "used": counters[feature],
        "limit": limit,
        "remaining": max(0, limit - counters[feature]),
    }


def reset_usage():
    """Manual reset (debug/admin)"""
    today = date.today().isoformat()
    _save({"date": today, "counters": {}})


def limit_guard(feature: str):
    """Decorator: check before, increment after."""
    def decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            status = check_limit(feature)
            if not status["allowed"]:
                raise RuntimeError(
                    f"⚠️ Daily limit reached for {LIMITS[feature][1]}\n"
                    f"Used: {status['used']}/{status['limit']}\n"
                    f"Tip: Add your own API keys in Settings for unlimited usage."
                )
            result = fn(*args, **kwargs)
            increment(feature)
            return result
        return wrapper
    return decorator


# =====================================================
# ⭐ Streamlit UI Helpers
# =====================================================
def usage_gate(feature_key: str) -> bool:
    """
    Check limit + show UI warning/block.
    Returns True if user can proceed, False if blocked.
    """
    import streamlit as st

    # ⭐ Skip limits if user provides own API keys
    if _has_user_keys():
        st.success("✅ Using YOUR API keys — Unlimited usage!")
        return True

    if feature_key not in LIMITS:
        return True

    label = LIMITS[feature_key][1]
    status = check_limit(feature_key)

    # Blocked — limit reached
    if not status["allowed"]:
        st.error(
            f"🚫 **Daily limit reached!**\n\n"
            f"**{label}** — Used: **{status['used']}/{status['limit']}**\n\n"
            f"🔄 Resets tomorrow at midnight.\n\n"
            f"💡 **Tip:** Add your own API keys in ⚙️ Settings for **UNLIMITED** usage!"
        )
        return False

    # Warning — low remaining
    if status["remaining"] <= 3:
        st.warning(
            f"⚠️ Only **{status['remaining']}** {label} left today "
            f"({status['used']}/{status['limit']})"
        )
    else:
        st.info(
            f"📊 {label}: **{status['remaining']}** / {status['limit']} remaining today"
        )

    return True


def usage_badge(feature_key: str) -> str:
    """Get a short text badge for display."""
    if _has_user_keys():
        return "∞"
    if feature_key not in LIMITS:
        return "∞"
    status = check_limit(feature_key)
    if status["limit"] >= 999:
        return "∞"
    return f"{status['remaining']}/{status['limit']}"


def usage_progress(feature_key: str) -> float:
    """Get progress 0.0-1.0 for progress bar."""
    if _has_user_keys():
        return 0.0
    if feature_key not in LIMITS:
        return 0.0
    status = check_limit(feature_key)
    if status["limit"] >= 999:
        return 0.0
    return min(1.0, status["used"] / status["limit"])


def usage_summary() -> dict:
    """Quick summary of all counters"""
    usage = get_usage()
    total_used = sum(u["used"] for u in usage.values() if not u["unlimited"])
    total_limit = sum(u["limit"] for u in usage.values() if not u["unlimited"])
    return {
        "total_used": total_used,
        "total_limit": total_limit,
        "percent": (total_used / total_limit * 100) if total_limit else 0,
    }