from __future__ import annotations

import json
from datetime import date
from pathlib import Path

import pytest

from checkin_cli.customer_admin import (
    CustomerAdminError,
    activate_customer,
    load_runtime_customer_registry,
)
from tests.test_customer_admin import (
    _activation_fixture,
    _canonical_digest,
    _membership_evidence,
)


def _snapshot(root: Path) -> dict[str, bytes]:
    return {
        str(path.relative_to(root)): path.read_bytes()
        for path in root.rglob("*")
        if path.is_file()
    }


@pytest.mark.parametrize("fault", ["digest", "stale", "missing_binding"])
def test_membership_evidence_faults_fail_before_any_activation_mutation(
    tmp_path: Path, fault: str
) -> None:
    profile, _, data_root, checklist = _activation_fixture(tmp_path)
    evidence_path = _membership_evidence(profile, "client_001")
    payload = json.loads(evidence_path.read_text())
    if fault == "digest":
        payload["membership_results"][0]["status"] = "member"
    elif fault == "stale":
        payload["observed_at_utc"] = "2026-08-01T00:00:00+00:00"
        payload["evidence_sha256"] = _canonical_digest(
            {key: value for key, value in payload.items() if key != "evidence_sha256"}
        )
    else:
        del payload["profile_wheel_sha256"]
        payload["evidence_sha256"] = _canonical_digest(
            {key: value for key, value in payload.items() if key != "evidence_sha256"}
        )
    evidence_path.write_text(json.dumps(payload, sort_keys=True, separators=(",", ":")) + "\n")
    evidence_path.chmod(0o600)
    before = _snapshot(profile)

    with pytest.raises(CustomerAdminError, match="membership"):
        activate_customer(
            profile,
            data_root,
            "client_001",
            checklist,
            evidence_path,
            kst_date=date(2026, 8, 1),
        )

    assert _snapshot(profile) == before
    assert not (profile / "data/customer-activation-journal.json").exists()


def test_runtime_rejects_committed_receipt_with_removed_membership_binding(
    tmp_path: Path,
) -> None:
    profile, _, data_root, checklist = _activation_fixture(tmp_path)
    evidence_path = _membership_evidence(profile, "client_001")
    activate_customer(
        profile,
        data_root,
        "client_001",
        checklist,
        evidence_path,
        kst_date=date(2026, 8, 1),
    )
    journal_path = profile / "data/customer-activation-journal.json"
    journal = json.loads(journal_path.read_text())
    del journal["staff_chat_inventory_sha256"]
    journal_path.write_text(json.dumps(journal))
    journal_path.chmod(0o600)

    with pytest.raises(CustomerAdminError, match="membership"):
        load_runtime_customer_registry(profile)
