"""Pinned TZif fixtures, authored dates; no provider or host timezone database."""

import base64
import datetime as dt
import hashlib
import json
from pathlib import Path
from typing import Any

import pytest
from pydantic import ValidationError

from app.domain.birth import RawBirthInput
from app.timezone.boundaries.contracts import (
    GeographicCoordinates,
    TimezoneBoundaryError,
    TimezoneBoundaryResult,
)
from app.timezone.boundaries.identity import (
    pinned_provenance,
    registered_zone_ids,
    validate_registered_boundary_fact,
)
from app.timezone.resolution import tzdb
from app.timezone.resolution.contracts import (
    ARCHIVE_NAME,
    CivilTimeError,
    CivilTimeFailure,
    ResolvedCivilTime,
)

ROOT = Path(__file__).resolve().parents[2]


def fact(zone: str = "Europe/Moscow") -> TimezoneBoundaryResult:
    # Unit fixture: registered identity, synthetic coordinates. Real geometry is tested
    # separately against the retained full TBB artifact, not asserted by this factory.
    return TimezoneBoundaryResult(
        schema_version="timezone-boundary.v1",
        coordinates=GeographicCoordinates(latitude=0.0, longitude=-0.0),
        provenance=pinned_provenance(),
        status="resolved",
        tzid=zone,
    )


def birth(date: str = "1976-06-15", time: str = "12:00") -> RawBirthInput:
    return RawBirthInput.model_validate(
        {"date": date, "time": time, "place_query": "private query"}
    )


@pytest.fixture
def resolver(monkeypatch: pytest.MonkeyPatch) -> tzdb.PinnedCivilTimeResolver:
    encoded = json.loads(
        (ROOT / "tests/fixtures/timezone/tzdb-2026c-golden-zones.json").read_bytes()
    )
    zones = {
        name: base64.b64decode(value["base64"], validate=True) for name, value in encoded.items()
    }
    for name, value in zones.items():
        assert hashlib.sha256(value).hexdigest() == encoded[name]["sha256"]
    monkeypatch.setattr(tzdb, "_load_zones", lambda directory: zones)
    return tzdb.PinnedCivilTimeResolver(Path("unused-unit-fixtures"))


@pytest.mark.parametrize(
    "zone,date,time,utc,offset",
    [
        ("Europe/Moscow", "1976-06-15", "12:00", "1976-06-15T09:00:00Z", 10800),
        ("Asia/Novosibirsk", "1985-01-15", "12:00", "1985-01-15T05:00:00Z", 25200),
        ("Asia/Novosibirsk", "1985-07-15", "12:00", "1985-07-15T04:00:00Z", 28800),
        ("Australia/Sydney", "1985-01-15", "12:00", "1985-01-15T01:00:00Z", 39600),
        ("Australia/Sydney", "1985-07-15", "12:00", "1985-07-15T02:00:00Z", 36000),
        ("Europe/Amsterdam", "1900-01-15", "12:00", "1900-01-15T11:40:28Z", 1172),
        ("Europe/Moscow", "1900-01-15", "12:00", "1900-01-15T09:29:43Z", 9017),
        ("Australia/Lord_Howe", "2020-01-15", "12:00", "2020-01-15T01:00:00Z", 39600),
        ("Australia/Lord_Howe", "2020-07-15", "12:00", "2020-07-15T01:30:00Z", 37800),
        ("Pacific/Kiritimati", "2100-01-01", "00:01", "2099-12-31T10:01:00Z", 50400),
        ("Europe/Moscow", "1900-01-01", "00:00", "1899-12-31T21:29:43Z", 9017),
        ("Europe/Moscow", "2100-12-31", "23:59:59.123456", "2100-12-31T20:59:59.123456Z", 10800),
    ],
)
def test_historical_golden_and_exact_replay(
    resolver: tzdb.PinnedCivilTimeResolver, zone: str, date: str, time: str, utc: str, offset: int
) -> None:
    source = fact(zone)
    result = resolver.resolve(birth(date, time), source)
    assert result.utc == dt.datetime.fromisoformat(utc)
    assert result.offset_seconds == offset
    assert result.boundary == source and result.boundary is not source
    assert result.boundary.coordinates.longitude.hex() == (-0.0).hex()
    assert result.resolution == "unique" and result.fold_choice is None
    replayed = ResolvedCivilTime.model_validate_json(result.model_dump_json())
    assert resolver.verify_result(replayed) == result
    assert "private query" not in result.model_dump_json()
    assert ("pre1970-records-have-limited-assurance" in result.limitations) == (date < "1970")
    assert "modern-geography-not-date-specific-jurisdiction" in result.limitations


@pytest.mark.parametrize(
    "zone,date,time,earlier,later",
    [
        ("Australia/Sydney", "1985-03-03", "02:30", "1985-03-02T15:30:00Z", "1985-03-02T16:30:00Z"),
        (
            "Australia/Lord_Howe",
            "2020-04-05",
            "01:45",
            "2020-04-04T14:45:00Z",
            "2020-04-04T15:15:00Z",
        ),
    ],
)
def test_ambiguity_requires_explicit_choice(
    resolver: tzdb.PinnedCivilTimeResolver,
    zone: str,
    date: str,
    time: str,
    earlier: str,
    later: str,
) -> None:
    with pytest.raises(CivilTimeError) as error:
        resolver.resolve(birth(date, time), fact(zone))
    assert error.value.category == CivilTimeFailure.AMBIGUOUS_LOCAL_TIME
    for fold, expected in enumerate((earlier, later)):
        result = resolver.resolve(birth(date, time), fact(zone), fold_choice=fold)
        assert result.utc == dt.datetime.fromisoformat(expected)
        assert result.resolution == "explicit_fold" and result.fold_choice == fold
        assert resolver.verify_result(result) == result


@pytest.mark.parametrize("fold", [None, 0, 1])
@pytest.mark.parametrize(
    "zone,date,time",
    [
        ("Australia/Sydney", "1985-10-27", "02:30"),
        ("Australia/Lord_Howe", "2020-10-04", "02:15"),
        ("Pacific/Apia", "2011-12-30", "12:00"),
    ],
)
def test_gap_never_corrected(
    resolver: tzdb.PinnedCivilTimeResolver, zone: str, date: str, time: str, fold: int | None
) -> None:
    with pytest.raises(CivilTimeError) as error:
        resolver.resolve(birth(date, time), fact(zone), fold_choice=fold)
    assert error.value.category == CivilTimeFailure.NONEXISTENT_LOCAL_TIME


@pytest.mark.parametrize("fold", [True, False, "0", 0.0, -1, 2, 0, 1])
def test_invalid_or_unnecessary_fold(resolver: tzdb.PinnedCivilTimeResolver, fold: Any) -> None:
    with pytest.raises(CivilTimeError) as error:
        resolver.resolve(birth(), fact(), fold_choice=fold)
    assert error.value.category == CivilTimeFailure.INVALID_FOLD


@pytest.mark.parametrize("date", ["1899-12-31", "2101-01-01"])
def test_range(resolver: tzdb.PinnedCivilTimeResolver, date: str) -> None:
    with pytest.raises(CivilTimeError) as error:
        resolver.resolve(birth(date), fact())
    assert error.value.category == CivilTimeFailure.INVALID_INPUT


@pytest.mark.parametrize(
    "field",
    [
        "archive_sha256",
        "manifest_sha256",
        "geometry_sha256",
        "catalog_sha256",
        "attribution",
        "shapely_version",
        "geos_version",
        "numpy_version",
        "python_version",
        "execution_target",
        "dataset",
        "release",
        "variant",
        "resolver",
        "license",
        "license_url",
    ],
)
def test_boundary_provenance_is_registered_not_just_shape_valid(
    resolver: tzdb.PinnedCivilTimeResolver, field: str
) -> None:
    source = fact()
    changed = source.model_copy(
        update={
            "provenance": source.provenance.model_copy(
                update={field: "0" * 64 if "sha256" in field else "forged"}
            )
        }
    )
    with pytest.raises(TimezoneBoundaryError):
        validate_registered_boundary_fact(changed)
    with pytest.raises(CivilTimeError) as error:
        resolver.resolve(birth(), changed)
    assert error.value.category == CivilTimeFailure.INVALID_INPUT


@pytest.mark.parametrize("zone", ["../Europe/Moscow", "Unregistered/Zone", "UTC", "Europe/Moscow "])
def test_unknown_zone_rejected(resolver: tzdb.PinnedCivilTimeResolver, zone: str) -> None:
    assert len(registered_zone_ids()) == 419
    with pytest.raises(CivilTimeError):
        resolver.resolve(birth(), fact(zone))


def test_unresolved_boundary_is_not_guessed(resolver: tzdb.PinnedCivilTimeResolver) -> None:
    source = fact().model_copy(
        update={"status": "no_match", "tzid": None, "reason": "outside_dataset"}
    )
    with pytest.raises(CivilTimeError) as error:
        resolver.resolve(birth(), source)
    assert error.value.category == CivilTimeFailure.UNRESOLVED_ZONE


@pytest.mark.parametrize(
    "field,value",
    [
        ("date", "not a date"),
        ("time", dt.time(12, fold=1)),
        ("time", dt.time(12, tzinfo=dt.UTC)),
        ("place_query", ""),
    ],
)
def test_revalidate_construct_bypass_without_privacy_leak(
    resolver: tzdb.PinnedCivilTimeResolver, field: str, value: Any, caplog: pytest.LogCaptureFixture
) -> None:
    with pytest.raises(CivilTimeError) as error:
        resolver.resolve(birth().model_copy(update={field: value}), fact())
    assert error.value.category == CivilTimeFailure.INVALID_INPUT
    assert str(error.value) == "Civil time failure: invalid_input"
    assert error.value.__suppress_context__
    assert not caplog.records


def test_result_privacy_immutability_and_verified_replay(
    resolver: tzdb.PinnedCivilTimeResolver,
) -> None:
    result = resolver.resolve(birth(), fact())
    assert "1976" not in repr(result) and "Moscow" not in repr(result)
    with pytest.raises(ValidationError):
        result.offset_seconds = 0
    forged = result.model_copy(
        update={
            "utc": result.utc - dt.timedelta(hours=1),
            "offset_seconds": 14400,
        }
    )
    # Coherent arithmetic alone is insufficient: recompute using exact TZif bytes.
    ResolvedCivilTime.model_validate(forged.model_dump())
    with pytest.raises(CivilTimeError):
        resolver.verify_result(forged)
    for field in ("archive_sha256", "tzdata_source_sha256", "tzcode_source_sha256", "tzif_sha256"):
        forged = result.model_copy(
            update={"provenance": result.provenance.model_copy(update={field: "0" * 64})}
        )
        with pytest.raises(CivilTimeError):
            resolver.verify_result(forged)


def test_artifact_missing_corrupt_and_runtime_guard(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    with pytest.raises(CivilTimeError) as missing:
        tzdb.PinnedCivilTimeResolver(tmp_path)
    assert missing.value.category == CivilTimeFailure.ARTIFACT_UNAVAILABLE
    (tmp_path / ARCHIVE_NAME).write_bytes(b"TZif not a pinned archive")
    with pytest.raises(CivilTimeError) as corrupt:
        tzdb.PinnedCivilTimeResolver(tmp_path)
    assert corrupt.value.category == CivilTimeFailure.ARTIFACT_INTEGRITY
    monkeypatch.setattr("platform.python_version", lambda: "3.12.999")
    with pytest.raises(CivilTimeError) as runtime:
        tzdb.PinnedCivilTimeResolver(tmp_path)
    assert runtime.value.category == CivilTimeFailure.UNSUPPORTED_RUNTIME


def test_no_ambient_zoneinfo_or_network_path() -> None:
    source = (ROOT / "app/timezone/resolution/tzdb.py").read_text()
    assert "ZoneInfo.from_file" in source and "ZoneInfo(" not in source
    for forbidden in (
        "httpx",
        "requests",
        "socket",
        "TZPATH",
        "datetime.now",
        "logging",
        "participant",
    ):
        assert forbidden not in source


@pytest.mark.parametrize(
    "zone,date,offset",
    [
        ("Australia/Sydney", "2100-01-15", 39600),
        ("Australia/Sydney", "2100-07-15", 36000),
        ("America/New_York", "2100-01-15", -18000),
        ("America/New_York", "2100-07-15", -14400),
    ],
)
def test_future_posix_footer_recurrence_not_fixed_last_offset(
    resolver: tzdb.PinnedCivilTimeResolver, zone: str, date: str, offset: int
) -> None:
    result = resolver.resolve(birth(date), fact(zone))
    assert result.offset_seconds == offset
    assert "post-release-rules-are-not-a-prediction-guarantee" in result.limitations


def test_future_fold_gap_and_upper_utc_year_crossing(
    resolver: tzdb.PinnedCivilTimeResolver,
) -> None:
    zone = fact("America/New_York")
    for date, time, category in [
        ("2100-03-14", "02:30", CivilTimeFailure.NONEXISTENT_LOCAL_TIME),
        ("2100-11-07", "01:30", CivilTimeFailure.AMBIGUOUS_LOCAL_TIME),
    ]:
        with pytest.raises(CivilTimeError) as error:
            resolver.resolve(birth(date, time), zone)
        assert error.value.category == category
    for fold, expected in enumerate(("2100-11-07T05:30:00Z", "2100-11-07T06:30:00Z")):
        result = resolver.resolve(birth("2100-11-07", "01:30"), zone, fold_choice=fold)
        assert result.utc == dt.datetime.fromisoformat(expected)
        assert resolver.verify_result(result) == result
    result = resolver.resolve(birth("2100-12-31", "23:30"), zone)
    assert result.utc == dt.datetime(2101, 1, 1, 4, 30, tzinfo=dt.UTC)
    assert resolver.verify_result(result) == result


def test_unresolved_diagnostic_ids_are_also_catalog_bound() -> None:
    source = fact().model_copy(
        update={
            "status": "ambiguous",
            "tzid": None,
            "reason": "multiple_zone_interiors",
            "candidate_ids": ("Europe/Moscow", "Unregistered/Zone"),
        }
    )
    with pytest.raises(TimezoneBoundaryError):
        validate_registered_boundary_fact(source)


@pytest.mark.parametrize("category", list(CivilTimeFailure))
def test_replay_preserves_artifact_failures_without_exposing_context(
    resolver: tzdb.PinnedCivilTimeResolver,
    monkeypatch: pytest.MonkeyPatch,
    category: CivilTimeFailure,
) -> None:
    result = resolver.resolve(birth(), fact())

    def fail(*args: Any, **kwargs: Any) -> ResolvedCivilTime:
        raise CivilTimeError(category)

    monkeypatch.setattr(resolver, "resolve", fail)
    with pytest.raises(CivilTimeError) as error:
        resolver.verify_result(result)
    expected = (
        category
        if category
        in {
            CivilTimeFailure.ARTIFACT_UNAVAILABLE,
            CivilTimeFailure.ARTIFACT_INTEGRITY,
            CivilTimeFailure.ARTIFACT_INVALID,
            CivilTimeFailure.UNSUPPORTED_RUNTIME,
        }
        else CivilTimeFailure.INVALID_INPUT
    )
    assert error.value.category == expected
    assert str(error.value) == f"Civil time failure: {expected.value}"
    assert error.value.__suppress_context__


@pytest.mark.parametrize("date", ["1900-01-15", "1976-06-15", "2100-01-15"])
def test_repr_does_not_disclose_coarse_birth_date_bucket(
    resolver: tzdb.PinnedCivilTimeResolver, date: str
) -> None:
    result = resolver.resolve(birth(date), fact())
    for label in result.limitations:
        assert label not in repr(result)
        assert label in result.model_dump_json()


def test_text_representations_hide_zone_fingerprint_and_fold_facts(
    resolver: tzdb.PinnedCivilTimeResolver,
) -> None:
    results = [
        resolver.resolve(birth("1900-01-15"), fact("Europe/Amsterdam")),
        resolver.resolve(birth(), fact("Europe/Moscow")),
        resolver.resolve(birth("2100-01-15"), fact("America/New_York")),
        *(
            resolver.resolve(
                birth("1985-03-03", "02:30"), fact("Australia/Sydney"), fold_choice=fold
            )
            for fold in (0, 1)
        ),
    ]
    assert len({repr(result) for result in results}) == 1
    assert len({str(result) for result in results}) == 1
    assert len({repr(result.provenance) for result in results}) == 1
    for result in results:
        assert result.boundary.tzid is not None
        for text in (repr(result), str(result), repr(result.provenance), str(result.provenance)):
            assert result.provenance.tzif_sha256 not in text
            assert result.boundary.tzid not in text
        serialized = result.model_dump_json()
        assert result.provenance.tzif_sha256 in serialized
        assert result.boundary.tzid in serialized
        replayed = ResolvedCivilTime.model_validate_json(serialized)
        assert resolver.verify_result(replayed) == result
        assert (
            replayed.resolution == result.resolution and replayed.fold_choice == result.fold_choice
        )
