"""Authored private markers and offline rule fixtures; no personal records/provider calls."""

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

import pytest
from pydantic import ValidationError

from app.core.provenance.build import SOURCE_REPOSITORY
from app.domain.birth import RawBirthInput
from app.domain.calculations.contracts import (
    CalculationPayload,
    CalculationRequest,
    CalculationResult,
    SelectedBirthInput,
    canonical_bytes,
    result_for,
)
from app.domain.participants import ParticipantContext
from app.ephemeris.ports.ephemeris import (
    EphemerisError,
    EphemerisFailure,
    EphemerisRequest,
    EphemerisResult,
)
from app.ephemeris.swiss.adapter import SwissEphemeris
from app.geo.contracts import PlaceCandidate, PlaceSearchRequest
from app.geo.selection import PlaceSearchResult
from app.services import calculation_worker
from app.services.calculation import CalculationError, CalculationService, build_calculation_service
from app.services.calculation_worker import CalculationWorker
from app.services.place_selection import PlaceSelectionService
from app.services.western_natal import WesternNatalService
from app.timezone.boundaries.contracts import GeographicCoordinates, TimezoneBoundaryResult
from app.timezone.boundaries.identity import pinned_provenance
from app.timezone.resolution import tzdb

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


def selected(
    query: str = "Санкт-Петербург private-marker",
    date: str = "1976-06-15",
    time: str = "12:00",
    latitude: float = 59.93863,
    longitude: float = 30.31413,
    fold: int | None = None,
) -> SelectedBirthInput:
    result = PlaceSearchResult(
        request=PlaceSearchRequest(query=query),
        candidates=(
            PlaceCandidate(
                provider="geonames",
                source_id="498817",
                display_name="Private selected label",
                latitude=latitude,
                longitude=longitude,
                attribution="GeoNames CC BY 4.0",
            ),
        ),
    )
    return SelectedBirthInput(
        raw=RawBirthInput.model_validate(
            {
                "date": date,
                "time": time,
                "place_query": query,
            }
        ),
        selected_place=PlaceSelectionService.select(result, selected_index=0),
        fold_choice=fold,
    )


def request() -> CalculationRequest:
    return CalculationRequest(
        person_a=selected(),
        person_b=selected(
            "Sydney private-marker", "1985-01-15", latitude=-33.86785, longitude=151.20732
        ),
        context_a=ParticipantContext(),
        context_b=ParticipantContext(),
    )


class Boundary:
    def __init__(self) -> None:
        self.calls: list[GeographicCoordinates] = []
        self.status: str = "resolved"

    def resolve(self, coordinates: GeographicCoordinates) -> TimezoneBoundaryResult:
        self.calls.append(coordinates)
        fields: dict[str, Any] = {"status": self.status}
        if self.status == "resolved":
            fields["tzid"] = "Europe/Moscow" if coordinates.latitude > 0 else "Australia/Sydney"
        elif self.status == "no_match":
            fields["reason"] = "outside_dataset"
        elif self.status == "ambiguous":
            fields.update(
                reason="multiple_zone_interiors", candidate_ids=("Asia/Shanghai", "Asia/Urumqi")
            )
        else:
            fields.update(reason="coordinate_seam_or_pole")
        return TimezoneBoundaryResult.model_validate(
            dict(
                schema_version="timezone-boundary.v1",
                coordinates=coordinates,
                provenance=pinned_provenance(),
                **fields,
            )
        )


class Astronomy:
    def __init__(self) -> None:
        self.calls: list[EphemerisRequest] = []

    def calculate(self, value: EphemerisRequest) -> EphemerisResult:
        self.calls.append(value)
        positions = (
            [84.376738910, 305.859342803]
            if value.utc.year == 1976
            else [294.824026632, 218.687525249]
        )
        limitations = ["modelled-ut1-not-measured-earth-orientation"]
        if value.utc.year < 1972:
            limitations.append("pre1972-proleptic-utc-used-as-ut1-proxy")
        elif value.utc.year >= 2017:
            limitations.append("leap-table-frozen-after-2016-not-a-future-prediction")
        return SwissEphemeris._result(
            value,
            {
                "positions": [x.hex() for x in positions],
                "jd_tt_hex": (2451545.0).hex(),
                "jd_ut1_hex": (2451545.0).hex(),
                "limitations": limitations,
            },
        )


@pytest.fixture
def pipeline(monkeypatch: pytest.MonkeyPatch) -> tuple[CalculationService, Boundary, Astronomy]:
    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)
    boundary, astronomy = Boundary(), Astronomy()
    service = CalculationService(
        boundary,
        tzdb.PinnedCivilTimeResolver(Path("unused-fixtures")),
        WesternNatalService(astronomy),
    )
    return service, boundary, astronomy


def test_full_pipeline_and_manifest(
    pipeline: tuple[CalculationService, Boundary, Astronomy],
) -> None:
    service, boundary, astronomy = pipeline
    value = request()
    result = service.calculate(value)
    a, b = result.payload.person_a, result.payload.person_b
    assert a.civil.utc == dt.datetime(1976, 6, 15, 9, tzinfo=dt.UTC)
    assert b.civil.utc == dt.datetime(1985, 1, 15, 1, tzinfo=dt.UTC)
    assert a.boundary.tzid == "Europe/Moscow" and b.boundary.tzid == "Australia/Sydney"
    assert result.payload.request == value and result.payload.request is not value
    assert len(boundary.calls) == 2 and len(astronomy.calls) == 4
    assert [x.utc for x in astronomy.calls] == [a.civil.utc, b.civil.utc, a.civil.utc, b.civil.utc]
    assert (
        result.manifest.result_sha256
        == hashlib.sha256(canonical_bytes(result.payload.model_dump(mode="json"))).hexdigest()
    )
    assert result.manifest.scoring_profile is None
    assert result.manifest.scoring_profile_sha256 is None
    assert result.manifest.ephemeris == a.natal.astronomy.provenance
    assert result.manifest.civil == (a.civil.provenance, b.civil.provenance)
    assert result.manifest.boundary == a.boundary.provenance
    assert (
        result.manifest.source_repository
        == result.manifest.ephemeris.source_repository
        == SOURCE_REPOSITORY
    )
    assert result.manifest.methodology_sha256 == result.payload.synastry.policy_sha256
    encoded = result.model_dump_json()
    assert CalculationResult.model_validate_json(encoded) == result
    astronomy.calls.clear()
    assert service.verify_result(result) == result and len(astronomy.calls) == 4
    assert result.model_dump_json() == service.calculate(value).model_dump_json()
    with pytest.raises(ValidationError):
        result.schema_version = "calculation-result.v1"


def test_context_is_separate_and_cannot_change_facts(
    pipeline: tuple[CalculationService, Boundary, Astronomy],
) -> None:
    service, _, _ = pipeline
    value = request()
    original = service.calculate(value)
    changed = service.calculate(
        value.model_copy(update={"context_a": ParticipantContext(sex_code="OpaqueX")})
    )
    assert original.payload.person_a == changed.payload.person_a
    assert original.payload.person_b == changed.payload.person_b
    assert original.payload.synastry == changed.payload.synastry
    for field in (
        "input_sha256",
        "boundary_sha256",
        "civil_sha256",
        "natal_sha256",
        "synastry_sha256",
        "facts_sha256",
    ):
        assert getattr(original.manifest, field) == getattr(changed.manifest, field)
    assert original.manifest.context_sha256 != changed.manifest.context_sha256
    assert original.manifest.result_sha256 != changed.manifest.result_sha256
    explicit_null = service.calculate(
        value.model_copy(update={"context_a": ParticipantContext(sex_code=None)})
    )
    assert explicit_null == original


def test_exact_query_binding_and_actual_selected_values() -> None:
    value = selected(query="  Санкт-Петербург private-marker  ")
    assert value.raw.place_query == value.selected_place.search_request.query
    assert value.selected_place.candidate.source_id == "498817"
    for query in ("Санкт-Петербург PRIVATE-marker", "Санкт-Петербург  private-marker"):
        raw = value.raw.model_copy(update={"place_query": query})
        with pytest.raises(ValidationError):
            SelectedBirthInput(raw=raw, selected_place=value.selected_place)
    with pytest.raises(ValidationError):
        CalculationRequest(person_a=value, person_b=value)  # type: ignore[call-arg]


@pytest.mark.parametrize("location", ["root", "raw", "candidate", "selection", "query", "context"])
def test_nested_copied_extras_rejected_before_work(
    pipeline: tuple[CalculationService, Boundary, Astronomy],
    location: str,
) -> None:
    service, boundary, astronomy = pipeline
    value = request()
    selected_input = value.person_b
    extra = {"secret_role": "Private hidden marker"}
    if location == "root":
        value = value.model_copy(update=extra)
    elif location == "context":
        value = value.model_copy(update={"context_a": value.context_a.model_copy(update=extra)})
    else:
        snapshot = selected_input.selected_place
        if location == "raw":
            selected_input = selected_input.model_copy(
                update={"raw": selected_input.raw.model_copy(update=extra)}
            )
        elif location == "selection":
            snapshot = snapshot.model_copy(update=extra)
        elif location == "query":
            snapshot = snapshot.model_copy(
                update={"search_request": snapshot.search_request.model_copy(update=extra)}
            )
        else:
            snapshot = snapshot.model_copy(
                update={"candidate": snapshot.candidate.model_copy(update=extra)}
            )
        if location != "raw":
            selected_input = selected_input.model_copy(update={"selected_place": snapshot})
        value = value.model_copy(update={"person_b": selected_input})
    with pytest.raises(CalculationError, match="invalid_input") as caught:
        service.calculate(value)
    assert caught.value.__context__ is None and caught.value.__cause__ is None
    assert not boundary.calls and not astronomy.calls


@pytest.mark.parametrize("status", ["no_match", "boundary", "ambiguous"])
def test_unresolved_geography_never_guesses_or_calls_native(
    pipeline: tuple[CalculationService, Boundary, Astronomy],
    status: str,
) -> None:
    service, boundary, astronomy = pipeline
    boundary.status = status
    with pytest.raises(CalculationError, match="unresolved_geography") as caught:
        service.calculate(request())
    assert caught.value.stage == "geography" and caught.value.person == "A"
    assert not astronomy.calls


@pytest.mark.parametrize(
    "date,fold,error",
    [
        ("1985-03-03", None, "ambiguous_local_time"),
        ("1985-10-27", None, "nonexistent_local_time"),
        ("1985-10-27", 0, "nonexistent_local_time"),
        ("1985-01-15", 1, "invalid_fold"),
    ],
)
def test_second_civil_failure_is_explicit_and_zero_native(
    pipeline: tuple[CalculationService, Boundary, Astronomy],
    date: str,
    fold: int | None,
    error: str,
) -> None:
    service, _, astronomy = pipeline
    value = request().model_copy(
        update={"person_b": selected("Sydney", date, "02:30", -33.86785, 151.20732, fold)}
    )
    with pytest.raises(CalculationError, match=error) as caught:
        service.calculate(value)
    assert caught.value.stage == "civil" and caught.value.person == "B"
    assert caught.value.__context__ is None and not astronomy.calls


def test_explicit_fold_preserved(pipeline: tuple[CalculationService, Boundary, Astronomy]) -> None:
    service, _, _ = pipeline
    instants = []
    for fold in (0, 1):
        value = request().model_copy(
            update={
                "person_b": selected("Sydney", "1985-03-03", "02:30", -33.86785, 151.20732, fold)
            }
        )
        result = service.calculate(value)
        assert result.payload.person_b.civil.fold_choice == fold
        instants.append(result.payload.person_b.civil.utc)
    assert instants[1] - instants[0] == dt.timedelta(hours=1)


def test_civil_verify_mandatory_before_utc_consumer(
    pipeline: tuple[CalculationService, Boundary, Astronomy],
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    service, _, astronomy = pipeline

    def reject(value: Any) -> Any:
        assert not astronomy.calls
        raise RuntimeError("private exception carrying birth input")

    monkeypatch.setattr(service._civil, "verify_result", reject)
    with pytest.raises(CalculationError, match="invalid_result") as caught:
        service.calculate(request())
    assert caught.value.stage == "civil" and caught.value.__context__ is None
    assert "private" not in str(caught.value) and not astronomy.calls


@pytest.mark.parametrize("field", ["manifest", "nested_extra", "overflow", "huge_decimal", "utc"])
def test_tampered_transport_is_guarded(
    pipeline: tuple[CalculationService, Boundary, Astronomy],
    field: str,
) -> None:
    service, _, astronomy = pipeline
    original = service.calculate(request())
    value = original.model_dump()
    if field == "manifest":
        value["manifest"]["result_sha256"] = "0" * 64
    else:
        astro = value["payload"]["person_a"]["natal"]["astronomy"]
        if field == "nested_extra":
            astro["positions"][0]["secret_role"] = "private"
        elif field == "overflow":
            astro["jd_tt_hex"] = "0x1p99999"
        elif field == "huge_decimal":
            astro["positions"][0]["longitude"] = "90." + "0" * 200000
        else:
            astro["utc"] = "2000-01-01T12:00:00Z"
    invalid = CalculationResult.model_construct(**value)
    astronomy.calls.clear()
    with pytest.raises(CalculationError, match="invalid_input") as caught:
        service.verify_result(invalid)
    assert caught.value.__context__ is None and not astronomy.calls


def test_consistent_shape_and_rehashed_forgery_is_not_authenticity(
    pipeline: tuple[CalculationService, Boundary, Astronomy],
) -> None:
    service, _, _ = pipeline
    original = service.calculate(request())
    data = original.payload.model_dump()
    for person in ("person_a", "person_b"):
        data[person]["natal"]["astronomy"]["provenance"]["binary_sha256"] = "0" * 64
        data["synastry"][person]["astronomy"]["provenance"]["binary_sha256"] = "0" * 64
    forged = result_for(CalculationPayload.model_validate(data))
    with pytest.raises(CalculationError, match="replay_mismatch"):
        service.verify_result(forged)


def test_privacy_and_failures(
    pipeline: tuple[CalculationService, Boundary, Astronomy],
    monkeypatch: pytest.MonkeyPatch,
    caplog: pytest.LogCaptureFixture,
) -> None:
    service, _, astronomy = pipeline
    value = request()
    result = service.calculate(value)
    for model in (
        value,
        value.person_a,
        result,
        result.payload,
        result.manifest,
        result.payload.person_a,
    ):
        assert "private-marker" not in repr(model) and "1976" not in repr(model)

    def fail(value: EphemerisRequest) -> EphemerisResult:
        raise EphemerisError(EphemerisFailure.TIMEOUT)

    monkeypatch.setattr(astronomy, "calculate", fail)
    with pytest.raises(CalculationError, match="timeout") as caught:
        service.calculate(value)
    assert caught.value.person == "A" and caught.value.stage == "natal"
    assert caught.value.__context__ is None and caught.value.__cause__ is None
    assert caplog.text == ""


def test_async_direct_guard(pipeline: tuple[CalculationService, Boundary, Astronomy]) -> None:
    service, boundary, astronomy = pipeline

    async def check() -> None:
        with pytest.raises(CalculationError, match="async_context"):
            service.calculate(request())
        with pytest.raises(CalculationError, match="async_context"):
            build_calculation_service(Path("unused"), Path("unused"), Path("unused"))

    asyncio.run(check())
    assert not boundary.calls and not astronomy.calls


def test_worker_success_shutdown_and_closed(
    pipeline: tuple[CalculationService, Boundary, Astronomy],
) -> None:
    service, _, astronomy = pipeline

    async def check() -> None:
        worker = CalculationWorker(service)
        try:
            result = await worker.calculate(request())
            assert result.payload.person_a.civil.utc.year == 1976
            assert len(astronomy.calls) == 4
        finally:
            await worker.close()
        await worker.close()
        with pytest.raises(CalculationError, match="closed"):
            await worker.calculate(request())

    asyncio.run(check())


@pytest.mark.parametrize("mode", ["cancel", "timeout", "shutdown", "cancel_shutdown"])
def test_busy_capacity_survives_caller_and_drains_offloop(
    pipeline: tuple[CalculationService, Boundary, Astronomy],
    monkeypatch: pytest.MonkeyPatch,
    mode: str,
) -> None:
    service, _, astronomy = pipeline
    original = astronomy.calculate
    entered, release = threading.Event(), threading.Event()

    def blocked(value: EphemerisRequest) -> EphemerisResult:
        entered.set()
        assert release.wait(5), "test must release native fixture"
        return original(value)

    monkeypatch.setattr(astronomy, "calculate", blocked)
    monkeypatch.setattr(calculation_worker, "RESPONSE_SECONDS", 0.05 if mode == "timeout" else 25)

    async def check() -> None:
        loop = asyncio.get_running_loop()
        failures: list[dict[str, Any]] = []
        loop.set_exception_handler(lambda loop, context: failures.append(context))
        worker = CalculationWorker(service)
        task = asyncio.create_task(worker.calculate(request()))
        try:
            assert await asyncio.to_thread(entered.wait, 2)
            with pytest.raises(CalculationError, match="busy"):
                await worker.calculate(request())
            # The process-wide synchronous budget also rejects a second facade/service call.
            with pytest.raises(CalculationError, match="busy"):
                await asyncio.to_thread(service.calculate, request())
            if mode == "cancel":
                task.cancel()
                with pytest.raises(asyncio.CancelledError):
                    await task
            elif mode == "timeout":
                with pytest.raises(CalculationError, match="timeout"):
                    await task
            else:
                closing = asyncio.create_task(worker.close())
                await asyncio.sleep(0.01)
                assert not closing.done()
                if mode == "cancel_shutdown":
                    closing.cancel()
                    with pytest.raises(asyncio.CancelledError):
                        await closing
            shutting_down = mode in {"shutdown", "cancel_shutdown"}
            with pytest.raises(CalculationError, match="closed" if shutting_down else "busy"):
                await worker.calculate(request())
            release.set()
            if mode == "shutdown":
                await closing
            if shutting_down:
                await task
        finally:
            release.set()
            await worker.close()
        await asyncio.sleep(0)
        assert len(astronomy.calls) == 4 and not failures

    asyncio.run(check())


def test_artifact_scope_and_no_exposure_or_network() -> None:
    scope = runpy.run_path(str(ROOT / "scripts/timezone-ci-scope.py"))
    assert scope["required"]("main", ["app/services/calculation.py"])
    assert scope["required"]("main", ["app/domain/calculations/contracts.py"])
    from app.api.application import create_app

    assert not any("calculation" in getattr(route, "path", "") for route in create_app().routes)
    source = (ROOT / "app/services/calculation.py").read_text()
    assert "httpx" not in source and "Geocoder" not in source and "sqlalchemy" not in source
    assert "ParticipantContext" not in source and "sex_code" not in source


def test_wrong_coordinate_and_replayed_civil_source_fail_before_native(
    pipeline: tuple[CalculationService, Boundary, Astronomy],
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    service, boundary, astronomy = pipeline
    original = boundary.resolve

    def wrong_coordinate(coordinates: GeographicCoordinates) -> TimezoneBoundaryResult:
        return original(GeographicCoordinates(latitude=0.0, longitude=0.0))

    with monkeypatch.context() as patch:
        patch.setattr(boundary, "resolve", wrong_coordinate)
        with pytest.raises(CalculationError, match="invalid_result") as caught:
            service.calculate(request())
        assert caught.value.stage == "geography" and not astronomy.calls
    resolve = service._civil.resolve

    def wrong_date(
        raw: RawBirthInput, source: TimezoneBoundaryResult, *, fold_choice: int | None = None
    ) -> Any:
        shifted = RawBirthInput(
            date=raw.date + dt.timedelta(days=1), time=raw.time, place_query=raw.place_query
        )
        return resolve(shifted, source, fold_choice=fold_choice)

    monkeypatch.setattr(service._civil, "resolve", wrong_date)
    # A separate pinned verifier accepts this as a valid fact for the wrong day. The
    # orchestrator must still compare it with the requested source before consuming UTC.
    verifier = tzdb.PinnedCivilTimeResolver(Path("unused-fixtures"))
    monkeypatch.setattr(service._civil, "verify_result", verifier.verify_result)
    with pytest.raises(CalculationError, match="invalid_result") as caught:
        service.calculate(request())
    assert caught.value.stage == "civil" and not astronomy.calls
    assert caught.value.__context__ is None


def test_running_revision_is_in_provenance_and_drift_is_not_replay(
    pipeline: tuple[CalculationService, Boundary, Astronomy],
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from app.domain.calculations import contracts
    from app.ephemeris.swiss import adapter

    service, _, _ = pipeline
    monkeypatch.setattr(contracts, "build_sha", lambda: "a" * 40)
    monkeypatch.setattr(adapter, "build_sha", lambda: "a" * 40)
    result = service.calculate(request())
    assert result.manifest.ace_git_sha == "a" * 40
    assert result.manifest.ephemeris.ace_git_sha == "a" * 40
    monkeypatch.setattr(contracts, "build_sha", lambda: "b" * 40)
    monkeypatch.setattr(adapter, "build_sha", lambda: "b" * 40)
    with pytest.raises(CalculationError, match="replay_mismatch"):
        service.verify_result(result)


def test_cancelled_awaiter_does_not_log_eventual_failure_and_capacity_recovers(
    pipeline: tuple[CalculationService, Boundary, Astronomy],
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    service, _, astronomy = pipeline
    original = astronomy.calculate
    entered, release = threading.Event(), threading.Event()

    def fail(value: EphemerisRequest) -> EphemerisResult:
        entered.set()
        assert release.wait(5)
        raise RuntimeError("private-marker late failure")

    monkeypatch.setattr(astronomy, "calculate", fail)

    async def check() -> None:
        failures: list[dict[str, Any]] = []
        asyncio.get_running_loop().set_exception_handler(
            lambda loop, context: failures.append(context)
        )
        worker = CalculationWorker(service)
        task = asyncio.create_task(worker.calculate(request()))
        try:
            assert await asyncio.to_thread(entered.wait, 2)
            task.cancel()
            with pytest.raises(asyncio.CancelledError):
                await task
            with pytest.raises(CalculationError, match="busy"):
                await worker.calculate(request())
        finally:
            release.set()
            await worker.close()
        await asyncio.sleep(0)
        assert not failures
        monkeypatch.setattr(astronomy, "calculate", original)
        next_worker = CalculationWorker(service)
        try:
            assert (
                await next_worker.calculate(request())
            ).schema_version == "calculation-result.v1"
        finally:
            await next_worker.close()

    asyncio.run(check())


def test_worker_start_failure_is_safe_and_slot_can_retry(
    pipeline: tuple[CalculationService, Boundary, Astronomy],
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    service, _, _ = pipeline

    async def check() -> None:
        worker = CalculationWorker(service)
        submit = worker._executor.submit

        def fail(*args: Any, **kwargs: Any) -> Any:
            raise RuntimeError("private-marker thread start failure")

        try:
            monkeypatch.setattr(worker._executor, "submit", fail)
            with pytest.raises(CalculationError, match="invalid_result") as caught:
                await worker.calculate(request())
            assert caught.value.__context__ is None
            assert "private-marker" not in str(caught.value)
            monkeypatch.setattr(worker._executor, "submit", submit)
            assert (await worker.calculate(request())).schema_version == "calculation-result.v1"
        finally:
            await worker.close()

    asyncio.run(check())
