"""Strict activation policy for bounded-pilot token-rotation waivers."""

from __future__ import annotations

from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import ClassVar, Literal

from pydantic import BaseModel, ConfigDict, ValidationError, field_validator


class TokenRotationPolicyError(ValueError):
    """The activation checklist has no valid token-rotation decision."""


@dataclass(frozen=True, slots=True)
class ActivationChecklistBindings:
    """Authorities that a bounded-pilot waiver must match exactly."""

    customer_key: str
    profile_root: Path
    data_root: Path
    registry_path: Path


class TokenRotationWaiver(BaseModel):
    """Exact owner risk acceptance when rotation is not required."""

    model_config: ClassVar[ConfigDict] = ConfigDict(
        extra="forbid", frozen=True, strict=True
    )

    status: Literal["not_required"]
    reason: Literal["existing_token_no_known_exposure"]
    scope: Literal["bounded_pilot"]
    approved_by: Literal["owner_operator"]
    approved: Literal[True]
    risk_acknowledged: Literal[True]

    @field_validator("approved", "risk_acknowledged", mode="before")
    @classmethod
    def require_exact_true(cls, value: object) -> object:
        if value is not True:
            raise ValueError("waiver acknowledgement must be exactly true")
        return value


def validate_token_rotation_policy(
    evidence: Mapping[str, object],
    payload: Mapping[str, object],
    bindings: ActivationChecklistBindings,
) -> None:
    """Accept exact legacy rotation or an exact, fully bound pilot waiver."""
    token_rotated = evidence.get("token_rotated")
    if token_rotated is True:
        return
    if token_rotated is not False:
        raise TokenRotationPolicyError(
            "token_rotated must be exactly true or false with a waiver"
        )

    waiver = evidence.get("token_rotation_waiver")
    try:
        _ = TokenRotationWaiver.model_validate(waiver)
    except ValidationError as exc:
        raise TokenRotationPolicyError("token rotation waiver is invalid") from exc

    _require_binding(payload, "customer_key", bindings.customer_key)
    _require_path_binding(payload, "profile_root", bindings.profile_root)
    _require_path_binding(payload, "data_root", bindings.data_root)
    _require_path_binding(payload, "registry_path", bindings.registry_path)


def _require_binding(
    payload: Mapping[str, object],
    key: str,
    expected: str,
) -> None:
    value = payload.get(key)
    if type(value) is not str or value != expected:
        raise TokenRotationPolicyError(
            f"token rotation waiver {key} binding is invalid"
        )


def _require_path_binding(
    payload: Mapping[str, object],
    key: str,
    expected: Path,
) -> None:
    value = payload.get(key)
    if type(value) is not str:
        raise TokenRotationPolicyError(
            f"token rotation waiver {key} binding is invalid"
        )
    try:
        matches = Path(value).resolve() == expected.resolve()
    except (OSError, RuntimeError, ValueError):
        matches = False
    if not matches:
        raise TokenRotationPolicyError(
            f"token rotation waiver {key} binding is invalid"
        )
