"""Deterministic unit/privacy/process policy tests; no external provider or data download."""

import datetime as dt
import hashlib
import json
import os
import subprocess
from concurrent.futures import ThreadPoolExecutor
from decimal import Decimal, Inexact, Rounded, localcontext
from pathlib import Path
from types import SimpleNamespace
from typing import Any

import pytest
from pydantic import ValidationError

from app.ephemeris.ports.ephemeris import (
    BodyLongitude,
    EphemerisError,
    EphemerisFailure,
    EphemerisRequest,
    longitude_decimal,
)
from app.ephemeris.swiss import adapter as module
from app.ephemeris.swiss import identity, worker

UTC = dt.datetime(1985, 7, 15, 4, tzinfo=dt.UTC)


def test_longitude_policy_ignores_ambient_decimal_precision_and_traps() -> None:
    expected = longitude_decimal(280.368922859698)
    with localcontext() as context:
        context.prec = 2
        context.traps[Inexact] = True
        context.traps[Rounded] = True
        assert longitude_decimal(280.368922859698) == expected
        assert context.prec == 2 and context.traps[Inexact] and context.traps[Rounded]


@pytest.mark.parametrize(
    "value",
    [
        "90." + "0" * 200_000,
        Decimal("90." + "0" * 200_000),
        "0e-999999",
        Decimal("0e999999"),
        "0.000000000000000000000000000000001",
    ],
    ids=["padded-text", "padded-decimal", "tiny-exponent", "huge-exponent", "long-text"],
)
def test_untrusted_longitude_encoding_is_bounded_before_ratio_work(value: Any) -> None:
    with pytest.raises(ValidationError, match="bounded astronomical longitude encoding"):
        BodyLongitude(body="sun", longitude=value, binary64_hex=(90.0).hex())


def test_parent_worker_and_manifest_binary_pins_agree() -> None:
    result = module.SwissEphemeris._result(EphemerisRequest(utc=UTC), native_response())
    assert result.provenance.binary_sha256 == identity.BINARY_SHA256 == worker.BINARY_SHA256
    assert identity.BINARY_SIZE == worker.BINARY_SIZE == 2391504
    manifest = json.loads(
        Path("data/ephemeris-manifests/swiss-de441-1800-2399.v1.json").read_text()
    )
    assert identity.BINARY_SHA256 == manifest["binding"]["binary_sha256"]
    assert identity.BINARY_SIZE == manifest["binding"]["binary_size"]


@pytest.mark.parametrize(
    "limitations", [[], ["private-text"], ["modelled-ut1-not-measured-earth-orientation"] * 2]
)
def test_result_limitation_vocabulary_and_policy_are_closed(limitations: list[str]) -> None:
    payload = native_response()
    payload["limitations"] = limitations
    with pytest.raises(ValidationError):
        module.SwissEphemeris._result(EphemerisRequest(utc=UTC), payload)


@pytest.fixture
def adapter(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> module.SwissEphemeris:
    identities = []
    for name in ("sepl_18.se1", "semo_18.se1"):
        raw = name.encode()
        (tmp_path / name).write_bytes(raw)
        identities.append((name, len(raw), hashlib.sha256(raw).hexdigest()))
    monkeypatch.setattr(module, "DATA", tuple(identities))
    return module.SwissEphemeris(tmp_path)


@pytest.mark.parametrize(
    "value",
    [
        "1985-01-01T00:00:00",
        "1985-01-01T00:00:00+10:00",
        "1800-01-01T00:00:00Z",
        "2101-01-02T00:00:00Z",
        "1985-01-01T00:00:60Z",
        float("nan"),
        True,
        dt.datetime(1985, 1, 1, tzinfo=dt.UTC, fold=1),
    ],
)
def test_request_rejects_unsupported_input(value: Any) -> None:
    with pytest.raises(ValidationError):
        EphemerisRequest(utc=value)


def test_only_utc_not_birth_or_participant_fields() -> None:
    assert set(EphemerisRequest.model_fields) == {"utc"}
    for key in ("date", "time", "timezone", "latitude", "sex", "role", "person_a", "place_query"):
        with pytest.raises(ValidationError):
            EphemerisRequest.model_validate({"utc": UTC, key: "private"})
    assert "1985" not in repr(EphemerisRequest(utc=UTC))


@pytest.mark.parametrize("value", [float("nan"), float("inf"), -0.1, 360.0])
def test_invalid_coordinates_cannot_become_longitudes(value: float) -> None:
    with pytest.raises(ValueError):
        longitude_decimal(value)


def test_explicit_rounding_and_wrap() -> None:
    assert str(longitude_decimal(12.1234567885)) == "12.123456788"
    assert str(longitude_decimal(12.1234567895)) == "12.123456790"
    assert longitude_decimal(359.9999999996) == 0
    with pytest.raises(ValidationError):
        BodyLongitude.model_validate(
            {"body": "sun", "longitude": "42", "binary64_hex": (43.0).hex()}
        )


@pytest.mark.parametrize("mutation", ["missing", "corrupt", "extra", "symlink"])
def test_data_directory_is_fail_closed(
    adapter: module.SwissEphemeris,
    tmp_path: Path,
    mutation: str,
) -> None:
    path = tmp_path / "semo_18.se1"
    if mutation == "missing":
        path.unlink()
    elif mutation == "corrupt":
        path.write_bytes(b"bad")
    elif mutation == "extra":
        (tmp_path / "seleapsec.txt").write_text("unapproved")
    else:
        path.unlink()
        path.symlink_to(tmp_path / "sepl_18.se1")
    with pytest.raises(EphemerisError) as caught:
        module.SwissEphemeris(tmp_path)
    assert caught.value.category == EphemerisFailure.DATA_INTEGRITY
    assert str(tmp_path) not in str(caught.value)


def native_response() -> dict[str, object]:
    return {
        "positions": [(84.0).hex(), (305.0).hex()],
        "jd_tt_hex": (2451545.1).hex(),
        "jd_ut1_hex": (2451545.0).hex(),
        "limitations": ["modelled-ut1-not-measured-earth-orientation"],
    }


def test_fresh_process_boundary_and_retained_bytes(
    adapter: module.SwissEphemeris,
    tmp_path: Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    calls: list[Path] = []
    monkeypatch.setenv("SE_EPHE_PATH", "/untrusted")
    monkeypatch.setenv("LD_PRELOAD", "/untrusted")
    monkeypatch.setenv("ACE_GEONAMES_USERNAME", "private-provider-secret")
    (tmp_path / "semo_18.se1").write_bytes(b"mutated after validation")

    def run(command: list[str], **kwargs: Any) -> SimpleNamespace:
        assert command[1:] == ["-I", str(module._WORKER)]
        assert "1985" not in repr(command)
        assert kwargs["env"] == {"PATH": os.defpath, "LC_ALL": "C", "TZ": "UTC"}
        assert kwargs["timeout"] == 5 and kwargs["stderr"] == subprocess.DEVNULL
        assert json.loads(kwargs["input"]) == {"utc": UTC.isoformat()}
        directory = kwargs["cwd"]
        calls.append(directory)
        assert directory.stat().st_mode & 0o777 == 0o700
        assert {path.name for path in directory.iterdir()} == {"sepl_18.se1", "semo_18.se1"}
        assert (directory / "semo_18.se1").read_bytes() == b"semo_18.se1"
        kwargs["stdout"].write(json.dumps(native_response()).encode())
        return SimpleNamespace(returncode=0)

    monkeypatch.setattr(subprocess, "run", run)
    first = adapter.calculate(EphemerisRequest(utc=UTC))
    assert adapter.calculate(EphemerisRequest(utc=UTC)) == first
    assert calls[0] != calls[1] and all(not path.exists() for path in calls)
    assert "1985" not in repr(first) and "84.0" not in repr(first)
    assert first.provenance.returned_flags == (2, 2)
    assert first.provenance.data_origin == "DE441"
    assert first.positions[0].body == "sun"
    with pytest.raises(ValidationError):
        first.utc = UTC


@pytest.mark.parametrize("kind", ["timeout", "native", "fallback", "runtime", "malformed", "huge"])
def test_safe_failures_release_capacity(
    adapter: module.SwissEphemeris,
    monkeypatch: pytest.MonkeyPatch,
    kind: str,
) -> None:
    expected = {
        "timeout": EphemerisFailure.TIMEOUT,
        "native": EphemerisFailure.NATIVE_FAILURE,
        "fallback": EphemerisFailure.FALLBACK_REJECTED,
        "runtime": EphemerisFailure.UNSUPPORTED_RUNTIME,
        "malformed": EphemerisFailure.INVALID_RESULT,
        "huge": EphemerisFailure.NATIVE_FAILURE,
    }[kind]

    def run(command: list[str], **kwargs: Any) -> SimpleNamespace:
        if kind == "timeout":
            raise subprocess.TimeoutExpired(command, 5, output=b"private-birth-data")
        body = {
            "native": b"private-native-path",
            "fallback": b'{"error":"fallback_rejected"}',
            "runtime": b'{"error":"unsupported_runtime"}',
            "malformed": b"private-birth-data",
            "huge": b"x" * 8193,
        }[kind]
        kwargs["stdout"].write(body)
        return SimpleNamespace(returncode=1 if kind == "native" else 0)

    monkeypatch.setattr(subprocess, "run", run)
    for _ in range(4):
        with pytest.raises(EphemerisError) as caught:
            adapter.calculate(EphemerisRequest(utc=UTC))
        assert caught.value.category == expected
        assert "private" not in str(caught.value) and "1985" not in str(caught.value)
        assert caught.value.__suppress_context__ or caught.value.__context__ is None


def test_capacity_and_invalid_copy_fail_before_spawn(
    adapter: module.SwissEphemeris,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    def forbidden(*args: Any, **kwargs: Any) -> None:
        pytest.fail("native process must not start")

    monkeypatch.setattr(subprocess, "run", forbidden)
    forged = EphemerisRequest(utc=UTC).model_copy(update={"utc": UTC.replace(tzinfo=None)})
    with pytest.raises(EphemerisError, match="invalid_input"):
        adapter.calculate(forged)
    assert module._CAPACITY.acquire() and module._CAPACITY.acquire()
    try:
        with pytest.raises(EphemerisError, match="busy"):
            adapter.calculate(EphemerisRequest(utc=UTC))
    finally:
        module._CAPACITY.release()
        module._CAPACITY.release()


def test_real_native_transport_rejects_unverified_fallback_without_logging(
    adapter: module.SwissEphemeris,
    caplog: pytest.LogCaptureFixture,
) -> None:
    # Actual pinned .so and isolated interpreter see invalid synthetic files. This is not a
    # MockTransport/manual logger simulation: no Moshier answer or native warning escapes.
    with pytest.raises(EphemerisError) as caught:
        adapter.calculate(EphemerisRequest(utc=UTC))
    assert caught.value.category in {
        EphemerisFailure.NATIVE_FAILURE,
        EphemerisFailure.FALLBACK_REJECTED,
    }
    assert caplog.text == ""


def test_worker_time_policy_does_not_call_implicit_utc_fallback(
    tmp_path: Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    tidal: list[float] = []
    swe = SimpleNamespace(
        TIDAL_DE441=-25.936,
        DELTAT_AUTOMATIC=-1e-10,
        GREG_CAL=1,
        SUN=0,
        MOON=1,
        set_ephe_path=lambda path: None,
        set_tid_acc=tidal.append,
        set_delta_t_userdef=lambda value: None,
        julday=lambda *args: 2451545.0,
        deltat_ex=lambda jd, flags: (64 / 86400, ""),
        calc=lambda jd, body, flags: ((280.0, 0.0, 1.0, 0.0, 0.0, 0.0), flags, ""),
        get_current_file_data=lambda index: (
            str(tmp_path / ("sepl_18.se1" if index == 0 else "semo_18.se1")),
            2378400.0,
            2597700.0,
            441,
        ),
        close=lambda: None,
    )
    monkeypatch.setattr(worker, "_library", lambda: swe)
    value = worker.run(dt.datetime(2000, 1, 1, tzinfo=dt.UTC), tmp_path)
    assert tidal == [-25.936]
    assert value["jd_tt_hex"] == (2451545.0 + 64.184 / 86400).hex()
    before = worker.run(dt.datetime(1900, 1, 1, tzinfo=dt.UTC), tmp_path)
    limitations = before["limitations"]
    assert isinstance(limitations, list)
    assert "pre1972-proleptic-utc-used-as-ut1-proxy" in limitations
    future = worker.run(dt.datetime(2100, 1, 1, tzinfo=dt.UTC), tmp_path)
    assert future["jd_tt_hex"] == (2451545.0 + 69.184 / 86400).hex()
    swe.calc = lambda jd, body, flags: ((280.0, 0.0, 1.0, 0.0, 0.0, 0.0), 4, "fallback")
    with pytest.raises(worker.WorkerFailure, match="fallback_rejected"):
        worker.run(UTC, tmp_path)


def test_concurrent_mocked_results_do_not_share_native_state(
    adapter: module.SwissEphemeris,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    def run(command: list[str], **kwargs: Any) -> SimpleNamespace:
        kwargs["stdout"].write(json.dumps(native_response()).encode())
        return SimpleNamespace(returncode=0)

    monkeypatch.setattr(subprocess, "run", run)
    with ThreadPoolExecutor(max_workers=2) as executor:
        results = list(
            executor.map(lambda _: adapter.calculate(EphemerisRequest(utc=UTC)), range(2))
        )
    assert results[0] == results[1]
