"""API key issuing, verification, rotation (TZ 2.9.1)."""

from __future__ import annotations

import hmac
from dataclasses import dataclass
from datetime import timedelta
from typing import Any

from django.db import transaction
from django.utils import timezone

from snapfile.core.crypto import base62, derive_key, encrypt_secret, hmac_hex, random_lower
from snapfile.projects.models import Project

from .models import SCOPES, ApiKey

DEFAULT_SCOPES = ["read", "templates:read", "render", "editor:issue", "webhooks"]
ROTATION_GRACE = timedelta(days=7)


@dataclass
class IssuedKey:
    key: ApiKey
    secret: str  # full token, shown once
    hmac_secret: str | None = None


def hash_secret(secret: str) -> str:
    return hmac_hex(derive_key("api-key-pepper"), secret)


def issue_key(
    project: Project,
    name: str,
    scopes: list[str] | None = None,
    *,
    env: str = "live",
    require_signature: bool = False,
    expires_at: Any = None,
    rotated_from: ApiKey | None = None,
) -> IssuedKey:
    scopes = [s for s in (scopes or DEFAULT_SCOPES) if s in SCOPES]
    prefix = random_lower(10)
    while ApiKey.objects.filter(prefix=prefix).exists():
        prefix = random_lower(10)
    secret = base62(32)
    hmac_secret = base62(32) if require_signature else None
    key = ApiKey.objects.create(
        project=project,
        name=name[:128],
        env=env,
        prefix=prefix,
        key_hash=hash_secret(secret),
        hmac_secret_enc=encrypt_secret(hmac_secret) if hmac_secret else None,
        require_signature=require_signature,
        scopes=scopes,
        expires_at=expires_at,
        rotated_from=rotated_from,
    )
    return IssuedKey(key=key, secret=f"vk_{env}_{prefix}.{secret}", hmac_secret=hmac_secret)


def parse_token(token: str) -> tuple[str, str, str] | None:
    """``vk_live_<prefix>.<secret>`` -> (env, prefix, secret)."""
    if not token.startswith("vk_") or "." not in token:
        return None
    head, _, secret = token.partition(".")
    parts = head.split("_")
    if len(parts) != 3 or parts[1] not in ("live", "test") or len(parts[2]) != 10:
        return None
    return parts[1], parts[2], secret


def verify_token(token: str) -> ApiKey | None:
    parsed = parse_token(token)
    if parsed is None:
        return None
    env, prefix, secret = parsed
    key = ApiKey.objects.select_related("project").filter(prefix=prefix, env=env).first()
    if key is None:
        hash_secret(secret)  # constant-ish time for unknown prefixes
        return None
    if not hmac.compare_digest(key.key_hash, hash_secret(secret)):
        return None
    now = timezone.now()
    if key.revoked_at is not None or (key.expires_at is not None and key.expires_at <= now):
        return None
    return key


def sign_with_key(project: Project, key: ApiKey, token: str) -> None:
    """One secret for the whole service: the key also signs the connector requests and the webhooks."""
    from snapfile.core import ids

    project.settings = {**(project.settings or {}), "service_key_id": ids.encode("key", key.id)}
    project.service_secret_enc = encrypt_secret(token)
    project.webhook_secret_enc = encrypt_secret(token)
    project.save(update_fields=["settings", "service_secret_enc", "webhook_secret_enc", "updated_at"])


def rotate_key(key: ApiKey) -> IssuedKey:
    """A new key with the same rights; the old one stays valid for the grace period. The signing moves along with it."""
    from snapfile.core import ids

    with transaction.atomic():
        issued = issue_key(
            key.project,
            key.name,
            list(key.scopes),
            env=key.env,
            require_signature=key.require_signature,
            rotated_from=key,
        )
        grace = timezone.now() + ROTATION_GRACE
        if key.expires_at is None or key.expires_at > grace:
            key.expires_at = grace
            key.save(update_fields=["expires_at", "updated_at"])
        if key.project.setting("service_key_id") == ids.encode("key", key.id):
            sign_with_key(key.project, issued.key, issued.secret)
    return issued


def key_dict(key: ApiKey) -> dict[str, Any]:
    from snapfile.core import ids

    return {
        "id": ids.encode("key", key.id),
        "name": key.name,
        "env": key.env,
        "prefix": key.prefix,
        "scopes": key.scopes,
        "require_signature": key.require_signature,
        "expires_at": key.expires_at.isoformat() if key.expires_at else None,
        "revoked_at": key.revoked_at.isoformat() if key.revoked_at else None,
        "last_used_at": key.last_used_at.isoformat() if key.last_used_at else None,
        "created_at": key.created_at.isoformat(),
    }
