#!/usr/bin/env python3
"""Fictional Calva earthworks package-allocation experiment; Python stdlib only.

Exact enumeration of 2,858,856 balanced partitions, modulo package relabelling.
This is an illustrative coordination model, not a civil-engineering design.
"""
import argparse
import hashlib
import itertools
import json
import math
import os
from fractions import Fraction
from pathlib import Path
from tempfile import NamedTemporaryFile
from time import perf_counter

ROOT = Path(__file__).resolve().parent
DENOMINATOR = 10000
TYPES = ("quantity", "level", "gradient")
ALL = (1 << 18) - 1


def make_inputs():
    stages = ["Strip and store", "Formation and drainage", "Trim and reinstate"]
    strip = [180, 240, 300, 360, 240, 180]
    place = [200, 220, 250, 330, 260, 240]
    # Source-minus-demand prefix: positive means movement to the right.
    lateral = list(itertools.accumulate(a-b for a, b in zip(strip, place)))[:-1]
    tiles = []
    for stage in range(3):
        for col in range(6):
            i = stage*6 + col
            tiles.append({"id": i, "code": f"{stage+1}{chr(65+col)}", "stage": stage,
                "stageName": stages[stage], "chainageCell": col,
                "chainageStartM": col*100, "chainageEndM": (col+1)*100,
                "context": "Bog beside the imagined youth hostel" if col in (2,3) else "Steep railway climb",
                "topsoilStrippedM3": strip[col] if stage == 0 else 0,
                "topsoilPlacedM3": place[col] if stage == 2 else 0})

    spatial = {
        "quantity": [[80,180,140,100,60],[60,160,120,130,80],[30,40,35,50,70]],
        "level": [[40,70,85,65,35],[90,190,210,140,90],[110,130,150,170,200]],
        "gradient": [[20,25,30,50,85],[60,90,120,180,220],[90,100,140,200,260]],
    }
    temporal = {
        "quantity": [[110,150,300,360,160,100],[50,70,160,180,90,60]],
        "level": [[60,80,100,110,70,60],[120,130,150,150,140,150]],
        "gradient": [[40,40,60,60,80,100],[100,120,140,150,240,300]],
    }
    edges = []
    for kind in ("space", "time"):
        rows, cols = (3,5) if kind == "space" else (2,6)
        weights = spatial if kind == "space" else temporal
        for row in range(rows):
            for col in range(cols):
                u = row*6+col
                v = u+1 if kind == "space" else u+6
                near_bog = col in (1,2,3) if kind == "space" else col in (2,3)
                nominal = lateral[col] if kind == "space" and row == 2 else (strip[col] if kind == "time" else 0)
                risk = {}
                for t in TYPES:
                    uplift = weights[t][row][col]
                    within = max(10, uplift//3)
                    # These are declared scenario inputs, not inferred/calibrated probabilities.
                    wet_extra = (uplift*2 if kind == "space" else uplift//2) if near_bog else 0
                    wet_within = within + (within//2 if near_bog else 0)
                    review_uplift = uplift//4 if near_bog else uplift
                    risk[t] = {
                        "reference": {"withinBp": within, "crossBp": within+uplift},
                        "wet_bog": {"withinBp": wet_within, "crossBp": wet_within+uplift+wet_extra},
                        "bog_joint_review": {"withinBp": within, "crossBp": within+review_uplift},
                    }
                quantity_gap = (5 if nominal == 0 else 10) + (15 if near_bog else 0) + row*5
                level_gap = (6+row*4+col*2) if kind == "space" else (4+row*3+col)
                gradient_gap_milli_permille = 20+10*row+10*col if kind == "space" else 20+10*col
                edges.append({"id": len(edges), "u":u, "v":v, "kind":kind,
                    "nearBog":near_bog, "label":f"{tiles[u]['code']} / {tiles[v]['code']}",
                    "comparison": "Same geographic interface in one stage" if kind == "space" else "Previous-stage handover surface versus next-stage inherited starting surface",
                    "nominalSignedTransferM3": nominal,
                    "quantityPlanGapM3": quantity_gap,
                    "levelGapMm": level_gap,
                    "gradientGapMilliPermille": gradient_gap_milli_permille,
                    "risk":risk})
    ledger = []
    for tile in tiles:
        i = tile["id"]
        incoming = outgoing = 0
        for e in edges:
            q = e["nominalSignedTransferM3"]
            source, target = (e["u"],e["v"]) if q >= 0 else (e["v"],e["u"])
            if target == i: incoming += abs(q)
            if source == i: outgoing += abs(q)
        ledger.append({"tile":i, "sourceStrippedM3":tile["topsoilStrippedM3"],
            "incomingM3":incoming, "outgoingM3":outgoing,
            "sinkPlacedM3":tile["topsoilPlacedM3"],
            "balanceM3":tile["topsoilStrippedM3"]+incoming-outgoing-tile["topsoilPlacedM3"]})
    return {"version":"calva-earthworks-1", "title":"The Calva earthworks handover",
        "fiction":"An invented railway alignment, schematic placement relative to the real hostel, geometry and probability model. Not surveyed Calva conditions or engineering advice.",
        "probabilityDenominator":DENOMINATOR,
        "probabilityMeaning":"Assumed marginal probability that a named discrepancy remains unresolved at the agreed handover checkpoint. These numbers are chosen illustrative inputs, not frequencies inferred from observations.",
        "objectiveMeaning":"Expected number of unresolved named seam discrepancies = sum of their marginal probabilities. A seam can contribute quantity, level and gradient events separately. No independence assumption, and not the probability of at least one failure.",
        "ownershipMeaning":"An allocation changes responsibility and assumed review efficacy. It does not repair geometry, change quantities, alter the fixed transfer ledger, or remove a known discrepancy.",
        "packageConstraint":"Three interchangeable packages, exactly six tiles each; connected packages are the principal admissible set. Unrestricted balanced partitions are also enumerated as a lower-bound comparison.",
        "stages":stages, "tiles":tiles, "edges":edges,
        "profiles":[{"id":"reference","label":"Reference assumptions"},{"id":"wet_bog","label":"Wet bog handoffs"},{"id":"bog_joint_review","label":"Joint review at the bog"}],
        "materialLedger":{"material":"Topsoil only; fixed nominal conserved transfer plan, distinct from provisional quantity disagreements", "strippedM3":sum(strip), "placedM3":sum(place), "exportedM3":0,"importedM3":0,"endingStoredM3":0,"tiles":ledger},
        "geometryCounterexample":{"description":"Two draft models at the same interface both give level 120.000 m and agree on a 50 m3 transfer. Their common-direction tangent grades are +25 and +35 per mille. The quantity ledger balances and the levels match, yet the tangent difference is 10 per mille. This example stipulates a shared tangent target at that interface; it is not a claim that every legitimate vertical curve must have one constant grade.","quantityTransferM3":50,"leftLevelMm":120000,"rightLevelMm":120000,"leftGradePermille":25,"rightGradePermille":35},
        "limitations":["Package labels are interchangeable; no specialist competence, cost, duration or resource differences are modelled.","Tile count is the declared workload proxy. Equal tile counts do not establish equal engineering effort.","Only adjacent cells in the time-by-chainage diagram share seams. Long-range drainage, geotechnical dependencies and temporary works are outside this model.","A temporal seam compares inherited starting conditions, not deliberately changed levels at different stages.","Transfer quantities refer to the same named transfer and material. Adjacent cells need not excavate or consume equal volumes.","The model requires within and cross probabilities to be recalibrated before operational use."]}


def connected(mask, adjacency):
    reached = frontier = mask & -mask
    while frontier:
        next_frontier = 0
        while frontier:
            bit = frontier & -frontier
            frontier -= bit
            next_frontier |= adjacency[bit.bit_length()-1]
        frontier = next_frontier & mask & ~reached
        reached |= frontier
    return reached == mask


def allocation(masks):
    return [next(k for k,m in enumerate(masks) if m & (1 << i)) for i in range(18)]


def objective_definitions(data):
    defs=[]
    for profile in ("reference","wet_bog","bog_joint_review"):
        for selected in ("all", *TYPES):
            types = TYPES if selected == "all" else (selected,)
            weights=[sum(e["risk"][t][profile]["crossBp"]-e["risk"][t][profile]["withinBp"] for t in types) for e in data["edges"]]
            base=sum(e["risk"][t][profile]["withinBp"] for e in data["edges"] for t in types)
            defs.append({"id":f"{profile}:{selected}","profile":profile,"types":list(types),"denominator":DENOMINATOR,"base":base,"weights":weights})
    # Exact rational sensitivity: interpolate/extrapolate only crossing uplift.
    for numerator in (0,1,2,3,4,6,8):
        weights=[]
        for e in data["edges"]:
            b=sum(e["risk"][t]["reference"]["crossBp"]-e["risk"][t]["reference"]["withinBp"] for t in TYPES)
            w=sum(e["risk"][t]["wet_bog"]["crossBp"]-e["risk"][t]["wet_bog"]["withinBp"] for t in TYPES)
            weights.append(4*b+numerator*(w-b))
        base=4*defs[0]["base"]
        defs.append({"id":f"sensitivity:{numerator}/4","profile":"crossing-only wet uplift sensitivity","types":list(TYPES),"denominator":4*DENOMINATOR,"base":base,"weights":weights,"wetUpliftFactor":{"numerator":numerator,"denominator":4}})
    return defs


def summarise_plan(data, masks, defs):
    labels=allocation(masks)
    cuts=[e["id"] for e in data["edges"] if labels[e["u"]] != labels[e["v"]]]
    return {"allocation":labels,"masks":list(masks),"packages":[[i for i in range(18) if m & (1<<i)] for m in masks],"crossPackageSeams":cuts,"crossPackageSeamCount":len(cuts),"scores":{d["id"]:{"numerator":d["base"]+sum(d["weights"][i] for i in cuts),"denominator":d["denominator"],"expectedCount":(d["base"]+sum(d["weights"][i] for i in cuts))/d["denominator"]} for d in defs}}


def sensitivity_envelope(feasible,defs):
    ref=defs[0]
    wet=defs[4]
    lines={}
    for p in feasible:
        cuts=p["crossPackageSeams"]
        a=ref["base"]+sum(ref["weights"][i] for i in cuts)
        b=sum(wet["weights"][i]-ref["weights"][i] for i in cuts)
        lines.setdefault((a,b),p["allocation"])
    points={Fraction(0),Fraction(2)}
    for (a,b),(c,d) in itertools.combinations(lines,2):
        if b!=d:
            x=Fraction(c-a,b-d)
            if 0<x<2: points.add(x)
    points=sorted(points)
    result=[]
    for left,right in zip(points,points[1:]):
        midpoint=(left+right)/2
        winner=min(lines,key=lambda line:line[0]+line[1]*midpoint)
        if result and result[-1]["line"]==winner:
            result[-1]["right"]=right
        else: result.append({"left":left,"right":right,"line":winner})
    return [{"from":{"numerator":s["left"].numerator,"denominator":s["left"].denominator},
        "to":{"numerator":s["right"].numerator,"denominator":s["right"].denominator},
        "interceptBp":s["line"][0],"slopeBp":s["line"][1],"allocation":lines[s["line"]]} for s in result]


def solve(data):
    start=perf_counter()
    defs=objective_definitions(data)
    nobj=len(defs)
    adjacency=[0]*18
    for e in data["edges"]:
        adjacency[e["u"]] |= 1 << e["v"]
        adjacency[e["v"]] |= 1 << e["u"]
    internal={}
    connected_masks=set()
    for cells in itertools.combinations(range(18),6):
        mask=sum(1<<i for i in cells)
        ids=[e["id"] for e in data["edges"] if mask & (1<<e["u"]) and mask & (1<<e["v"])]
        internal[mask]=tuple(sum(d["weights"][i] for i in ids) for d in defs)
        if connected(mask,adjacency): connected_masks.add(mask)
    best=[[-math.inf,None,0,[]] for _ in defs]
    best_connected=[[-math.inf,None,0,[]] for _ in defs]
    count=connected_count=0
    feasible_allocations=[]
    # Unique representative: A contains tile 0; B contains smallest tile not in A.
    for rest_a in itertools.combinations(range(1,18),5):
        a=1+sum(1<<i for i in rest_a)
        rem=[i for i in range(18) if not a & (1<<i)]
        first=1<<rem[0]
        ai=internal[a]
        a_connected=a in connected_masks
        for rest_b in itertools.combinations(rem[1:],5):
            b=first+sum(1<<i for i in rest_b)
            c=ALL ^ a ^ b
            bi,ci=internal[b],internal[c]
            count+=1
            is_connected=a_connected and b in connected_masks and c in connected_masks
            connected_count+=is_connected
            if is_connected:
                labels=allocation((a,b,c))
                feasible_allocations.append({"allocation":labels,"crossPackageSeams":[e["id"] for e in data["edges"] if labels[e["u"]]!=labels[e["v"]]]})
            for j in range(nobj):
                val=ai[j]+bi[j]+ci[j]
                record=best[j]
                if val>record[0]: record[:]=[val,(a,b,c),1,[(a,b,c)]]
                elif val==record[0]:
                    record[2]+=1
                    if len(record[3])<6: record[3].append((a,b,c))
                if is_connected:
                    record=best_connected[j]
                    if val>record[0]: record[:]=[val,(a,b,c),1,[(a,b,c)]]
                    elif val==record[0]:
                        record[2]+=1
                        if len(record[3])<6: record[3].append((a,b,c))
    expected=math.factorial(18)//(math.factorial(6)**3*math.factorial(3))
    assert count==expected==2858856
    outputs={}
    for domain, records in (("connected",best_connected),("unrestricted",best)):
        outputs[domain]={}
        for d, record in zip(defs,records):
            outputs[domain][d["id"]]={"objective":d["id"],"optimalCount":record[2],"minimumNumerator":d["base"]+sum(d["weights"])-record[0],"denominator":d["denominator"],"plan":summarise_plan(data,record[1],defs),"sampleOptimalAllocations":[allocation(m) for m in record[3]]}
    by_stage=tuple(sum(1<<i for i in range(s*6,s*6+6)) for s in range(3))
    by_chainage=tuple(sum(1<<i for i in range(18) if i%6//2==p) for p in range(3))
    result={"model":data,"objectives":defs,"feasibleConnectedAllocations":feasible_allocations,"crossingSensitivityEnvelope":sensitivity_envelope(feasible_allocations,defs),"baselines":{"stage_bands":summarise_plan(data,by_stage,defs),"chainage_bands":summarise_plan(data,by_chainage,defs)},"optima":outputs,
        "certificate":{"method":"Exhaustive integer enumeration. For each mask of six tiles, precompute internal-edge uplift. Every balanced partition is enumerated once using two anchor rules; minimizing cut uplift is equivalent to maximizing internal uplift. Connected-domain optimum tests connectivity of all three induced subgraphs.","allBalancedUnlabelledPartitions":count,"allBalancedLabelledAllocations":count*6,"connectedUnlabelledPartitions":connected_count,"connectedSixTileSubsets":len(connected_masks),"sixTileSubsets":len(internal),"objectivesCertified":nobj,"inputSha256":hashlib.sha256(json.dumps(data,sort_keys=True,separators=(",",":")).encode()).hexdigest(),"elapsedSeconds":round(perf_counter()-start,3),"independenceAssumed":False,"roundingDuringOptimisation":False}}
    return result


def validate_inputs(data):
    template = make_inputs()
    for field in ("version", "probabilityDenominator", "stages", "tiles", "packageConstraint",
                  "materialLedger", "geometryCounterexample", "profiles"):
        if data[field] != template[field]:
            raise ValueError(f"{field} differs from the fixed Calva example; edit the join probabilities")
    edges = data["edges"]
    if len(edges) != len(template["edges"]):
        raise ValueError("the Calva model expects its 27 joins")
    for index, (edge, expected) in enumerate(zip(edges, template["edges"])):
        if any(edge[key] != value for key, value in expected.items() if key != "risk"):
            raise ValueError(f"join {index} differs from the fixed Calva geometry or ledger")
        if edge["risk"].keys() != expected["risk"].keys():
            raise ValueError(f"join {index} must specify quantity, level and gradient")
        for name in TYPES:
            profiles = edge["risk"][name]
            if profiles.keys() != expected["risk"][name].keys():
                raise ValueError(f"join {index} {name} must specify the three Calva profiles")
            for profile, risk in profiles.items():
                if risk.keys() != {"withinBp", "crossBp"}:
                    raise ValueError(f"join {index} {name} {profile} must specify withinBp and crossBp")
                for key, value in risk.items():
                    if type(value) is not int or not 0 <= value <= DENOMINATOR:
                        raise ValueError(f"join {index} {name} {profile} {key} must be an integer from 0 to 10000")


def result_target_exists(output):
    if output.is_symlink():
        raise ValueError(f"{output} is a symbolic link; choose a regular result file")
    if not output.exists():
        return False
    if output.is_file():
        try:
            previous = json.loads(output.read_bytes())
        except (ValueError, UnicodeError):
            previous = None
        if isinstance(previous, dict) and "edges" not in previous:
            model = previous.get("model")
            if (isinstance(model, dict) and model.get("version") == "calva-earthworks-1"
                    and isinstance(previous.get("certificate"), dict) and "optima" in previous):
                return True
    raise ValueError(f"{output} already exists and is not a Calva result; choose a new output path")


def write_result(output, result):
    # Replace the previous complete result only after the new JSON has been written.
    temporary = None
    try:
        with NamedTemporaryFile(mode="w", encoding="utf-8", dir=output.parent,
                                prefix=f".{output.name}.", delete=False) as stream:
            temporary = Path(stream.name)
            json.dump(result, stream, indent=2)
            stream.write("\n")
        if result_target_exists(output):
            temporary.replace(output)
        else:
            # A concurrent creation at a fresh path must keep its own contents.
            os.link(temporary, output)
    finally:
        if temporary is not None and temporary.exists():
            temporary.unlink()


def main():
    parser = argparse.ArgumentParser(description="Check the Calva drawing allocations exactly.")
    parser.add_argument("--input", type=Path, help="JSON assumptions (default: inputs.json beside the checker, or the built-in example if absent)")
    parser.add_argument("--output", type=Path, help="result path (default: model.json beside the checker)")
    parser.add_argument("--inputs-only", action="store_true", help="write a new editable example instead of calculating (default: inputs.json beside the checker)")
    args = parser.parse_args()
    default_inputs = ROOT / "inputs.json"
    try:
        if args.inputs_only:
            if args.input is not None:
                parser.error("--inputs-only creates example assumptions and cannot take --input")
            target = args.output or default_inputs
            with target.open("x", encoding="utf-8") as stream:
                stream.write(json.dumps(make_inputs(), indent=2) + "\n")
            print(f"Wrote example assumptions to {target}")
            return

        source = args.input or default_inputs
        output = args.output or ROOT / "model.json"
        if source.resolve() == output.resolve() or (
                source.exists() and output.exists() and source.samefile(output)):
            parser.error("input and result must be different files")
        if output.resolve() == default_inputs.resolve():
            parser.error("inputs.json beside the checker is reserved for assumptions")
        if args.input is None and not source.exists() and not source.is_symlink():
            raw = (json.dumps(make_inputs(), indent=2) + "\n").encode("utf-8")
            source_name = "built-in example"
        else:
            raw = source.read_bytes()
            source_name = source.name
        data = json.loads(raw)
        validate_inputs(data)
        result_target_exists(output)
        result = solve(data)
        result["certificate"]["inputSource"] = source_name
        result["certificate"]["inputFileSha256"] = hashlib.sha256(raw).hexdigest()
        write_result(output, result)
    except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
        parser.exit(1, f"{parser.prog}: {error}\n")
    print(f"Wrote results to {output}")
    print(json.dumps(result["certificate"],indent=2))
    for key in ("reference:all","wet_bog:all","bog_joint_review:all"):
        item=result["optima"]["connected"][key]
        print(key,item["minimumNumerator"]/item["denominator"],item["plan"]["allocation"],"ties",item["optimalCount"])


if __name__=="__main__": main()
