"""API key generation and verification utilities."""
from __future__ import annotations

import hashlib
import hmac
import os
import secrets
from dataclasses import dataclass
from datetime import datetime
from typing import Optional


def _api_key_salt() -> str:
    """Return stable salt for hashing API keys."""
    return os.getenv("AIF_API_KEY_SALT", "").strip()


def hash_api_key(plain_key: str) -> str:
    """Hash API key for storage; never persist plaintext."""
    payload = f"{_api_key_salt()}:{plain_key}".encode("utf-8")
    return hashlib.sha256(payload).hexdigest()


def verify_api_key_hash(plain_key: str, stored_hash: str) -> bool:
    """Constant-time hash comparison."""
    return hmac.compare_digest(hash_api_key(plain_key), stored_hash or "")


def generate_api_key(prefix: str = "aif_ak") -> str:
    """Generate one external API key."""
    return f"{prefix}_{secrets.token_urlsafe(32)}"


def mask_api_key(raw: str) -> str:
    """Mask key for display/logging."""
    if not raw:
        return ""
    if len(raw) <= 10:
        return "***"
    return f"{raw[:6]}...{raw[-4:]}"


@dataclass
class ResolvedAPIKey:
    """Resolved API key identity context."""

    key_id: str
    agent_id: str
    scopes: list[str]
    is_active: bool
    expires_at: Optional[datetime]

