"""Authored synthetic geometry tests; ordinary CI performs no dataset/provider lookup."""

import hashlib
import io
import json
import zipfile
from pathlib import Path
from typing import Any

import pytest
import shapely
from pydantic import ValidationError
from shapely.geometry import Polygon, box, mapping

from app.geo.contracts import PlaceCandidate, PlaceSearchRequest
from app.geo.selection import SelectedPlaceSnapshot
from app.timezone.boundaries import tbb
from app.timezone.boundaries.contracts import (
    BoundaryProvenance,
    GeographicCoordinates,
    TimezoneBoundaryError,
    TimezoneBoundaryFailure,
    TimezoneBoundaryResult,
    coordinates_from_snapshot,
)

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


@pytest.fixture
def provenance() -> BoundaryProvenance:
    return BoundaryProvenance(
        dataset="timezone-boundary-builder",
        release="2026c",
        variant="comprehensive-no-oceans",
        manifest_sha256=tbb.MANIFEST_SHA256,
        archive_sha256=tbb.ARCHIVE_SHA256,
        geometry_sha256=tbb.GEOMETRY_SHA256,
        catalog_sha256=tbb.CATALOG_SHA256,
        resolver="tbb-planar.v1",
        shapely_version="2.1.2",
        geos_version="3.13.1",
        numpy_version="2.5.3",
        python_version="3.12.14",
        execution_target="linux-amd64",
        license="ODbL-1.0",
        attribution="synthetic test only",
        license_url="https://opendatacommons.org/licenses/odbl/1-0/",
    )


@pytest.mark.parametrize("value", [True, "1", None, float("nan"), float("inf"), -float("inf")])
@pytest.mark.parametrize("field", ["latitude", "longitude"])
def test_coordinates_reject_invalid_values(field: str, value: Any) -> None:
    with pytest.raises(ValidationError):
        GeographicCoordinates.model_validate({"latitude": 0.0, "longitude": 0.0, field: value})


@pytest.mark.parametrize("latitude,longitude", [(90.01, 0), (-90.01, 0), (0, 180.01), (0, -180.01)])
def test_coordinate_ranges_match_candidate(latitude: float, longitude: float) -> None:
    with pytest.raises(ValidationError):
        GeographicCoordinates(latitude=latitude, longitude=longitude)
    with pytest.raises(ValidationError):
        PlaceCandidate(
            provider="fixture",
            source_id="1",
            display_name="x",
            latitude=latitude,
            longitude=longitude,
        )


def test_snapshot_copy_revalidation_and_privacy() -> None:
    candidate = PlaceCandidate(
        provider="fixture",
        source_id="x",
        display_name="private place",
        latitude=-0.0,
        longitude=151.2,
    )
    snapshot = SelectedPlaceSnapshot(
        schema_version="selected-place.v1",
        candidate=candidate,
        search_request=PlaceSearchRequest(query="private query"),
        selected_index=0,
        result_count=1,
    )
    coordinates = coordinates_from_snapshot(snapshot)
    assert coordinates.latitude.hex() == (-0.0).hex()
    assert set(coordinates.model_dump()) == {"latitude", "longitude"}
    assert repr(coordinates) == "GeographicCoordinates()"
    with pytest.raises(ValidationError):
        coordinates.latitude = 12
    forged = snapshot.model_copy(
        update={"candidate": candidate.model_copy(update={"latitude": 100})}
    )
    with pytest.raises(TimezoneBoundaryError) as error:
        coordinates_from_snapshot(forged)
    assert error.value.category == TimezoneBoundaryFailure.INVALID_INPUT
    assert "private" not in str(error.value)


@pytest.mark.parametrize(
    "latitude,longitude,expected,reason",
    [
        (1, 1, "resolved", None),
        (0, 1, "boundary", "polygon_boundary"),
        (0, 0, "boundary", "polygon_boundary"),
        (3, 3, "no_match", "outside_dataset"),
        (90, 0, "boundary", "coordinate_seam_or_pole"),
        (-90, 0, "boundary", "coordinate_seam_or_pole"),
        (0, 180, "boundary", "coordinate_seam_or_pole"),
        (0, -180, "boundary", "coordinate_seam_or_pole"),
        (1, 1e-12, "resolved", None),
        (1, -1e-12, "no_match", "outside_dataset"),
    ],
)
def test_outcomes(
    latitude: float,
    longitude: float,
    expected: str,
    reason: str | None,
    provenance: BoundaryProvenance,
) -> None:
    geometry = box(0, 0, 2, 2)
    result = tbb._outcome(
        GeographicCoordinates(latitude=latitude, longitude=longitude),
        ("Europe/Test",),
        (geometry,),
        shapely.STRtree([geometry]),
        provenance,
    )
    assert result.status == expected and result.reason == reason
    assert TimezoneBoundaryResult.model_validate_json(result.model_dump_json()) == result
    assert result.tzid == ("Europe/Test" if expected == "resolved" else None)


def test_overlaps_no_arbitrary_winner_or_order_dependence(provenance: BoundaryProvenance) -> None:
    shapes = (box(0, 0, 3, 3), box(1, 1, 4, 4))
    coordinates = GeographicCoordinates(latitude=2, longitude=2)
    result = tbb._outcome(
        coordinates, ("Zone/Z", "Zone/A"), shapes, shapely.STRtree(shapes), provenance
    )
    reversed_result = tbb._outcome(
        coordinates, ("Zone/A", "Zone/Z"), shapes[::-1], shapely.STRtree(shapes[::-1]), provenance
    )
    assert result == reversed_result
    assert result.status == "ambiguous" and result.candidate_ids == ("Zone/A", "Zone/Z")
    same = tbb._outcome(
        coordinates, ("Zone/A", "Zone/A"), shapes, shapely.STRtree(shapes), provenance
    )
    assert same.status == "resolved"


def test_holes_shared_edges_and_conservative_boundary(provenance: BoundaryProvenance) -> None:
    polygon = Polygon(
        [(0, 0), (4, 0), (4, 4), (0, 4), (0, 0)], holes=[[(1, 1), (2, 1), (2, 2), (1, 2), (1, 1)]]
    )
    for lon, lat, status in [(1.5, 1.5, "no_match"), (1, 1, "boundary"), (3, 3, "resolved")]:
        result = tbb._outcome(
            GeographicCoordinates(latitude=lat, longitude=lon),
            ("Zone/A",),
            (polygon,),
            shapely.STRtree([polygon]),
            provenance,
        )
        assert result.status == status
    shapes = (box(0, 0, 2, 2), box(1, 0, 3, 2))
    result = tbb._outcome(
        GeographicCoordinates(latitude=1, longitude=1),
        ("Zone/A", "Zone/B"),
        shapes,
        shapely.STRtree(shapes),
        provenance,
    )
    assert result.status == "boundary" and len(result.candidate_ids) == 2


def document(geometry: dict[str, Any] | None = None) -> bytes:
    value = {
        "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "properties": {"tzid": "Zone/A"},
                "geometry": geometry or mapping(box(0, 0, 1, 1)),
            }
        ],
    }
    return json.dumps(value).encode()


def test_incremental_parser_valid_multipolygon_and_catalog() -> None:
    names, shapes = tbb._parse_geometry(
        document(mapping(shapely.MultiPolygon([box(0, 0, 1, 1), box(2, 2, 3, 3)]))),
        frozenset({"Zone/A"}),
    )
    assert names == ("Zone/A",) and shapes[0].geom_type == "MultiPolygon"


@pytest.mark.parametrize(
    "raw",
    [
        b"[]",
        b"{}",
        b"null",
        b"not json",
        b'{"type":"FeatureCollection","features":[',
        document() + b"garbage",
        document().replace(b'"tzid": "Zone/A"', b'"tzid":"Zone/A","tzid":"Zone/A"'),
    ],
)
def test_parser_rejects_malformed_payload(raw: bytes) -> None:
    with pytest.raises((TimezoneBoundaryError, ValueError, IndexError)):
        tbb._parse_geometry(raw, frozenset({"Zone/A"}))


@pytest.mark.parametrize(
    "geometry",
    [
        {"type": "Point", "coordinates": [0, 0]},
        {"type": "Polygon", "coordinates": []},
        {"type": "Polygon", "coordinates": [[[0, 0], [1, 0], [1, 1], [0, 1]]]},
        {"type": "Polygon", "coordinates": [[[0, 0], [1, 1], [0, 1], [1, 0], [0, 0]]]},
        {"type": "Polygon", "coordinates": [[[0, 0], [181, 0], [1, 1], [0, 0]]]},
        {"type": "Polygon", "coordinates": [[[0, 0], [True, 0], [1, 1], [0, 0]]]},
        {"type": "Polygon", "coordinates": [[[0, 0], ["1", 0], [1, 1], [0, 0]]]},
        {"type": "Polygon", "coordinates": [[[-170, 0], [170, 0], [170, 1], [-170, 1], [-170, 0]]]},
    ],
)
def test_geometry_validation_is_fail_closed(geometry: dict[str, Any]) -> None:
    with pytest.raises(TimezoneBoundaryError):
        tbb._parse_geometry(document(geometry), frozenset({"Zone/A"}))


def test_unknown_catalog_zone_and_trailing_comma_rejected() -> None:
    with pytest.raises(TimezoneBoundaryError):
        tbb._parse_geometry(document(), frozenset({"Zone/B"}))
    raw = document().replace(b"}]}", b"},]}")
    with pytest.raises(TimezoneBoundaryError):
        tbb._parse_geometry(raw, frozenset({"Zone/A"}))


def test_exact_pole_segment_is_not_misclassified_as_unsplit_seam() -> None:
    tbb._validate_ring([[-180, -90], [180, -90], [0, -80], [-180, -90]])


def test_missing_and_corrupt_artifacts_fail_before_parsing(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    # Isolate integrity behavior from the separately tested deployment-runtime gate.
    monkeypatch.setattr(tbb, "_require_runtime", lambda: None)
    with pytest.raises(TimezoneBoundaryError) as missing:
        tbb.TBBTimezoneBoundaryResolver(tmp_path)
    assert missing.value.category == TimezoneBoundaryFailure.ARTIFACT_UNAVAILABLE
    (tmp_path / "timezones.geojson.zip").write_bytes(b"private-data-corrupt")
    with pytest.raises(TimezoneBoundaryError) as corrupt:
        tbb.TBBTimezoneBoundaryResolver(tmp_path)
    assert corrupt.value.category == TimezoneBoundaryFailure.ARTIFACT_INTEGRITY
    assert "private-data" not in str(corrupt.value) and str(tmp_path) not in str(corrupt.value)


def test_result_signed_zero_json_replay(provenance: BoundaryProvenance) -> None:
    result = TimezoneBoundaryResult(
        schema_version="timezone-boundary.v1",
        coordinates=GeographicCoordinates(latitude=-0.0, longitude=-0.0),
        provenance=provenance,
        status="no_match",
        reason="outside_dataset",
    )
    replayed = TimezoneBoundaryResult.model_validate_json(result.model_dump_json())
    assert replayed.coordinates.latitude.hex() == "-0x0.0p+0"
    assert replayed.coordinates.longitude.hex() == "-0x0.0p+0"


@pytest.mark.parametrize(
    "exception,category",
    [
        (RecursionError, TimezoneBoundaryFailure.ARTIFACT_INVALID),
        (MemoryError, TimezoneBoundaryFailure.ARTIFACT_UNAVAILABLE),
    ],
)
def test_constructor_sanitizes_parser_resource_failures(
    tmp_path: Path,
    monkeypatch: pytest.MonkeyPatch,
    exception: type[Exception],
    category: TimezoneBoundaryFailure,
) -> None:
    raw = document()
    buffer = io.BytesIO()
    with zipfile.ZipFile(buffer, "w") as archive:
        archive.writestr("combined.json", raw)
    monkeypatch.setattr(tbb, "_require_runtime", lambda: None)
    monkeypatch.setattr(tbb, "GEOMETRY_BYTES", len(raw))
    monkeypatch.setattr(tbb, "GEOMETRY_SHA256", hashlib.sha256(raw).hexdigest())
    monkeypatch.setattr(tbb, "FEATURE_COUNT", 1)
    monkeypatch.setattr(
        tbb,
        "_read_verified",
        lambda path, size, digest: buffer.getvalue() if path.suffix == ".zip" else b'["Zone/A"]',
    )

    def fail(*args: object) -> None:
        raise exception("sensitive diagnostic")

    monkeypatch.setattr(tbb, "_parse_geometry", fail)
    with pytest.raises(TimezoneBoundaryError) as failure:
        tbb.TBBTimezoneBoundaryResolver(tmp_path)
    assert failure.value.category == category
    assert "sensitive" not in str(failure.value)
    assert failure.value.__suppress_context__


def test_read_allocation_failure_is_safe(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
    def fail(*args: object, **kwargs: object) -> None:
        raise MemoryError("private path")

    monkeypatch.setattr(Path, "open", fail)
    with pytest.raises(TimezoneBoundaryError) as failure:
        tbb._read_verified(tmp_path / "unused", 1, "0" * 64)
    assert failure.value.category == TimezoneBoundaryFailure.ARTIFACT_UNAVAILABLE
    assert "private" not in str(failure.value)


def test_wrong_native_version_fails_before_file_access(
    monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
    monkeypatch.setattr(shapely, "geos_version_string", "wrong")
    with pytest.raises(TimezoneBoundaryError) as failure:
        tbb.TBBTimezoneBoundaryResolver(tmp_path)
    assert failure.value.category == TimezoneBoundaryFailure.UNSUPPORTED_RUNTIME


def test_manifest_identity_matches_runtime_constants() -> None:
    raw = (ROOT / "data/timezone-manifests/tbb-2026c-comprehensive-no-oceans.v1.json").read_bytes()
    assert hashlib.sha256(raw).hexdigest() == tbb.MANIFEST_SHA256
    manifest = json.loads(raw)
    for name, digest, size in [
        ("archive", tbb.ARCHIVE_SHA256, tbb.ARCHIVE_BYTES),
        ("catalog", tbb.CATALOG_SHA256, tbb.CATALOG_BYTES),
        ("geometry", tbb.GEOMETRY_SHA256, tbb.GEOMETRY_BYTES),
    ]:
        assert manifest[name]["sha256"] == digest and manifest[name]["size"] == size


@pytest.mark.parametrize(
    "update",
    [
        {"status": "resolved"},
        {"candidate_ids": ("Zone/A",)},
        {"tzid": "Zone/A"},
        {"schema_version": "future"},
        {"birth_date": "1976-01-01"},
    ],
)
def test_result_invariants_and_separation(
    provenance: BoundaryProvenance, update: dict[str, Any]
) -> None:
    value = {
        "schema_version": "timezone-boundary.v1",
        "coordinates": {"latitude": 0, "longitude": 0},
        "provenance": provenance,
        "status": "no_match",
        "reason": "outside_dataset",
    }
    value.update(update)
    with pytest.raises(ValidationError):
        TimezoneBoundaryResult.model_validate(value)


def test_boundary_code_imports_no_network_historical_or_participant_module() -> None:
    import ast

    imports = []
    for path in (ROOT / "app/timezone/boundaries").glob("*.py"):
        for node in ast.walk(ast.parse(path.read_text())):
            if isinstance(node, ast.ImportFrom):
                imports.append(node.module or "")
            elif isinstance(node, ast.Import):
                imports.extend(alias.name for alias in node.names)
    forbidden = (
        "httpx",
        "requests",
        "socket",
        "urllib",
        "zoneinfo",
        "datetime",
        "app.timezone.resolution",
        "app.ephemeris",
        "app.participants",
    )
    assert not any(name.startswith(forbidden) for name in imports)
