#!/usr/bin/env python3
"""Reconcile written references with finite catalogs and section-level coverage maps."""
import hashlib
import json
from pathlib import Path
import subprocess

from inventory import ROOT, MANUALS, sha
from validate import capabilities


def read(name):
    return json.loads((MANUALS/"authoring"/name).read_text())


def main():
    catalog = read("catalogs.json")
    rows = capabilities()
    for row in rows:
        assert (ROOT/row["reference"]).is_file(), (row["id"], "missing canonical chapter")
    settings = read("collection.json")
    books = settings["books"]
    assert len(books) == 6
    printed = set()
    for book in books:
        assert len(book["pages"]) == len(set(book["pages"])), (book["title"], "duplicate chapter")
        for path in book["pages"]:
            assert (MANUALS/path).is_file(), (book["title"], "missing chapter", path)
            printed.add("docs/manuals/"+path)
    anchors = {}
    def section(reference):
        path, _, fragment = reference.partition("#")
        assert (ROOT/path).is_file(), ("missing section source", reference)
        assert path in printed, ("reference omitted from print collection", path)
        if fragment:
            if path not in anchors:
                ast = json.loads(subprocess.check_output(["pandoc", "-f", "gfm", "-t", "json", str(ROOT/path)], text=True))
                found = set()
                def walk(value):
                    if isinstance(value, dict):
                        if value.get("t") == "Header":
                            found.add(value["c"][1][0])
                        for item in value.values():
                            walk(item)
                    elif isinstance(value, list):
                        for item in value:
                            walk(item)
                walk(ast)
                anchors[path] = found
            assert fragment in anchors[path], ("missing section anchor", reference)
    for row in rows:
        section(row["reference"])
    language = {r["id"] for r in rows if r["id"].startswith("LANG-")}
    vibe = read("vibe-coverage.json")
    assert {r["feature_id"] for r in vibe["feature_mappings"]} == language
    for row in vibe["feature_mappings"]:
        assert row["sections"]
        section(row["shared_reference"])
        for target in row["sections"]:
            section(target)
    apl = read("apl-coverage.json")
    expected_apl = {r["id"]: r for r in rows if r["id"].startswith("LANG-APL-")}
    assert {r["capability_id"] for r in apl["capabilities"]} == set(expected_apl)
    section(apl["chapter"])
    for row in apl["capabilities"]:
        expected = expected_apl[row["capability_id"]]
        assert row["implementation_status"] == expected["status"], (row["capability_id"], "APL status drift")
        assert expected["reference"] == apl["chapter"], (row["capability_id"], "APL canonical destination drift")
        for target in row["sections"]:
            section(target)
    for row in read("vada-varc-coverage.json")["documents"]:
        section(row["path"])
        assert set(row["capability_ids"]) <= language
    tool_rows = {r["id"] for r in rows if r["id"].startswith("tool.")}
    tools = read("toolchain-coverage.json")["capabilities"]
    assert {r["capability_id"] for r in tools} == tool_rows
    for row in tools:
        assert row["sections"]
        for target in row["sections"]:
            section(target)
    verification = read("verification-coverage.json")["feature_mappings"]
    expected_verification = {r["id"] for r in rows if r["id"].startswith("verification.")}
    assert {r["feature_id"] for r in verification} == expected_verification
    for row in verification:
        assert row["sections"]
        for target in row["sections"]:
            section(target)
    library = read("library-coverage.json")
    units = {u["unit"]: u for u in library["units"]}
    assert set(units) == {u["unit"] for u in catalog["libraries"]}
    count = 0
    for unit in catalog["libraries"]:
        covered = units[unit["unit"]]
        for key in ("curated", "family", "reference"):
            section(covered[key])
        blocks = covered["declaration_blocks"]
        assert len(blocks) == len(unit["declarations"]), (unit["unit"], "declaration block gap")
        for ordinal, (actual, expected) in enumerate(zip(blocks, unit["declarations"]), 1):
            # Curated labels can improve an unheaded generic/field block's extracted name.
            # The complete signature hash and ordinal identify the actual declaration block.
            assert actual["ordinal"] == ordinal, (unit["unit"], "declaration ordering drift")
            assert actual["signature_sha256"] == hashlib.sha256(expected["signature"].encode()).hexdigest(), (unit["unit"], "signature drift")
            section(actual["curated_section"])
            section(actual["declaration_reference"])
            count += 1
    diagnostics = read("diagnostics-coverage.json")["codes"]
    assert {r["code"] for r in diagnostics} == {r["code"] for r in catalog["diagnostics"]}
    for row in diagnostics:
        section(row["reference"])
        section(row["family_reference"])
        assert sha(ROOT/row["reference"]) == row["content_sha256"], (row["code"], "refresh diagnostics metadata after review")
        # (B8008 and B8012 depend on files a golden case would have to keep, certificates and the
        # proof cache: test/Verada/Proof's CertificateSpec and RememberSpec produce them on copies;
        # B8011 on the solver's version: FragileSpec makes the first search give up; B0712 and
        # B1020 only in the APL Workbench's analysis: WorkbenchSpec)
        if row["status"] == "active" and row["code"] not in ("B0712", "B1020", "B8008", "B8011", "B8012"):
            assert row["regression_case"] and (ROOT/row["regression_case"]).exists()
    for name, path in (("recognized_attributes", "language/attributes.md"), ("recognized_aspects", "language/aspects-pragmas.md")):
        text = (MANUALS/path).read_text().casefold()
        for token in catalog[name]:
            assert token.casefold() in text, ("recognized name not explained", name, token)
    result = {"schema_version": 1, "baseline_revision": catalog["baseline_revision"], "completed": True,
              "canonical_capability_destinations": len(rows), "language_inventory_ids_with_shared_and_vibe_sections": len(language),
              "apl_capabilities_with_dedicated_sections": len(apl["capabilities"]),
              "tool_capabilities_with_sections": len(tools), "library_units": len(units),
              "verification_capabilities_with_sections": len(verification),
              "library_declaration_blocks_with_guidance": count, "diagnostic_code_pages": len(diagnostics),
              "recognized_attributes": len(catalog["recognized_attributes"]), "recognized_aspects": len(catalog["recognized_aspects"]),
              "print_volumes": len(books), "distinct_print_chapters_including_glossary": len(printed),
              "interpretation": "Coverage reconciliation checks authored sections and source-derived surfaces. It does not promote source review or named tests into execution evidence or certify release readiness."}
    (MANUALS/"authoring/edition-coverage.json").write_text(json.dumps(result, indent=2)+"\n")
    print(json.dumps(result, indent=2))


if __name__ == "__main__":
    main()
