"""Typed path-free config parsing for weekly reminder bootstrap."""

from __future__ import annotations

import hashlib
import json
import sys
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from types import TracebackType
from typing import TYPE_CHECKING, Literal, Self, final
from typing_extensions import TypeIs

from .nutrition_weekly_operations_config import JsonValue
from .nutrition_weekly_reminder_resources import ResourceRegistrar

AUTHORITY_COMPROMISE_BOUNDARY = (
    "simultaneous pre-startup rewrite of trusted config and operator receipt"
)

if TYPE_CHECKING:
    from gateway.config import PlatformConfig
    from .nutrition_weekly_operations_authority import (
        WeeklyOperationsAuthorityReceipt,
    )
    from .nutrition_weekly_operations_config import WeeklyOperationsConfig
    from .nutrition_weekly_reminder_authority import (
        RegisteredWeeklyReminderCustomer,
    )


class WeeklyReminderStartupAuthorityIncident(RuntimeError):
    """Enabled operator authority or profile capability is unavailable."""


class BootstrapConfigIncident(WeeklyReminderStartupAuthorityIncident):
    pass


def _is_mapping(value: JsonValue | None) -> TypeIs[Mapping[str, JsonValue]]:
    return isinstance(value, Mapping)


def mapping(value: JsonValue | None) -> Mapping[str, JsonValue]:
    if _is_mapping(value):
        return value
    raise BootstrapConfigIncident("weekly reminder startup config is invalid")


def relative_name(raw: JsonValue | None, label: str) -> str:
    path = Path(raw) if isinstance(raw, str) else Path()
    if not path.parts or path == Path(".") or path.is_absolute() or ".." in path.parts:
        raise BootstrapConfigIncident(f"weekly reminder {label} is invalid")
    return str(path)


def profile_root(config: PlatformConfig) -> Path:
    nutrition = mapping(config.extra.get("nutrition_coaching"))
    raw = nutrition.get("profile_root")
    if not isinstance(raw, str) or not raw.strip():
        raise BootstrapConfigIncident(
            "weekly reminder profile root is unavailable"
        )
    return Path(raw)


def _canonical(value: Mapping[str, JsonValue]) -> bytes:
    try:
        return json.dumps(
            value, sort_keys=True, separators=(",", ":")
        ).encode()
    except (TypeError, ValueError) as error:
        raise BootstrapConfigIncident(
            "operator authority input is not canonical JSON"
        ) from error


def _source(config: PlatformConfig) -> Mapping[str, JsonValue]:
    nutrition = mapping(config.extra.get("nutrition_coaching"))
    authority_source = nutrition.get("weekly_operations_authority_source")
    if authority_source != "operator":
        raise BootstrapConfigIncident(
            "enabled weekly reminder requires operator authority input"
        )
    return {
        "weekly_operations_authority_source": authority_source,
        "weekly_operations": mapping(nutrition.get("weekly_operations")),
        "weekly_operations_authority": mapping(
            nutrition.get("weekly_operations_authority")
        ),
        "profile_root": nutrition.get("profile_root"),
        "registry_path": nutrition.get("registry_path"),
        "weekly_operations_authority_path": nutrition.get(
            "weekly_operations_authority_path", "weekly-authority"
        ),
    }


@dataclass(frozen=True, slots=True)
class _CloseOwnedOnError:
    owned: OwnedWeeklyReminderCustomers

    def __enter__(self) -> None:
        return None

    def __exit__(
        self,
        kind: type[BaseException] | None,
        _error: BaseException | None,
        _traceback: TracebackType | None,
    ) -> Literal[False]:
        if kind is not None:
            self.owned.close()
        return False


@final
class OwnedWeeklyReminderCustomers:
    """Own every bootstrap resource from first open through adapter shutdown."""

    __slots__ = ("_customers", "registrar")

    def __init__(self) -> None:
        self._customers: list[RegisteredWeeklyReminderCustomer] = []
        self.registrar: ResourceRegistrar = ResourceRegistrar()

    @property
    def customers(self) -> tuple[RegisteredWeeklyReminderCustomer, ...]:
        return tuple(self._customers)

    def add_customer(self, customer: RegisteredWeeklyReminderCustomer) -> None:
        self._customers.append(customer)

    def close(self) -> None:
        self.registrar.close()
        self._customers.clear()

    def close_on_error(self) -> _CloseOwnedOnError:
        return _CloseOwnedOnError(self)

    def __enter__(self) -> Self:
        return self

    def __exit__(
        self,
        _kind: type[BaseException] | None,
        _error: BaseException | None,
        _traceback: TracebackType | None,
    ) -> Literal[False]:
        self.close()
        return False


def new_owned_weekly_reminder_customers() -> OwnedWeeklyReminderCustomers:
    sys.audit("nutricoach.weekly_reminder.owned_container_before_construction")
    owned = OwnedWeeklyReminderCustomers()
    sys.audit("nutricoach.weekly_reminder.owned_container_after_construction")
    return owned


@dataclass(frozen=True, slots=True)
class CandidateAuthorityVerifierFields:
    candidate_digest: str
    config_binding_digest: str
    registry_identity_binding_digest: str
    receipt_integrity_digest: str
    operator_input_integrity_digest: str
    consent_digest: str
    feature_epoch: str
    enabled_customer_keys: tuple[str, ...]
    owner_binding: tuple[str, str, int]


@dataclass(frozen=True, slots=True)
class OperatorAuthoritySnapshot:
    weekly: WeeklyOperationsConfig
    receipt: WeeklyOperationsAuthorityReceipt
    canonical_bytes: bytes
    integrity_digest: str

    @property
    def candidate_verifier_fields(self) -> CandidateAuthorityVerifierFields:
        owner = self.receipt.owner
        return CandidateAuthorityVerifierFields(
            self.receipt.candidate_digest,
            self.receipt.config_digest,
            self.receipt.registry_identity.binding_digest,
            self.receipt.integrity_digest,
            self.integrity_digest,
            self.receipt.consent_digest,
            self.receipt.feature_epoch,
            self.receipt.enabled_customer_keys,
            (owner.user_id, owner.chat_id, owner.version),
        )

    def verify(self, config: PlatformConfig) -> None:
        current = _canonical(_source(config))
        if (
            current != self.canonical_bytes
            or hashlib.sha256(current).hexdigest() != self.integrity_digest
        ):
            raise BootstrapConfigIncident(
                "operator authority input changed during bootstrap"
            )


def capture_operator_authority(
    config: PlatformConfig,
) -> OperatorAuthoritySnapshot | None:
    from .nutrition_weekly_operations_authority import (
        parse_weekly_operations_authority,
    )
    from .nutrition_weekly_operations_config import (
        parse_weekly_operations_config,
    )

    weekly = parse_weekly_operations_config(config.extra)
    if not weekly.enabled:
        return None
    source = _source(config)
    nutrition = mapping(config.extra.get("nutrition_coaching"))
    receipt = parse_weekly_operations_authority(
        mapping(nutrition.get("weekly_operations_authority"))
    )
    canonical = _canonical(source)
    return OperatorAuthoritySnapshot(
        weekly, receipt, canonical, hashlib.sha256(canonical).hexdigest()
    )
