from __future__ import annotations

from datetime import date
from pathlib import Path

from checkin_cli.weekly_operations_summary import build_weekly_operations_summary
import pytest
from checkin_cli.weekly_operations import CustomerKey, WeeklyOperationsConflict
from tests._weekly_operations_correlation_support import CUSTOMER, store_at
from tests._weekly_operations_summary_support import approved_synthetic_week


def test_summary_fails_closed_for_missing_authority_inputs(tmp_path: Path) -> None:
    # Given: one valid aggregate fixture.
    fixture = approved_synthetic_week(tmp_path)
    try:
        # When/Then: neither authority may be omitted at the public builder boundary.
        with pytest.raises(WeeklyOperationsConflict, match="canonical authority is missing"):
            _ = build_weekly_operations_summary(
                None, fixture.sidecar.store, date(2026, 8, 17)
            )
        with pytest.raises(WeeklyOperationsConflict, match="sidecar authority is missing"):
            _ = build_weekly_operations_summary(
                fixture.canonical.source, None, date(2026, 8, 17)
            )
    finally:
        fixture.close()


def test_summary_fails_closed_for_wrong_customer_sidecar(tmp_path: Path) -> None:
    # Given: a registered source and a confirmed sidecar for another customer identity.
    fixture = approved_synthetic_week(tmp_path / "source")
    other = store_at(tmp_path / "other", CustomerKey("other_customer_001"))
    try:
        # When/Then: no aggregate crosses the customer authority boundary.
        with pytest.raises(WeeklyOperationsConflict, match="customer authority disagrees") as raised:
            _ = build_weekly_operations_summary(
                fixture.canonical.source, other.store, date(2026, 8, 17)
            )
        assert str(CUSTOMER) not in str(raised.value)
    finally:
        other.close()
        fixture.close()


def test_summary_fails_closed_for_registry_authority_mismatch(tmp_path: Path) -> None:
    # Given: a same-customer sidecar is rooted in another registered authority tree.
    fixture = approved_synthetic_week(tmp_path / "source")
    unrelated = store_at(tmp_path / "unrelated", CUSTOMER)
    try:
        # When/Then: matching opaque identity cannot bypass the registry authority pin.
        with pytest.raises(WeeklyOperationsConflict, match="registry authority disagrees"):
            _ = build_weekly_operations_summary(
                fixture.canonical.source, unrelated.store, date(2026, 8, 17)
            )
    finally:
        unrelated.close()
        fixture.close()
