"""Contracts for active-manuscript artifact provenance."""

from __future__ import annotations

import json
import os
import subprocess
import sys
from pathlib import Path

import pytest


REPO_ROOT = Path(__file__).resolve().parent.parent
AUDIT = (
    REPO_ROOT
    / "Paper-JSS"
    / "replication"
    / "scripts"
    / "manuscript_artifact_audit.py"
)
RESULTS = REPO_ROOT / "Paper-JSS" / "replication" / "results"

# ``Paper-JSS/`` is a git-ignored, local-only submission working directory
# (see ``.gitignore``); it is absent from fresh clones and CI checkouts. The
# JSS source-snapshot audits only make sense against that local tree, so skip
# the whole module when it is absent rather than erroring on missing scripts.
pytestmark = pytest.mark.skipif(
    not (REPO_ROOT / "Paper-JSS").exists(),
    reason="Paper-JSS/ submission working dir is git-ignored / local-only",
)


def test_active_manuscript_artifacts_have_generators_and_hash_guards() -> None:
    env = os.environ.copy()
    env.setdefault("SOURCE_DATE_EPOCH", "1780185600")
    res = subprocess.run(
        [sys.executable, str(AUDIT)],
        cwd=REPO_ROOT,
        env=env,
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        check=False,
    )
    assert res.returncode == 0, res.stderr

    payload = json.loads((RESULTS / "manuscript_artifact_audit.json").read_text())
    artifacts = {
        row["path"]: row
        for row in [*payload["tables"], *payload["figure_artifacts"]]
    }

    assert payload["status"] == "PASS"
    assert len(payload["active_sections"]) == 9
    assert payload["artifact_count"] == 4
    assert payload["hash_mismatches"] == 0
    assert {
        "Paper-JSS/manuscript/tables/track_a_cross_language_snapshot.tex",
        "Paper-JSS/manuscript/tables/track_c_perf.tex",
        "Paper-JSS/replication/tables/ex07_agent_trace.tex",
        "Paper-JSS/manuscript/figures/track_c_loglog.pdf",
    } == set(artifacts)
    assert artifacts[
        "Paper-JSS/manuscript/tables/track_c_perf.tex"
    ]["hash_equal"] is True
    assert artifacts[
        "Paper-JSS/manuscript/figures/track_c_loglog.pdf"
    ]["hash_equal"] is True

    snapshot = (
        REPO_ROOT
        / "Paper-JSS"
        / "manuscript"
        / "tables"
        / "track_a_cross_language_snapshot.tex"
    ).read_text()
    assert "AUTO-GENERATED by tests/r_parity/compare.py" in snapshot
    assert "T4 R/Stata reference disagreement" in snapshot
    assert "T3 combined-MC-error pass" in snapshot
