"""License validation and management."""

import hashlib
import time
from dataclasses import dataclass
from enum import Enum
from typing import Optional

from jose import jwt

from .config import settings


class Tier(str, Enum):
    """Product tiers."""
    FREE = "free"
    PRO = "pro"
    SHIELD = "shield"
    INTEL = "intel"
    TEAM = "team"


@dataclass
class License:
    """Validated license information."""
    user_id: str
    email: str
    tier: Tier
    addons: list[str]
    expires_at: int
    team_id: Optional[str] = None

    @property
    def is_valid(self) -> bool:
        """Check if license is still valid."""
        return self.expires_at > int(time.time())

    def has_access(self, required_tier: Tier) -> bool:
        """Check if license grants access to a tier."""
        if not self.is_valid:
            return False
        tier_hierarchy = {
            Tier.FREE: 0,
            Tier.PRO: 1,
            Tier.SHIELD: 2,
            Tier.INTEL: 2,
            Tier.TEAM: 3,
        }
        if required_tier in (Tier.SHIELD, Tier.INTEL):
            return required_tier.value in self.addons
        return tier_hierarchy.get(self.tier, 0) >= tier_hierarchy.get(required_tier, 0)


def generate_license_key(user_id: str, email: str, tier: str, addons: list[str],
                         duration_days: int = 30) -> str:
    """Generate a signed JWT license key."""
    payload = {
        "sub": user_id,
        "email": email,
        "tier": tier,
        "addons": addons,
        "exp": int(time.time()) + (duration_days * 86400),
        "iat": int(time.time()),
        "iss": "aris.dev",
    }
    return jwt.encode(payload, settings.jwt_secret, algorithm="HS256")


def validate_license_key(token: str) -> Optional[License]:
    """Validate a license key and return License object."""
    try:
        payload = jwt.decode(token, settings.jwt_secret, algorithms=["HS256"])
        return License(
            user_id=payload["sub"],
            email=payload["email"],
            tier=Tier(payload["tier"]),
            addons=payload.get("addons", []),
            expires_at=payload["exp"],
            team_id=payload.get("team_id"),
        )
    except Exception:
        return None


def generate_hardware_fingerprint() -> str:
    """Generate a fingerprint of the user's machine for license binding."""
    import platform
    import uuid
    raw = f"{platform.node()}-{uuid.getnode()}-{platform.machine()}"
    return hashlib.sha256(raw.encode()).hexdigest()[:16]
