"""Pin the separate artifact workflow and fail-closed cache/acquisition behavior."""

import hashlib
import json
import runpy
import stat
from pathlib import Path
from typing import Any

import pytest

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


def test_separate_ci_security_and_reproducibility_contract() -> None:
    workflow = (ROOT / ".github/workflows/timezone-artifact.yml").read_text()
    for expected in (
        "contents: read",
        "timeout-minutes: 10",
        "cancel-in-progress: true",
        "group: timezone-artifact-${{ github.event_name }}-",
        "actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683",
        "actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830",
        "--network none",
        "--read-only",
        "--cap-drop ALL",
        "--cpus 2 --memory 4g",
        "--security-opt no-new-privileges",
        "scripts/prepare-timezone-artifact.py",
        "scripts/check-timezone-artifact.py",
        "GIT_SHA=$GITHUB_SHA",
    ):
        assert expected in workflow
    assert "secrets." not in workflow and "pull_request_target" not in workflow
    assert "if: needs.scope.outputs.required == 'true'" in workflow
    assert "if: steps.cache.outputs.cache-hit" not in workflow
    dockerfile = (ROOT / "Dockerfile").read_text()
    assert "python:3.12.14-slim-bookworm@sha256:" in dockerfile
    assert "ghcr.io/astral-sh/uv:0.12.10@sha256:" in dockerfile


@pytest.mark.parametrize(
    "branch,paths,expected",
    [
        ("codex/vs-04-vertical-slice", ["docs/validation/checkpoint.md"], True),
        ("codex/phase-18-check", [], True),
        ("main", ["app/timezone/boundaries/tbb.py"], True),
        ("main", ["app/geo/contracts.py"], True),
        ("main", ["uv.lock"], True),
        ("main", ["docs/validation/phase-18-timezone-boundaries.md"], True),
        ("main", ["README.md"], False),
    ],
)
def test_scope_is_or_not_and(branch: str, paths: list[str], expected: bool) -> None:
    scope = runpy.run_path(str(ROOT / "scripts/timezone-ci-scope.py"))
    assert scope["required"](branch, paths) is expected


def fixture_acquisition(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Any, Path]:
    namespace = runpy.run_path(str(ROOT / "scripts/prepare-timezone-artifact.py"))
    directory = tmp_path / "data"
    directory.mkdir()
    files = {
        "archive": ("timezones.geojson.zip", b"archive"),
        "catalog": ("timezone-names.json", b"[]"),
    }
    manifest = {}
    for key, (name, value) in files.items():
        (directory / name).write_bytes(value)
        manifest[key] = {
            "name": name,
            "size": len(value),
            "sha256": hashlib.sha256(value).hexdigest(),
        }
    path = tmp_path / "manifest.json"
    path.write_text(json.dumps(manifest))
    main = namespace["main"]
    monkeypatch.setitem(main.__globals__, "MANIFEST", path)
    return main, directory


def test_cache_hit_is_hashed_and_corruption_never_downloads(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    main, directory = fixture_acquisition(tmp_path, monkeypatch)

    def no_network(*args: Any, **kwargs: Any) -> None:
        pytest.fail("cache verification must not perform a network fallback")

    monkeypatch.setattr("subprocess.run", no_network)
    main(directory)
    (directory / "timezones.geojson.zip").write_bytes(b"wrong!!")
    with pytest.raises(ValueError):
        main(directory)


def test_cache_symlink_is_rejected(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    main, directory = fixture_acquisition(tmp_path, monkeypatch)
    path = directory / "timezone-names.json"
    moved = directory / "saved.json"
    path.rename(moved)
    path.symlink_to(moved)
    with pytest.raises(ValueError):
        main(directory)


def test_acquisition_caps_and_no_shell_or_latest() -> None:
    text = (ROOT / "scripts/prepare-timezone-artifact.py").read_text()
    assert "DOWNLOAD_LIMIT = 60 * 1024 * 1024" in text
    assert "TRANSFER_SECONDS = 120" in text
    assert "resource.RLIMIT_FSIZE" in text
    assert "timeout=TRANSFER_SECONDS" in text
    assert "shell=True" not in text and "releases/latest" not in text
    assert "data-timezones-tbb-2026c" in text and "os.link" in text


@pytest.mark.parametrize("collision", [None, "timezones.geojson.zip", "timezone-names.json"])
def test_download_verification_and_no_overwrite_promotion(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, collision: str | None
) -> None:
    main, source = fixture_acquisition(tmp_path, monkeypatch)
    destination = tmp_path / "fresh"
    limits = []
    staged: list[Path] = []
    monkeypatch.setattr("resource.setrlimit", lambda kind, value: limits.append(value))

    def fake_gh(command: list[str], **kwargs: Any) -> None:
        assert command[:-1] == [
            "gh",
            "release",
            "download",
            "data-timezones-tbb-2026c",
            "--repo",
            "github.com/Attory/astrological-compatibility-engine",
            "--pattern",
            "timezones.geojson.zip",
            "--pattern",
            "timezone-names.json",
            "--dir",
        ]
        assert kwargs == {"check": True, "timeout": 120, "capture_output": True}
        scratch = Path(command[-1])
        assert stat.S_IMODE(scratch.stat().st_mode) == 0o700
        staged.append(scratch)
        for name in ("timezones.geojson.zip", "timezone-names.json"):
            (scratch / name).write_bytes((source / name).read_bytes())

    original_link = main.__globals__["os"].link
    links = []

    def record_link(source_path: Path, target: Path) -> None:
        assert stat.S_IMODE(source_path.stat().st_mode) == 0o644
        if target.name == collision:
            target.write_bytes(b"concurrent owner value")
        original_link(source_path, target)
        assert source_path.stat().st_ino == target.stat().st_ino
        links.append(target.name)

    monkeypatch.setattr("subprocess.run", fake_gh)
    monkeypatch.setattr("os.link", record_link)
    if collision:
        with pytest.raises(FileExistsError):
            main(destination)
        assert (destination / collision).read_bytes() == b"concurrent owner value"
        assert links == ([] if collision == "timezones.geojson.zip" else ["timezones.geojson.zip"])
        # An interrupted pair never self-heals or falls back to another download.
        with pytest.raises(ValueError):
            main(destination)
    else:
        main(destination)
        assert links == ["timezones.geojson.zip", "timezone-names.json"]
        assert (destination / links[0]).read_bytes() == b"archive"
    assert limits == [(60 * 1024 * 1024, 60 * 1024 * 1024)]
    assert len(staged) == 1 and not staged[0].exists()


def test_corrupt_download_is_rejected_before_any_promotion(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    main, source = fixture_acquisition(tmp_path, monkeypatch)
    destination = tmp_path / "fresh"
    staged: list[Path] = []
    monkeypatch.setattr("resource.setrlimit", lambda *args: None)

    def fake_gh(command: list[str], **kwargs: Any) -> None:
        scratch = Path(command[-1])
        staged.append(scratch)
        (scratch / "timezones.geojson.zip").write_bytes(b"corrupt")
        (scratch / "timezone-names.json").write_bytes((source / "timezone-names.json").read_bytes())

    monkeypatch.setattr("subprocess.run", fake_gh)
    with pytest.raises(ValueError):
        main(destination)
    assert not list(destination.iterdir())
    assert len(staged) == 1 and not staged[0].exists()


def test_dangling_cache_symlink_fails_without_download(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    main, _ = fixture_acquisition(tmp_path, monkeypatch)
    directory = tmp_path / "dangling"
    directory.mkdir()
    (directory / "timezones.geojson.zip").symlink_to(directory / "absent")
    monkeypatch.setattr("subprocess.run", lambda *args, **kwargs: pytest.fail("no fallback"))
    with pytest.raises(ValueError):
        main(directory)
