#!/usr/bin/env python3
"""Reconstruct one source-calibrated Dd.6.29 page route; stdlib only.

The query supplies a complaint, never a destination. The observed index supplies
its side numeral. Two directly read side headers calibrate the catalogue range.
Rubric matching is a separate landing check. This is not a medical-use tool.
"""
import argparse
import copy
import hashlib
import json
import re
import sys
from pathlib import Path

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


class RouteError(ValueError):
    pass


def cue(text):
    return " ".join(re.findall(r"[a-z]+", text.lower()))


def roman_side(text):
    text = text.strip(" .").lower().replace("j", "i")
    if not text or re.fullmatch("[ivxlcdm]+", text) is None:
        raise RouteError("Unreadable or invalid side numeral")
    values = dict(i=1, v=5, x=10, l=50, c=100, d=500, m=1000)
    return sum(-values[c] if n + 1 < len(text) and values[c] < values[text[n + 1]]
               else values[c] for n, c in enumerate(text))


def load():
    pins = json.loads((ROOT / "SOURCE_MANIFEST.json").read_text())
    for item in pins["sources"]:
        if hashlib.sha256(Path(item["path"]).read_bytes()).hexdigest() != item["sha256"]:
            raise RouteError("Source pin mismatch: " + item["path"])
    source = json.loads((ROOT / "source_operator.json").read_text())
    manifest = json.loads(Path(source["held_manifest"]).read_text())
    return source, manifest


def route(query, source, manifest):
    entries = [e for e in source["index_entries"]
               if cue(query) in {cue(a) for a in e["query_aliases"]}]
    if len(entries) != 1:
        raise RouteError("Query has no unique transcribed source index entry")
    entry = entries[0]
    if len(entry["address_readings"]) != 1:
        raise RouteError("Index numeral is uncertain; route withheld")
    side = roman_side(entry["address_readings"][0])
    ranges = [r for r in manifest["structures"] if r["@id"] == source["recipe_range_id"]]
    if len(ranges) != 1:
        raise RouteError("Catalogue recipe range is absent or ambiguous")
    inventory = ranges[0]["canvases"]
    canvases = {c["@id"]: c for c in manifest["sequences"][0]["canvases"]}
    if len(set(inventory)) != len(inventory) or any(c not in canvases for c in inventory):
        raise RouteError("Catalogue range has duplicate or missing canvases")
    offsets, anchors = [], []
    for a in source["directly_read_page_headers"]:
        matches = [i for i, c in enumerate(inventory) if canvases[c]["label"] == a["folio"]]
        if len(matches) != 1:
            raise RouteError("Calibration anchor absent or ambiguous")
        ordinal = roman_side(a["numeral"])
        offset = matches[0] - ordinal + 1
        offsets.append(offset)
        anchors.append({"folio": a["folio"], "direct_header": a["numeral"],
                        "side_ordinal": ordinal, "inventory_index_zero_based": matches[0],
                        "implied_side_one_index": offset, "evidence": a["evidence"]})
    if len(anchors) < 2 or len(set(offsets)) != 1:
        raise RouteError("Source header anchors disagree or are insufficient")
    index = offsets[0] + side - 1
    if side < 1 or not 0 <= index < len(inventory):
        raise RouteError("Index side numeral is outside the catalogued recipe range")
    landing_id = inventory[index]
    observed = source["landing_rubrics"].get(landing_id, [])
    matches = [r for r in observed if cue(r["normalized_heading"]) == cue(entry["landing_cue"])]
    if len(matches) != 1:
        raise RouteError("Landing rubric is absent, wrong or ambiguous; route withheld")
    return {
        "route_state": "SOURCE_CALIBRATED_ROUTE",
        "input": {"type": "complaint_cue", "query": query},
        "steps": [
            {"operation": "select_index_cue", "folio": "20r", "entry_id": entry["id"],
             "evidence": entry["evidence"]},
            {"operation": "follow_drawn_brace", "address": entry["address_readings"][0],
             "normalized_side_ordinal": side, "evidence": entry["evidence"]},
            {"operation": "calibrate_side_numbering", "anchors": anchors,
             "catalogue_range": source["recipe_range_id"],
             "range_label": ranges[0]["label"], "side_one_index": offsets[0]},
            {"operation": "resolve_catalogued_canvas", "canvas_id": landing_id,
             "catalogue_folio_label": canvases[landing_id]["label"],
             "inventory_index_zero_based": index},
            {"operation": "verify_landing_rubric", "heading": matches[0]["normalized_heading"],
             "evidence": matches[0]["evidence"]}
        ],
        "output": {"type": "located_recipe_entry", "folio": canvases[landing_id]["label"],
                   "canvas_id": landing_id, "entry": matches[0]["id"]},
        "limitations": source["limitations"],
        "destination_supplied_as_input": False,
        "vms_route_executed": False
    }


def self_test(source, manifest):
    checks = []
    def passes(name, fn):
        fn()
        checks.append({"name": name, "verdict": "PASS"})
    def rejects(name, s, query="For the head ache"):
        try:
            route(query, s, manifest)
        except RouteError as exc:
            checks.append({"name": name, "verdict": "PASS", "rejection": str(exc)})
        else:
            raise AssertionError("Invalid fixture accepted: " + name)
    def expected():
        r = route("For the head ache", source, manifest)
        assert r["output"]["folio"] == "34r"
        assert r["steps"][2]["anchors"][0]["side_ordinal"] == 3
        assert r["steps"][2]["anchors"][1]["side_ordinal"] == 5
        assert not r["destination_supplied_as_input"]
    passes("head complaint reaches catalogue 34r with two source anchors", expected)
    rejects("unknown complaint rejected", source, "untranscribed complaint")
    rejects("uncertain eye iij/iiij rejected", source, "For him that may not well see")
    changed = copy.deepcopy(source)
    changed["directly_read_page_headers"][1]["numeral"] = "vij"
    rejects("changed calibration anchor rejected", changed)
    changed = copy.deepcopy(source)
    changed["index_entries"][0]["address_readings"] = ["clx"]
    rejects("out of range address rejected", changed)
    changed = copy.deepcopy(source)
    changed["landing_rubrics"]["http://cudl.lib.cam.ac.uk/iiif/MS-DD-00006-00029/canvas/69"][0]["normalized_heading"] = "For the feet"
    rejects("wrong landing heading rejected", changed)
    changed = copy.deepcopy(source)
    changed["landing_rubrics"]["http://cudl.lib.cam.ac.uk/iiif/MS-DD-00006-00029/canvas/69"] = []
    rejects("missing landing heading rejected", changed)
    changed = copy.deepcopy(source)
    changed["index_entries"].append(copy.deepcopy(changed["index_entries"][0]))
    rejects("ambiguous source cue rejected", changed)
    return {"verdict": "PASS", "checks": checks, "check_count": len(checks),
            "scope": "New route implementation controls only; no historical statistical probe repeated."}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--query", default="For the head ache")
    parser.add_argument("--self-test", action="store_true")
    args = parser.parse_args()
    try:
        source, manifest = load()
        output = self_test(source, manifest) if args.self_test else route(args.query, source, manifest)
        print(json.dumps(output, indent=2))
    except (RouteError, AssertionError, KeyError, OSError) as exc:
        print(json.dumps({"verdict": "REJECTED", "reason": str(exc)}), file=sys.stderr)
        return 2
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
