"""Truthful authority boundary and Todo13 verifier contract tests."""

from __future__ import annotations

import inspect
import sys
from dataclasses import MISSING, fields
from pathlib import Path

import pytest

import gateway.platforms.nutrition_weekly_operations_authority as authority_boundary
import gateway.platforms.nutrition_weekly_operations_registry_identity as registry_boundary
from gateway.platforms.nutrition_weekly_reminder_bootstrap import (
    WeeklyReminderStartupAuthorityIncident,
)
from gateway.platforms.nutrition_weekly_reminder_bootstrap_config import (
    AUTHORITY_COMPROMISE_BOUNDARY,
    BootstrapConfigIncident,
    capture_operator_authority,
    mapping,
)
from gateway.platforms.telegram import TelegramAdapter
from tests.gateway._nutrition_weekly_reminder_support import (
    reminder_owner_fixture,
)
from tests.gateway.test_nutrition_weekly_reminder_bootstrap_boundary_r7 import (
    platform_config,
)


def test_runtime_exposes_no_registry_or_receipt_issuer() -> None:
    for module in (registry_boundary, authority_boundary):
        assert not any(
            token in name.lower()
            for name in dir(module)
            for token in ("issue", "mint", "create", "refresh")
        )
    receipt_fields = fields(
        authority_boundary.WeeklyOperationsAuthorityReceipt
    )
    token = receipt_fields[-1]
    assert token.name == "_token"
    assert token.default is MISSING
    source = inspect.getsource(authority_boundary)
    assert source.count("WeeklyOperationsAuthorityReceipt(") == 1


def test_operator_input_is_captured_once_and_candidate_fields_are_exact(
    tmp_path: Path,
) -> None:
    fixture = reminder_owner_fixture(tmp_path)
    config = platform_config(tmp_path, fixture.extra)
    snapshot = capture_operator_authority(config)
    assert snapshot is not None
    fields = snapshot.candidate_verifier_fields
    assert fields.candidate_digest == snapshot.receipt.candidate_digest
    assert fields.config_binding_digest == snapshot.receipt.config_digest
    assert (
        fields.registry_identity_binding_digest
        == snapshot.receipt.registry_identity.binding_digest
    )
    assert fields.receipt_integrity_digest == snapshot.receipt.integrity_digest
    assert fields.operator_input_integrity_digest == snapshot.integrity_digest

    nutrition = dict(mapping(config.extra.get("nutrition_coaching")))
    nutrition["registry_path"] = "rewritten.json"
    config.extra["nutrition_coaching"] = nutrition
    with pytest.raises(BootstrapConfigIncident):
        snapshot.verify(config)
    fixture.owner.close()


def test_simultaneous_trusted_source_rewrite_is_explicitly_out_of_scope() -> None:
    assert AUTHORITY_COMPROMISE_BOUNDARY == (
        "simultaneous pre-startup rewrite of trusted config and operator receipt"
    )


def _fds() -> frozenset[int]:
    return frozenset(
        int(entry.name) for entry in Path("/proc/self/fd").iterdir()
    )


@pytest.mark.parametrize("attempt", (1, 2))
def test_operator_snapshot_drift_after_customer_construction_closes_all_fds(
    tmp_path: Path, attempt: int,
) -> None:
    assert attempt in (1, 2)
    fixture = reminder_owner_fixture(tmp_path)
    config = platform_config(tmp_path, fixture.extra)
    baseline = _fds()
    active = [True]

    def rewrite_operator_input(event: str, arguments: tuple[str]) -> None:
        if (
            active[0]
            and event == "nutricoach.weekly_reminder.customers_constructed"
            and arguments == ("registry.json",)
        ):
            active[0] = False
            nutrition = dict(mapping(config.extra.get("nutrition_coaching")))
            receipt = dict(mapping(nutrition.get("weekly_operations_authority")))
            receipt["expires_at"] = "2026-08-18T00:00:00+09:00"
            nutrition["weekly_operations_authority"] = receipt
            config.extra["nutrition_coaching"] = nutrition

    sys.addaudithook(rewrite_operator_input)
    try:
        with pytest.raises(WeeklyReminderStartupAuthorityIncident):
            _ = TelegramAdapter(config)
        assert not active[0]
        assert _fds() == baseline
    finally:
        active[0] = False
        fixture.owner.close()


def test_enabled_bootstrap_requires_operator_authority_source_before_profile_open(
    tmp_path: Path,
) -> None:
    fixture = reminder_owner_fixture(tmp_path)
    config = platform_config(tmp_path, fixture.extra)
    nutrition = dict(mapping(config.extra.get("nutrition_coaching")))
    _ = nutrition.pop("weekly_operations_authority_source")
    config.extra["nutrition_coaching"] = nutrition
    baseline = _fds()

    with pytest.raises(WeeklyReminderStartupAuthorityIncident):
        _ = TelegramAdapter(config)

    assert _fds() == baseline
    fixture.owner.close()
