"""Rebuild Essai 01. Run beside lessons.ttl and reuse.rq with RDFLib 7.6.0."""
import argparse
import json
from collections import defaultdict
from pathlib import Path

from rdflib import Graph, Namespace, Literal

HERE = Path(__file__).resolve().parent
EX = Namespace("https://experimentsin.ai/project-knowledge-reuse/essai-01/lessons.ttl#")
HEADINGS = {
    "agenda": "Put on the agenda",
    "verify": "Find corroboration",
    "clarify": "Clarify the asset",
    "superseded": "Use the later record",
    "context": "Different setting",
    "asset": "Different asset",
}
# The expected decisions were set when writing these seven fictional cases.
# They are fixture checks, not independently observed outcomes.
EXPECTED = {
    "AQ-17": "agenda", "FV-09": "agenda", "HC-06": "verify",
    "AQ-08": "superseded", "FV-12": "clarify", "EJ-04": "context", "WB-03": "asset",
}


def assess(row, meanings):
    if not meanings:
        return "clarify", "The vocabulary supplies no meaning for the recorded term."
    if len(meanings) > 1:
        return "clarify", "The recorded term has more than one possible meaning. Obtain an asset ID before transferring the lesson."
    if row.wanted not in meanings:
        return "asset", f"The record identifies a {next(iter(meanings.values()))}. Merebridge needs a {row.wantedLabel}."
    if row.replacement:
        return "superseded", f"The controlled index points to {row.replacement} as the replacement for this entry."
    if row.settingID != row.wantedSettingID:
        return "context", f"The source concerns a {row.setting}. Merebridge is a {row.wantedSetting}."
    if row.standing != EX.Accepted:
        return "verify", "The report matches the asset and setting. An acceptance minute or corroborating source is still needed."
    return "agenda", "The recorded term identifies the display, the setting matches, and the current record has accepted evidence."


def build(graph):
    groups = defaultdict(list)
    for row in graph.query((HERE / "reuse.rq").read_text()):
        groups[str(row.id)].append(row)
    records = []
    for key, rows in groups.items():
        first = rows[0]
        meanings = {r.concept: str(r.meaning) for r in rows if r.concept is not None}
        decision, reason = assess(first, meanings)
        records.append({
            "id": key, "lesson": str(first.title), "term": str(first.term),
            "meanings": sorted(meanings.values()), "setting": str(first.setting),
            "source": str(first.source), "date": str(first.date), "extract": str(first.extract),
            "standing": "accepted" if first.standing == EX.Accepted else "unconfirmed",
            "replacement": str(first.replacement) if first.replacement else None,
            "literal": str(first.term).casefold() == str(first.wantedLabel).casefold(),
            "mapped": first.wanted in meanings, "decision": decision,
            "heading": HEADINGS[decision], "reason": reason,
        })
    methods = {
        "literal": [r["id"] for r in records if r["literal"]],
        "mapped": [r["id"] for r in records if r["mapped"]],
        "agenda": [r["id"] for r in records if r["decision"] == "agenda"],
    }
    return {"cutoff": str(graph.value(EX.brief, EX.cutoff)), "triples": len(graph),
            "methods": methods, "records": records}


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--check", action="store_true", help="verify the saved result")
    args = parser.parse_args()
    graph = Graph().parse(HERE / "lessons.ttl", format="turtle")
    result = build(graph)
    payload = json.dumps(result, ensure_ascii=False, indent=2) + "\n"
    target = HERE / "results.json"
    if args.check:
        if {r["id"]: r["decision"] for r in result["records"]} != EXPECTED:
            raise SystemExit("The seven decisions differ from the authored fixture expectations.")
        if target.read_text() != payload:
            raise SystemExit("Saved results differ from the reproduced results.")
        # Change two facts in memory. One source gains corroboration, and one
        # asset term loses its mapping. Check that the agenda changes accordingly.
        graph.set((EX.HCnote, EX.standing, EX.Accepted))
        graph.set((EX.FV09, EX.recordedTerm, Literal("unmapped term")))
        changed = {r["id"]: r["decision"] for r in build(graph)["records"]}
        if changed != {**EXPECTED, "HC-06": "agenda", "FV-09": "clarify"}:
            raise SystemExit("Changed evidence and an unmapped term failed to change the decisions.")
    else:
        target.write_text(payload)
    for method, identifiers in result["methods"].items():
        print(f"{method}: {', '.join(identifiers)}")
