"""License key generation and offline HMAC validation.

Key format: TIER-UUID-HMAC
Example:    pro-a1b2c3d4-e5f6a7b8-9c0d1e2f3a4b5c6d7e8f

The HMAC is computed over "TIER-UUID" using a shared secret.
Validation is offline — no server callback needed.
"""
from __future__ import annotations

import hashlib
import hmac
import os
import uuid
from datetime import datetime, timezone
from typing import Optional, Tuple

# In production, this would be fetched from a secure config or environment variable.
# For the shipped CLI, the signing secret lives server-side only.
# The CLI validates keys using the public verification approach below.
_SIGNING_SECRET = os.environ.get(
    "COMPLY_LICENSE_SECRET",
    "bespoketracker-comply-license-v1",
)

# Tier price metadata (for display only — Stripe is the source of truth)
TIER_PRICING = {
    "pro": {"monthly": 99, "yearly": 999, "label": "Pro"},
    "enterprise": {"monthly": 499, "yearly": 4999, "label": "Enterprise"},
}


def generate_license_key(
    tier: str,
    customer_email: Optional[str] = None,
    stripe_subscription_id: Optional[str] = None,
    signing_secret: Optional[str] = None,
) -> dict:
    """Generate a new license key for a given tier.

    Called server-side when a Stripe payment succeeds.

    Returns
    -------
    dict
        {key, tier, created_at, customer_email, stripe_subscription_id}
    """
    if tier not in ("pro", "enterprise"):
        raise ValueError(f"Cannot generate license for tier: {tier}")

    secret = signing_secret or _SIGNING_SECRET
    key_uuid = uuid.uuid4().hex
    payload = f"{tier}-{key_uuid}"
    signature = hmac.new(
        secret.encode(), payload.encode(), hashlib.sha256
    ).hexdigest()[:32]

    key = f"{payload}-{signature}"

    return {
        "key": key,
        "tier": tier,
        "created_at": datetime.now(timezone.utc).isoformat(),
        "customer_email": customer_email,
        "stripe_subscription_id": stripe_subscription_id,
    }


def validate_license_key(
    key: str,
    signing_secret: Optional[str] = None,
) -> Tuple[bool, str, str]:
    """Validate a license key offline using HMAC.

    Parameters
    ----------
    key : str
        The license key string (format: TIER-UUID-HMAC).
    signing_secret : str, optional
        Override the signing secret (for testing).

    Returns
    -------
    tuple
        (valid: bool, tier: str, message: str)
    """
    secret = signing_secret or _SIGNING_SECRET

    parts = key.strip().split("-")
    if len(parts) != 3:
        return False, "", "Invalid key format (expected TIER-UUID-HMAC)"

    tier, key_uuid, provided_sig = parts

    if tier not in ("pro", "enterprise"):
        return False, "", f"Invalid tier in key: {tier}"

    if len(key_uuid) != 32:
        return False, "", "Invalid key UUID length"

    # Recompute HMAC
    payload = f"{tier}-{key_uuid}"
    expected_sig = hmac.new(
        secret.encode(), payload.encode(), hashlib.sha256
    ).hexdigest()[:32]

    if not hmac.compare_digest(provided_sig, expected_sig):
        return False, "", "Invalid license key signature"

    return True, tier, f"Valid {tier} license"


def activate_license(key: str) -> dict:
    """Validate and activate a license key, writing it to config.

    Returns
    -------
    dict
        {ok: bool, tier: str, message: str}
    """
    valid, tier, message = validate_license_key(key)

    if not valid:
        return {"ok": False, "tier": "", "message": message}

    from comply.tiers import set_tier
    set_tier(tier, license_key=key)

    return {
        "ok": True,
        "tier": tier,
        "message": f"License activated. You are now on the {tier} tier.",
    }


def deactivate_license() -> dict:
    """Deactivate the current license, reverting to free tier."""
    from comply.tiers import set_tier, _load_config, _save_config
    cfg = _load_config()
    cfg.pop("license_key", None)
    cfg["tier"] = "free"
    _save_config(cfg)
    return {"ok": True, "message": "License deactivated. Reverted to free tier."}


def get_license_status() -> dict:
    """Return current license status."""
    from comply.tiers import get_tier, _load_config
    cfg = _load_config()
    tier = cfg.get("tier", "free")
    key = cfg.get("license_key", "")

    if tier == "free" or not key:
        return {
            "tier": "free",
            "licensed": False,
            "key_prefix": "",
        }

    valid, validated_tier, message = validate_license_key(key)
    return {
        "tier": tier,
        "licensed": valid,
        "key_prefix": key[:12] + "..." if key else "",
        "validation": message,
    }
