"""Public API authentication: API key bearer, optional HMAC signature, scopes, rate limit (TZ 2.9.1-2.9.2)."""

from __future__ import annotations

import hashlib
import hmac
import ipaddress
import time
from datetime import timedelta
from typing import Any

from django.db import IntegrityError, transaction
from django.http import HttpRequest
from django.utils import timezone
from ninja.security import HttpBearer

from snapfile.core.crypto import decrypt_secret, sha256_hex
from snapfile.core.errors import ApiError
from snapfile.core.locks import acquire_lock, incr_counter, lock_held

from .keys import verify_token
from .models import ApiKey, RequestNonce

SIGNATURE_WINDOW = 300
FAIL_LIMIT_PER_MIN = 10
IP_BLOCK_SECONDS = 15 * 60


def client_ip(request: HttpRequest) -> str:
    return request.META.get("REMOTE_ADDR", "") or "-"


def _check_ip_allowlist(key: ApiKey, ip: str) -> None:
    if not key.ip_allowlist:
        return
    try:
        addr = ipaddress.ip_address(ip)
    except ValueError as exc:
        raise ApiError(403, "IP_NOT_ALLOWED", "Client IP is not allowed") from exc
    if not any(addr in ipaddress.ip_network(c, strict=False) for c in key.ip_allowlist):
        raise ApiError(403, "IP_NOT_ALLOWED", "Client IP is not allowed")


def verify_signature(request: HttpRequest, key: ApiKey) -> None:
    ts_raw = request.META.get("HTTP_X_SNAPFILE_TIMESTAMP", "")
    sig_raw = request.META.get("HTTP_X_SNAPFILE_SIGNATURE", "")
    if not ts_raw or not sig_raw:
        if key.require_signature:
            raise ApiError(401, "SIGNATURE_INVALID", "Request signature is required")
        return
    try:
        ts = int(ts_raw)
    except ValueError as exc:
        raise ApiError(401, "SIGNATURE_INVALID", "Bad timestamp") from exc
    if abs(time.time() - ts) > SIGNATURE_WINDOW:
        raise ApiError(401, "SIGNATURE_EXPIRED", "Timestamp outside the allowed window")
    secret = decrypt_secret(key.hmac_secret_enc) or ""
    path = request.get_full_path()
    original = getattr(request, "original_path", None)
    if original and original != request.path_info:
        path = original + (("?" + request.META["QUERY_STRING"]) if request.META.get("QUERY_STRING") else "")
    string = f"{request.method}\n{path}\n{ts}\n{hashlib.sha256(request.body).hexdigest()}"
    expected = "v1=" + hmac.new(secret.encode(), string.encode(), hashlib.sha256).hexdigest()
    candidates = [s.strip() for s in sig_raw.split(",")]
    if not secret or not any(hmac.compare_digest(expected, c) for c in candidates):
        raise ApiError(401, "SIGNATURE_INVALID", "Signature mismatch")
    try:
        with transaction.atomic():
            RequestNonce.objects.create(
                nonce_hash=sha256_hex(sig_raw), expires_at=timezone.now() + timedelta(seconds=2 * SIGNATURE_WINDOW)
            )
    except IntegrityError as exc:
        raise ApiError(401, "SIGNATURE_INVALID", "Signature replay detected") from exc


def _rate_limit(request: HttpRequest, key: ApiKey) -> None:
    limit = int(key.project.setting("rate_limit_per_min") or 600)
    window = timezone.now().strftime("%Y%m%d%H%M")
    count = incr_counter(f"key:{key.id.hex}:{window}", 120)
    reset = 60 - timezone.now().second
    request.rate_headers = {  # type: ignore[attr-defined]
        "RateLimit-Limit": str(limit),
        "RateLimit-Remaining": str(max(0, limit - count)),
        "RateLimit-Reset": str(reset),
    }
    if count > limit:
        raise ApiError(429, "RATE_LIMITED", "Too many requests", headers={"Retry-After": str(reset)})


class ApiKeyAuth(HttpBearer):
    openapi_scheme = "bearer"

    def __call__(self, request: HttpRequest) -> Any:
        header = request.headers.get("Authorization", "")
        if not header.lower().startswith("bearer "):
            raise ApiError(401, "UNAUTHENTICATED", "Authorization: Bearer <API key> is required")
        return self.authenticate(request, header[7:].strip())

    def authenticate(self, request: HttpRequest, token: str) -> ApiKey:
        ip = client_ip(request)
        if lock_held(f"ipblock:{ip}"):
            raise ApiError(403, "IP_BLOCKED", "Too many failed authentication attempts")
        key = verify_token(token)
        if key is None:
            fails = incr_counter(f"ipfail:{ip}:{timezone.now():%Y%m%d%H%M}", 120)
            if fails >= FAIL_LIMIT_PER_MIN:
                acquire_lock(f"ipblock:{ip}", "blocked", IP_BLOCK_SECONDS)
            raise ApiError(401, "INVALID_API_KEY", "API key is invalid, expired or revoked")
        project = key.project
        if project.deleted_at is not None:
            raise ApiError(401, "INVALID_API_KEY", "API key is invalid, expired or revoked")
        if project.status != "active":
            raise ApiError(403, "PROJECT_SUSPENDED", "Project is suspended")
        _check_ip_allowlist(key, ip)
        verify_signature(request, key)
        _rate_limit(request, key)
        now = timezone.now()
        if key.last_used_at is None or now - key.last_used_at > timedelta(minutes=1):
            ApiKey.objects.filter(pk=key.pk).update(last_used_at=now, last_used_ip=ip[:45])
        request.api_key = key  # type: ignore[attr-defined]
        request.project = project  # type: ignore[attr-defined]
        return key


def require_scope(request: HttpRequest, scope: str) -> ApiKey:
    key: ApiKey = request.auth  # type: ignore[attr-defined]
    if not key.has_scope(scope):
        raise ApiError(403, "SCOPE_MISSING", f"API key lacks scope {scope!r}")
    return key
