"""Authenticated internal request contract for the AroFlo UI worker."""

from __future__ import annotations

import hashlib
import hmac
import os
import time

from flask import Request
from sqlalchemy import select

from config.control_plane import get_control_plane_session
from bridge_platform.tenants.models import TenantIntegration
from bridge_platform.secrets.secrets_manager import SecretsManager


MAX_CLOCK_SKEW = 60


def sign_worker_request(secret: str, method: str, path: str, body: bytes, timestamp: str, nonce: str) -> str:
    digest = hashlib.sha256(body).hexdigest()
    message = "\n".join((method.upper(), path, timestamp, nonce, digest)).encode()
    return hmac.new(secret.encode(), message, hashlib.sha256).hexdigest()


def authenticate_worker_request(request: Request, tenant_id: str) -> None:
    timestamp = request.headers.get("X-AroFlo-Timestamp", "")
    nonce = request.headers.get("X-AroFlo-Nonce", "")
    supplied = request.headers.get("X-AroFlo-Signature", "")
    if not timestamp.isdigit() or not nonce or len(nonce) > 128 or not supplied:
        raise PermissionError("Worker authentication required")
    secret = SecretsManager().get_secret(
        tenant_id=tenant_id,
        app_id="aroflo_connector_app",
        secret_name="ui_worker_shared_secret",
    ) or ""
    if not secret:
        raise PermissionError("Worker authentication required")
    if abs(int(time.time()) - int(timestamp)) > MAX_CLOCK_SKEW:
        raise PermissionError("Worker request expired")
    expected = sign_worker_request(secret, request.method, request.path, request.get_data(cache=True), timestamp, nonce)
    if not hmac.compare_digest(expected, supplied):
        raise PermissionError("Worker signature rejected")
    _consume_nonce(tenant_id, nonce, int(timestamp))


def _consume_nonce(tenant_id: str, nonce: str, timestamp: int) -> None:
    name = "worker_auth_replay"
    cutoff = int(time.time()) - MAX_CLOCK_SKEW
    with get_control_plane_session() as session:
        row = session.execute(select(TenantIntegration).where(
            TenantIntegration.tenant_id == tenant_id,
            TenantIntegration.app_id == "aroflo_connector_app",
            TenantIntegration.integration_name == name,
        ).with_for_update()).scalar_one_or_none()
        if row is None:
            row = TenantIntegration(tenant_id=tenant_id, app_id="aroflo_connector_app",
                                    integration_name=name, status="active", config_json={"nonces": {}})
            session.add(row)
        nonces = {key: value for key, value in ((row.config_json or {}).get("nonces") or {}).items()
                  if int(value) >= cutoff}
        if nonce in nonces:
            raise PermissionError("Worker request replay detected")
        nonces[nonce] = timestamp
        row.config_json = {"nonces": nonces}
        session.commit()
