"""Enumerate which differences in a project instruction survive three minute forms."""
import json
from itertools import combinations
from pathlib import Path

FILES = {
    "located": {"local": True, "adverse": False},
    "similar": {"local": False, "adverse": False},
    "adverse": {"local": True, "adverse": True},
}
MINUTES = {
    "replacement": "Keep the brief to replacement",
    "assessment": "Commission a repair assessment",
    "credit": "Allow extra strength",
}
# These are explicit judgements made for the rehearsal. The test compares what
# a form transmits once those judgements have been made.
CONSEQUENCES = {
    "located": ["Grounded enquiry dropped; record why.", "Repair assessment commissioned.", "Performance allowance lacks support."],
    "similar": ["A local records search remains available.", "Checking local attribution first costs less.", "Both installation and performance remain open."],
    "adverse": ["Independent finding supports closure.", "Reopening needs a new premise.", "Performance allowance lacks support."],
}


def adjudicate(record, lookup_affordable):
    if record["adverse"]:
        instruction = "Close the repair route in this brief"
    elif record["local"]:
        instruction = "Commission the repair assessment"
    elif lookup_affordable:
        instruction = "Search the local works file"
    else:
        instruction = "Close the repair route in this brief"
    return instruction, 0


def encode(form, record, instruction, credit):
    if form == "stamp":
        return ("Film local" if record["local"] else "Film from elsewhere",)
    if form == "boxes":
        return ("Assess now" if instruction == "Commission the repair assessment"
                else "No assessment", credit)
    return (instruction, credit)


def compare(lookup_affordable):
    intended = {name: adjudicate(record, lookup_affordable) for name, record in FILES.items()}
    output = {}
    for form in ["stamp", "boxes", "instruction"]:
        slips = {name: encode(form, FILES[name], *target) for name, target in intended.items()}
        pairs = list(combinations(FILES, 2))
        different = [(a, b) for a, b in pairs if intended[a] != intended[b]]
        lost = [(a, b) for a, b in different if slips[a] == slips[b]]
        output[form] = {"slips": slips, "distinct_instruction_pairs": len(different),
                        "lost_pairs": lost, "recoverable_pairs": len(different) - len(lost)}
    return {"intended": intended, "forms": output}


def run():
    usual = compare(True)
    costly = compare(False)
    assert usual["forms"]["stamp"]["lost_pairs"] == [("located", "adverse")]
    assert usual["forms"]["boxes"]["lost_pairs"] == [("similar", "adverse")]
    assert not usual["forms"]["instruction"]["lost_pairs"]
    assert [costly["forms"][f]["recoverable_pairs"] for f in ("stamp", "boxes", "instruction")] == [1, 2, 2]
    minutes = {f: dict(zip(MINUTES, CONSEQUENCES[f])) for f in FILES}
    assert sum(len(items) for items in minutes.values()) == 9
    return {"rehearsal": minutes, "ordinary_lookup": usual, "costly_lookup": costly}


if __name__ == "__main__":
    result = json.dumps(run(), indent=2, ensure_ascii=False) + "\n"
    print(result, end="")
    # A checked-in copy accompanies the model. The program can also run alone.
    saved = Path(__file__).with_name("results.json")
    if saved.exists():
        assert json.loads(saved.read_text(encoding="utf-8")) == json.loads(result)
