"""Write the claim ledger and package-wide SHA-256 inventory."""

from __future__ import annotations

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

HERE = Path(__file__).resolve().parent


def sha256(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def file_record(
    identifier: str, kind: str, path: str, command: str
) -> dict[str, Any]:
    target = HERE / path
    if not target.is_file():
        raise FileNotFoundError(f"manifest output is missing: {path}")
    return {
        "id": identifier,
        "kind": kind,
        "path": path,
        "sha256": sha256(target),
        "command": command,
    }


def main() -> None:
    question_path = HERE / "inputs" / "question.md"
    report_path = HERE / "paper.tex"
    if not question_path.is_file() or not report_path.is_file():
        raise FileNotFoundError("question or report source is missing")

    analysis_command = "python run_analysis.py"
    latex_command = "latexmk -pdf -interaction=nonstopmode -halt-on-error paper.tex"
    manifest = {
        "schemaVersion": "1.0",
        "id": "strust-v1-evidence-bounded-case-study",
        "title": "STRUST v1: An Evidence-Bounded Project Case Study",
        "deliverableMode": "report",
        "question": {
            "path": "inputs/question.md",
            "sha256": sha256(question_path),
        },
        "sources": [
            {
                "id": "historical-pdf",
                "title": "Strust-v1: Performance Metric for COBOL-to-Java Generative AI",
                "url": "git:96dba8008ce831118da87b968dc2b48df79eb373/public/pdfs/Strust.pdf",
                "accessed": "2026-08-03",
            },
            {
                "id": "historical-tree",
                "title": "Repository tree at the last pre-reconstruction Strust revision",
                "url": "git:96dba8008ce831118da87b968dc2b48df79eb373",
                "accessed": "2026-08-03",
            },
            {
                "id": "acm-sigsim-artifacts",
                "title": "PADS 2026 Reproducibility and Artifact Evaluation",
                "url": "https://sigsim.acm.org/conf/pads/2026/blog/artifact-evaluation/",
                "accessed": "2026-08-03",
            },
        ],
        "outputs": [
            file_record(
                "historical-source",
                "other",
                "inputs/historical_strust_v1.pdf",
                "recovered from the recorded Git commit; not generated by this analysis",
            ),
            file_record(
                "historical-ledger",
                "data",
                "inputs/historical_ledger.csv",
                "literal manual transcription of historical Table I, p. 7",
            ),
            file_record(
                "study-config",
                "other",
                "study_config.json",
                "not generated",
            ),
            file_record(
                "case-audit",
                "data",
                "results/case_audit.csv",
                analysis_command,
            ),
            file_record(
                "evidence-inventory",
                "data",
                "results/evidence_inventory.csv",
                analysis_command,
            ),
            file_record(
                "summary-json",
                "data",
                "results/summary.json",
                analysis_command,
            ),
            file_record(
                "audit-figure-pdf",
                "figure",
                "figures/ledger_evidence_audit.pdf",
                analysis_command,
            ),
            file_record(
                "audit-figure-png",
                "figure",
                "figures/ledger_evidence_audit.png",
                analysis_command,
            ),
            file_record("claim-evidence-edges", "data", "results/claim_evidence_edges.csv", analysis_command),
            file_record("evidence-survival", "data", "results/evidence_survival.csv", analysis_command),
            file_record("artifact-recovery-counterfactual", "data", "results/artifact_recovery_counterfactual.csv", analysis_command),
            file_record("evidence-survival-summary", "data", "results/evidence_survival_summary.json", analysis_command),
            file_record("evidence-survival-figure-pdf", "figure", "figures/claim_evidence_survival.pdf", analysis_command),
            file_record("evidence-survival-figure-png", "figure", "figures/claim_evidence_survival.png", analysis_command),
            file_record("evidence-graph-code", "code", "evidence_graph.py", "not generated"),
            file_record("evidence-graph-tests", "code", "tests/test_evidence_graph.py", "not generated"),
            file_record("paper-pdf", "other", "paper.pdf", latex_command),
            file_record("analysis-code", "code", "run_analysis.py", "not generated"),
            file_record("analysis-tests", "code", "tests/test_analysis.py", "not generated"),
            file_record("manifest-builder", "code", "build_manifest.py", "not generated"),
            file_record("paper-source", "code", "paper.tex", "not generated"),
            file_record("readme", "other", "README.md", "not generated"),
        ],
        "claims": [
            {
                "id": "historical-accuracy-claim",
                "kind": "empirical",
                "statement": "The historical PDF states 100% accuracy or success despite its recorded failures.",
                "status": "supported",
                "sourceRefs": [
                    {
                        "sourceId": "historical-pdf",
                        "locator": "Results p. 7; Validation of Feasibility p. 8; Conclusion p. 10",
                    }
                ],
                "outputIds": [],
                "dependsOn": [],
                "caveats": [],
            },
            {
                "id": "table-ledger",
                "kind": "empirical",
                "statement": "Table I contains ten cases with eight Pass statuses and two Fail statuses, T9 and T10.",
                "status": "supported",
                "sourceRefs": [
                    {
                        "sourceId": "historical-pdf",
                        "locator": "Table I, p. 7",
                    }
                ],
                "outputIds": [],
                "dependsOn": [],
                "caveats": [],
            },
            {
                "id": "computed-pass-rate",
                "kind": "computational",
                "statement": "The transcribed table yields a recorded pass rate of 8/10 = 0.80.",
                "status": "reproduced",
                "sourceRefs": [],
                "outputIds": ["case-audit", "summary-json"],
                "dependsOn": ["table-ledger"],
                "caveats": [
                    "This is a document-level pass rate, not independently validated accuracy."
                ],
            },
            {
                "id": "internal-contradiction",
                "kind": "synthetic",
                "statement": "The historical 100% prose claim exceeds the source-table rate by 20 percentage points.",
                "status": "supported",
                "sourceRefs": [],
                "outputIds": [],
                "dependsOn": ["historical-accuracy-claim", "computed-pass-rate"],
                "caveats": [
                    "The comparison audits internal consistency; it does not reconstruct the original executions."
                ],
            },
            {
                "id": "evidence-boundary",
                "kind": "empirical",
                "statement": "The recovered v1 source artifact contains no executable subjects, fixtures, raw traces, comparator configuration, or environment manifest.",
                "status": "supported",
                "sourceRefs": [
                    {
                        "sourceId": "historical-pdf",
                        "locator": "Complete ten-page artifact; only prose, pseudocode, example output, and Table I are embedded",
                    },
                    {
                        "sourceId": "historical-tree",
                        "locator": "Git tree at commit 96dba800: public/pdfs/Strust.pdf is the preserved Strust artifact",
                    },
                ],
                "outputIds": [],
                "dependsOn": [],
                "caveats": [],
            },
            {"id": "artifact-evaluation-context", "kind": "empirical", "statement": "The official ACM SIGSIM PADS artifact process distinguishes availability, functionality, reusability, and reproduced results.", "status": "supported", "sourceRefs": [{"sourceId": "acm-sigsim-artifacts", "locator": "Artifact Evaluation section"}], "outputIds": [], "dependsOn": [], "caveats": ["The locally declared STRUST graph is not an ACM badge decision."]},
            {"id": "claim-evidence-survival", "kind": "computational", "statement": "Under the locally declared graph, 2 of 19 required claim-artifact links survive and one of five modeled outcome claim classes, recorded table arithmetic, is fully auditable; four modeled claim classes remain blocked, and no single missing artifact completes one.", "status": "reproduced", "sourceRefs": [], "outputIds": ["claim-evidence-edges", "evidence-survival", "artifact-recovery-counterfactual", "evidence-survival-summary", "evidence-survival-figure-pdf", "evidence-graph-code"], "dependsOn": ["computed-pass-rate", "evidence-boundary", "artifact-evaluation-context"], "caveats": ["The required bundles are locally declared conjunctive requirements; alternative sufficient bundles were not assessed.", "Complete coverage makes a claim auditable, not correct or favorable.", "Private or lost artifacts may once have existed."]},
            {
                "id": "classification",
                "kind": "synthetic",
                "statement": "STRUST v1 belongs in the Project portfolio as a transparent case study, not in the Research portfolio as a validated experiment.",
                "status": "supported",
                "sourceRefs": [],
                "outputIds": [],
                "dependsOn": ["internal-contradiction", "evidence-boundary", "claim-evidence-survival"],
                "caveats": [
                    "This is a publication-classification judgment based on the preserved evidence, not a claim that the underlying project had no value."
                ],
            },
        ],
        "report": {
            "path": "paper.tex",
            "sha256": sha256(report_path),
            "status": "draft",
        },
        "approvals": {
            "scope": {
                "status": "approved",
                "approvedAt": "2026-08-03",
                "note": "User explicitly requested a complete evidence-bounded revision of this study.",
            },
            "final": {
                "status": "pending",
                "approvedAt": None,
                "note": "Awaiting user review of the rebuilt case study.",
            },
        },
    }
    (HERE / "research.json").write_text(
        json.dumps(manifest, indent=2, sort_keys=False) + "\n", encoding="utf-8"
    )
    print("wrote research.json with package-wide SHA-256 inventory")


if __name__ == "__main__":
    main()
