"""
core/license.py — License management (HMAC offline)
"""

import json
import hashlib
import platform
from pathlib import Path
from datetime import datetime
from core.license_verify import verify_key


def _get_storage_path() -> Path:
    home = Path.home() / ".yt_analyzer_pro"
    home.mkdir(exist_ok=True)
    return home / "license.json"


def _hwid() -> str:
    raw = f"{platform.node()}-{platform.machine()}-{platform.system()}"
    return hashlib.sha256(raw.encode()).hexdigest()[:16]


def verify_license(key: str) -> dict:
    """Verify HMAC-signed key (offline)"""
    return verify_key(key)


def save_license(key: str) -> None:
    data = {
        "key": key.strip().upper(),
        "hwid": _hwid(),
        "saved_at": datetime.now().isoformat(),
    }
    _get_storage_path().write_text(json.dumps(data, indent=2), encoding="utf-8")


def load_license() -> str | None:
    p = _get_storage_path()
    if not p.exists():
        return None
    try:
        data = json.loads(p.read_text(encoding="utf-8"))
        if data.get("hwid") != _hwid():
            return None
        return data.get("key")
    except Exception:
        return None


def clear_license() -> None:
    p = _get_storage_path()
    if p.exists():
        p.unlink()