"""Bounded build tooling and exact-source fixture/manifest regression checks."""

import hashlib
import io
import json
import runpy
import tarfile
from pathlib import Path
from typing import Any

import pytest

from app.timezone.resolution import contracts

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


def test_manifest_agrees_with_runtime_and_builder() -> None:
    manifest = json.loads(
        (ROOT / "data/timezone-manifests/tzdb-2026c-packrat-zone-tab.v1.json").read_bytes()
    )
    builder = runpy.run_path(str(ROOT / "scripts/build-tzdb-artifact.py"))
    assert manifest["archive"] == {
        "name": contracts.ARCHIVE_NAME,
        "size": contracts.ARCHIVE_BYTES,
        "sha256": contracts.ARCHIVE_SHA256,
    }
    assert {source["name"]: source["sha256"] for source in manifest["sources"]} == builder[
        "SOURCES"
    ]
    assert manifest["build_policy"] == builder["BUILD_POLICY"] == contracts.BUILD_POLICY


def test_existing_output_and_bad_source_never_compile(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    build = runpy.run_path(str(ROOT / "scripts/build-tzdb-artifact.py"))["build"]
    monkeypatch.setattr("subprocess.run", lambda *args, **kwargs: pytest.fail("must not compile"))
    output = tmp_path / "existing.zip"
    output.write_bytes(b"owner data")
    with pytest.raises(ValueError, match="output already exists"):
        build(tmp_path, output)
    assert output.read_bytes() == b"owner data"
    (tmp_path / "tzcode2026c.tar.gz").write_bytes(b"wrong source")
    with pytest.raises(ValueError, match="source integrity"):
        build(tmp_path, tmp_path / "new.zip")
    assert not (tmp_path / "new.zip").exists()
    assert not list(tmp_path.glob("tzdb-build-*"))


@pytest.mark.parametrize(
    "name,kind", [("../escape", tarfile.REGTYPE), ("symlink", tarfile.SYMTYPE)]
)
def test_unsafe_source_members_rejected(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, name: str, kind: bytes
) -> None:
    build = runpy.run_path(str(ROOT / "scripts/build-tzdb-artifact.py"))["build"]
    stream = io.BytesIO()
    with tarfile.open(fileobj=stream, mode="w:gz") as archive:
        member = tarfile.TarInfo(name)
        member.type = kind
        archive.addfile(member)
    source = tmp_path / "test.tar.gz"
    source.write_bytes(stream.getvalue())
    monkeypatch.setitem(
        build.__globals__, "SOURCES", {source.name: hashlib.sha256(source.read_bytes()).hexdigest()}
    )
    with pytest.raises(ValueError, match="source member"):
        build(tmp_path, tmp_path / "output.zip")
    assert not (tmp_path / "output.zip").exists()


def test_tzdb_acquisition_reuses_verified_cache(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    main = runpy.run_path(str(ROOT / "scripts/prepare-timezone-artifact.py"))["main"]
    assets: list[dict[str, Any]] = []
    for name in ("rules.zip", "code.tar.gz", "data.tar.gz"):
        value = name.encode()
        (tmp_path / name).write_bytes(value)
        assets.append(
            {"name": name, "size": len(value), "sha256": hashlib.sha256(value).hexdigest()}
        )
    manifest = tmp_path / "manifest.json"
    manifest.write_text(json.dumps({"archive": assets[0], "sources": assets[1:]}))
    monkeypatch.setitem(main.__globals__, "TZDB_MANIFEST", manifest)
    monkeypatch.setattr("subprocess.run", lambda *args, **kwargs: pytest.fail("no fallback"))
    main(tmp_path, tzdb=True)
    (tmp_path / "data.tar.gz").write_bytes(b"corrupt")
    with pytest.raises(ValueError):
        main(tmp_path, tzdb=True)


def test_civil_artifact_ci_requires_source_rebuild_and_offline_composition() -> None:
    workflow = (ROOT / ".github/workflows/timezone-artifact.yml").read_text()
    for expected in (
        "scripts/build-tzdb-artifact.py",
        "cmp ",
        "--tzdb",
        "scripts/check-civil-time-artifact.py",
    ):
        assert expected in workflow
    assert workflow.count("--network none") == 5
    assert "scripts/check-calculation-artifact.py" in workflow
    assert "--cpus 2 --memory 1536m" in workflow
    assert "scripts/check-ephemeris-artifact.py" in workflow
    scope = runpy.run_path(str(ROOT / "scripts/timezone-ci-scope.py"))["required"]
    for path in (
        "scripts/build-tzdb-artifact.py",
        "scripts/check-civil-time-artifact.py",
        "tests/fixtures/timezone/example.json",
        "app/domain/birth/raw_input.py",
        "app/geo/providers/geonames.py",
        "app/services/place_selection.py",
    ):
        assert scope("main", [path])
