"""No external data/provider calls: trust/replay/provenance and input separation checks."""

import ast
import asyncio
import datetime as dt
import runpy
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Any

import pytest
from pydantic import ValidationError

from app.engines.western.natal import WesternNatalFacts
from app.ephemeris.ports.ephemeris import (
    EphemerisError,
    EphemerisFailure,
    EphemerisRequest,
    EphemerisResult,
)
from app.ephemeris.swiss.adapter import SwissEphemeris
from app.services.western_natal import NatalError, NatalFailure, WesternNatalService

UTC = dt.datetime(2000, 1, 1, 12, tzinfo=dt.UTC)
ROOT = Path(__file__).resolve().parents[2]


def astronomy(utc: dt.datetime = UTC) -> EphemerisResult:
    limitations = ["modelled-ut1-not-measured-earth-orientation"]
    if utc.year < 1972:
        limitations.append("pre1972-proleptic-utc-used-as-ut1-proxy")
    elif utc.year >= 2017:
        limitations.append("leap-table-frozen-after-2016-not-a-future-prediction")
    return SwissEphemeris._result(
        EphemerisRequest(utc=utc),
        {
            "positions": [(280.368922859698).hex(), (223.323800853027).hex()],
            "jd_tt_hex": (2451545.0007428704).hex(),
            "jd_ut1_hex": (2451545.0).hex(),
            "limitations": limitations,
        },
    )


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

    def calculate(self, request: EphemerisRequest) -> EphemerisResult:
        self.requests.append(request)
        return astronomy(request.utc)


@pytest.mark.parametrize("year", [1900, 1976, 1985, 2000, 2017, 2100])
def test_complete_source_fact_and_limitations_are_preserved(year: int) -> None:
    port = FixtureEphemeris()
    request = EphemerisRequest(utc=UTC.replace(year=year))
    facts = WesternNatalService(port).calculate(request)
    assert facts.astronomy == astronomy(request.utc)
    assert tuple(item.body for item in facts.astronomy.positions) == ("sun", "moon")
    assert facts.schema_version == "western-natal.v1"
    assert facts.projection == "western-tropical-sun-moon.v1"
    assert facts.astronomy.provenance.numerical_policy == "binary64-to-decimal-9dp-half-even.v1"
    assert port.requests == [request] and port.requests[0] is not request
    assert WesternNatalFacts.model_validate_json(facts.model_dump_json()) == facts
    with pytest.raises(ValidationError):
        facts.projection = "western-tropical-sun-moon.v1"


@pytest.mark.parametrize("field", ["sex", "role", "person_a", "latitude", "birthplace", "score"])
def test_non_astronomical_fields_are_not_part_of_natal_facts(field: str) -> None:
    with pytest.raises(ValidationError):
        WesternNatalFacts.model_validate({"astronomy": astronomy(), field: "private"})
    assert set(WesternNatalFacts.model_fields) == {"schema_version", "projection", "astronomy"}


@pytest.mark.parametrize("value", [None, {}, True, "private-birth"])
def test_invalid_request_is_safe_and_causes_zero_calls(value: Any) -> None:
    port = FixtureEphemeris()
    with pytest.raises(NatalError) as caught:
        WesternNatalService(port).calculate(value)
    assert caught.value.category == NatalFailure.INVALID_INPUT
    assert caught.value.__context__ is None
    assert "private" not in str(caught.value) and not port.requests


def test_constructed_request_and_nested_result_cannot_bypass_validation() -> None:
    port = FixtureEphemeris()
    service = WesternNatalService(port)
    request = EphemerisRequest(utc=UTC).model_copy(update={"utc": UTC.replace(tzinfo=None)})
    with pytest.raises(NatalError, match="invalid_input"):
        service.calculate(request)
    assert not port.requests
    valid = astronomy()
    broken_body = valid.positions[0].model_copy(update={"longitude": 999})
    broken_result = valid.model_copy(update={"positions": (broken_body, valid.positions[1])})
    for value in (broken_result, {**valid.model_dump(), "positions": broken_result.positions}):
        with pytest.raises(ValidationError):
            WesternNatalFacts.model_validate({"astronomy": value})


def test_wrong_utc_or_invalid_result_is_rejected_without_sensitive_context() -> None:
    class FaultyPort:
        def calculate(self, request: EphemerisRequest) -> EphemerisResult:
            return astronomy(UTC + dt.timedelta(days=1))

    with pytest.raises(NatalError, match="invalid_result") as caught:
        WesternNatalService(FaultyPort()).calculate(EphemerisRequest(utc=UTC))
    assert caught.value.__context__ is None

    class CorruptPort:
        def calculate(self, request: EphemerisRequest) -> EphemerisResult:
            return astronomy().model_copy(update={"positions": ()})

    with pytest.raises(NatalError, match="invalid_result") as caught:
        WesternNatalService(CorruptPort()).calculate(EphemerisRequest(utc=UTC))
    assert caught.value.__context__ is None


def test_native_failures_remain_explicit_not_empty_facts() -> None:
    class FailingPort:
        def calculate(self, request: EphemerisRequest) -> EphemerisResult:
            raise EphemerisError(EphemerisFailure.FALLBACK_REJECTED)

    with pytest.raises(EphemerisError, match="fallback_rejected"):
        WesternNatalService(FailingPort()).calculate(EphemerisRequest(utc=UTC))


@pytest.mark.parametrize("field", ["body", "jd_tt_hex", "jd_ut1_hex"])
def test_overflowing_hex_is_sanitized_at_both_service_boundaries(field: str) -> None:
    source = astronomy()
    if field == "body":
        body = source.positions[0].model_copy(update={"binary64_hex": "0x1p99999"})
        source = source.model_copy(update={"positions": (body, source.positions[1])})
    else:
        source = source.model_copy(update={field: "0x1p99999"})

    class OverflowPort:
        def calculate(self, request: EphemerisRequest) -> EphemerisResult:
            return source

    with pytest.raises(NatalError, match="^Natal fact failure: invalid_result$") as caught:
        WesternNatalService(OverflowPort()).calculate(EphemerisRequest(utc=UTC))
    assert caught.value.__context__ is None and caught.value.__cause__ is None
    port = FixtureEphemeris()
    with pytest.raises(NatalError, match="^Natal fact failure: invalid_input$") as caught:
        WesternNatalService(port).verify_facts(WesternNatalFacts.model_construct(astronomy=source))
    assert not port.requests
    assert caught.value.__context__ is None and caught.value.__cause__ is None


def test_port_must_return_declared_model_not_structural_dict() -> None:
    class DictionaryPort:
        def calculate(self, request: EphemerisRequest) -> Any:
            return astronomy().model_dump()

    with pytest.raises(NatalError, match="invalid_result"):
        WesternNatalService(DictionaryPort()).calculate(EphemerisRequest(utc=UTC))


@pytest.mark.parametrize("mutation", ["hash", "longitude", "build"])
def test_shape_valid_forgery_requires_replay_and_is_rejected(mutation: str) -> None:
    service = WesternNatalService(FixtureEphemeris())
    facts = service.calculate(EphemerisRequest(utc=UTC))
    assert service.verify_facts(facts) == facts
    payload = facts.model_dump()
    if mutation == "hash":
        payload["astronomy"]["provenance"]["binary_sha256"] = "0" * 64
    elif mutation == "build":
        payload["astronomy"]["provenance"]["ace_git_sha"] = "a" * 40
    else:
        payload["astronomy"]["positions"][0]["longitude"] = "42.000000000"
        payload["astronomy"]["positions"][0]["binary64_hex"] = (42.0).hex()
    forged = WesternNatalFacts.model_validate(payload)
    with pytest.raises(NatalError, match="replay_mismatch") as caught:
        service.verify_facts(forged)
    assert caught.value.__context__ is None


def test_invalid_replay_fails_before_native_call() -> None:
    port = FixtureEphemeris()
    forged = WesternNatalFacts.model_construct(astronomy="private-birth")
    with pytest.raises(NatalError, match="invalid_input") as caught:
        WesternNatalService(port).verify_facts(forged)
    assert not port.requests and caught.value.__context__ is None


def test_direct_event_loop_invocation_fails_before_call() -> None:
    port = FixtureEphemeris()
    service = WesternNatalService(port)

    async def check() -> None:
        with pytest.raises(NatalError, match="async_context"):
            service.calculate(EphemerisRequest(utc=UTC))
        with pytest.raises(NatalError, match="async_context"):
            service.verify_facts(WesternNatalFacts(astronomy=astronomy()))
        assert not port.requests

    asyncio.run(check())


def test_source_models_are_copied_and_faulty_port_cannot_rewrite_request() -> None:
    source = astronomy()
    facts = WesternNatalFacts(astronomy=source)
    before = facts.model_dump_json()
    object.__setattr__(source.positions[0], "longitude", 0)
    assert facts.model_dump_json() == before

    class MutatingPort:
        def calculate(self, request: EphemerisRequest) -> EphemerisResult:
            object.__setattr__(request, "utc", UTC + dt.timedelta(days=1))
            return astronomy(request.utc)

    request = EphemerisRequest(utc=UTC)
    with pytest.raises(NatalError, match="invalid_result"):
        WesternNatalService(MutatingPort()).calculate(request)
    assert request.utc == UTC


def test_repeat_reverse_concurrency_and_privacy(caplog: pytest.LogCaptureFixture) -> None:
    service = WesternNatalService(FixtureEphemeris())
    requests = [EphemerisRequest(utc=UTC.replace(year=year)) for year in (1900, 1985, 2100)]
    facts = [service.calculate(request) for request in requests]
    with ThreadPoolExecutor(max_workers=2) as executor:
        assert list(executor.map(service.calculate, reversed(requests))) == list(reversed(facts))
    assert len({repr(item) for item in facts}) == 1
    assert "280" not in repr(facts) and "1900" not in str(facts)
    assert caplog.text == ""


def test_natal_boundary_has_no_geography_civil_context_or_api_coupling() -> None:
    for name in ("app/engines/western/natal.py", "app/services/western_natal.py"):
        tree = ast.parse((ROOT / name).read_text())
        imports = []
        for node in ast.walk(tree):
            if isinstance(node, ast.ImportFrom):
                imports.append(node.module)
            elif isinstance(node, ast.Import):
                imports.extend(alias.name for alias in node.names)
        assert all(
            not item
            or not item.startswith(("app.geo", "app.timezone", "app.participant", "app.api"))
            for item in imports
        )
    api_paths = list((ROOT / "app/api").rglob("*.py"))
    assert api_paths
    for path in api_paths:
        assert "western_natal" not in path.read_text() and "WesternNatal" not in path.read_text()


def test_ordinary_branch_natal_changes_trigger_real_artifact_acceptance() -> None:
    required = runpy.run_path(str(ROOT / "scripts/timezone-ci-scope.py"))["required"]
    for path in (
        "app/engines/western/natal.py",
        "app/services/western_natal.py",
        "tests/unit/test_western_natal.py",
    ):
        assert required("main", [path])
