"""License key generation and offline license file encoding."""
from __future__ import annotations

import base64
import hashlib
import hmac
import json
import uuid
from datetime import datetime
from typing import Optional

from .models import LicenseInfo


def generate_license_key() -> str:
    """Generate a formatted license key: MESH-XXXX-XXXX-XXXX-XXXX."""
    raw = uuid.uuid4().hex.upper()
    return f"MESH-{raw[:4]}-{raw[4:8]}-{raw[8:12]}-{raw[12:16]}"


def _sign(payload: bytes, signing_key: str) -> str:
    """Create HMAC-SHA256 signature."""
    return hmac.new(
        signing_key.encode("utf-8"),
        payload,
        hashlib.sha256,
    ).hexdigest()


def encode_license_file(license_info: LicenseInfo, signing_key: str) -> str:
    """Encode and sign a license for offline use.

    Returns a base64 string containing the JSON payload and its HMAC signature.
    """
    payload = license_info.model_dump_json().encode("utf-8")
    sig = _sign(payload, signing_key)
    envelope = json.dumps({
        "payload": base64.b64encode(payload).decode("ascii"),
        "signature": sig,
        "version": 1,
    })
    return base64.b64encode(envelope.encode("utf-8")).decode("ascii")


def decode_license_file(encoded: str, signing_key: str) -> Optional[LicenseInfo]:
    """Verify and decode an offline license file.

    Returns None if the signature is invalid.
    """
    try:
        envelope = json.loads(base64.b64decode(encoded))
        payload = base64.b64decode(envelope["payload"])
        expected_sig = _sign(payload, signing_key)
        if not hmac.compare_digest(envelope["signature"], expected_sig):
            return None
        return LicenseInfo.model_validate_json(payload)
    except Exception:
        return None
