"""Counterfactual cut analysis for CF-001/C. Recomputes every count, reachability result
and minimal cut set in the article from graph.yaml.  Needs Python 3 and PyYAML.

  python3 analyze.py                      counts, and cuts for every scenario
  python3 analyze.py --markdown           also print the sensitivity table used in the article
  python3 analyze.py --on D6c1            which targets survive with only these controls switched on,
                                          with one surviving route per target, in every scenario
  python3 analyze.py --on D6c1 --drop 10b the same with transitions removed (here: Hugging Face's account only)
  python3 analyze.py --role               for each preventive control, the scenarios and targets where it
                                          belongs to a minimal cut set of up to three controls
"""
import sys, json, itertools, yaml

def opt(name):
    if name in sys.argv:
        i = sys.argv.index(name)
        if i + 1 < len(sys.argv): return [x for x in sys.argv[i + 1].split(",") if x]
    return []
FLAGS_WITH_VALUE = {"--on", "--drop"}
ARGS = [a for i, a in enumerate(sys.argv[1:], 1) if not a.startswith("--") and sys.argv[i - 1] not in FLAGS_WITH_VALUE]
G = yaml.safe_load(open(ARGS[0] if ARGS else "graph.yaml"))
DROP = set(opt("--drop"))
T = [t for t in G["transitions"] if t["id"] not in DROP]; ROOTS = set(G["roots"])

def active(t, scen):
    if t["kind"] == "alternative" and t["id"] not in scen["alts"]: return False
    if t.get("excluded"): return False
    if t["kind"] == "assumption" and not scen["assume"].get(t["needs"], False): return False
    return True

def prevented(t, controls, scen):
    for c in t["controls"]:
        if c["f"] == "prevent" and c["c"] in controls:
            need = c.get("needs")
            if need is None or scen["assume"].get(need, False): return True
    return False

def reach(controls, scen, witness=False):
    got = set(ROOTS); via = {}; changed = True
    while changed:
        changed = False
        for t in T:
            if t["to"] in got or not active(t, scen) or prevented(t, controls, scen): continue
            if all(f in got for f in t["from"]): got.add(t["to"]); via[t["to"]] = t; changed = True
    return (got, via) if witness else got

def route(state, via, seen=None, out=None):
    """one surviving route to a state, as transition ids in order (AND sources expanded first)"""
    seen = set() if seen is None else seen; out = [] if out is None else out
    t = via.get(state)
    if t is None or t["id"] in seen: return out
    seen.add(t["id"])
    for f in t["from"]: route(f, via, seen, out)
    out.append(t["id"]); return out

PREVENTERS = sorted({c["c"] for t in T for c in t["controls"] if c["f"] == "prevent"})
def targets_reached(controls, scen):
    r = reach(controls, scen); return {k: v["state"] in r for k, v in G["targets"].items()}

def min_cuts(target, scen, maxk=3):
    found = []
    for k in range(1, maxk + 1):
        for combo in itertools.combinations(PREVENTERS, k):
            if any(set(f) <= set(combo) for f in found): continue
            if not targets_reached(set(combo), scen)[target]: found.append(combo)
    return found

def scenario(alts=(), **assume):
    a = {k: v["default"] for k, v in G["assumptions"].items()}; a.update(assume)
    return {"alts": set(alts), "assume": a}

ALL_ALTS = ["3r", "8x", "9x", "10x", "11x"]
SCEN = {
 "Hugging Face's credential account (11c, A1)":  scenario(),
 "OpenAI's credential account (11x)":            scenario(["11x"], A1=False),
 "Extended graph, property B holds":             scenario(ALL_ALTS),
 "Extended graph, property B fails":             scenario(ALL_ALTS, B=False),
}
def atoms():
    out = {"prevent": [], "constrain": [], "none": []}
    for t in T:
        if t["kind"] != "atom": continue
        fs = {c["f"] for c in t["controls"]}
        out["prevent" if "prevent" in fs else "constrain" if "constrain" in fs else "none"].append(t["id"])
    return out

def role():
    """for each preventive control: (scenario, target, cut set) where it is a member of a minimal cut"""
    out = {c: [] for c in PREVENTERS}
    for name, sc in SCEN.items():
        base = targets_reached(set(), sc)
        for tg in G["targets"]:
            if not base[tg]: continue
            for cs in min_cuts(tg, sc):
                for c in cs: out[c].append((name, tg, " + ".join(cs)))
    return out

if __name__ == "__main__":
    if DROP: print(f"Transitions removed for this run: {', '.join(sorted(DROP))}\n")
    on = opt("--on")
    if on:
        bad = [c for c in on if c not in G["controls"]]
        if bad: sys.exit(f"Unknown control(s): {', '.join(bad)}")
        print(f"Controls switched on: {', '.join(on)}. Every other control is off.")
        for name, sc in SCEN.items():
            got, via = reach(set(on), sc, witness=True); base = reach(set(), sc)
            print(f"\n[{name}]")
            for tg, v in G["targets"].items():
                if v["state"] not in base: print(f"   {tg}: no route in this scenario, even with no controls"); continue
                if v["state"] in got: print(f"   {tg}: STILL REACHABLE, for example by {', '.join(route(v['state'], via))}")
                else: print(f"   {tg}: cut")
        sys.exit(0)
    if "--role" in sys.argv:
        r = role()
        for c in PREVENTERS:
            print(f"\n{c} ({G['controls'][c]}): member of a minimal cut in {len(r[c])} case(s)")
            for n, tg, cs in r[c]: print(f"   {n}, {tg}: {cs}")
        sys.exit(0)

    a = atoms(); n = sum(len(v) for v in a.values())
    print(f"Atoms: {n}. Preventive {len(a['prevent'])}, constrain only {len(a['constrain'])}, none {len(a['none'])}")
    for k, v in a.items(): print("  ", k, ", ".join(v))
    res = {"counts": {k: v for k, v in a.items()}, "scenarios": {}}
    for name, sc in SCEN.items():
        base = targets_reached(set(), sc)
        print(f"\n[{name}]  reachable with no controls: {[k for k, v in base.items() if v]}")
        res["scenarios"][name] = {"reachable": base, "cuts": {}}
        for tg in G["targets"]:
            if not base[tg]: print(f"   {tg}: not reachable in this scenario"); continue
            cs = min_cuts(tg, sc); res["scenarios"][name]["cuts"][tg] = [list(c) for c in cs]
            singles = [c[0] for c in cs if len(c) == 1]
            print(f"   {tg}: single control cuts {singles or 'none'}; minimal sets {[' + '.join(c) for c in cs][:8]}")
    if not DROP: json.dump(res, open("results.json", "w"), indent=1)

    if "--markdown" in sys.argv:
        print("\n| Scenario | t_node: single controls that cut it | t_admin: single controls that cut it | t_inv: single controls that cut it |\n|---|---|---|---|")
        for name, sc in SCEN.items():
            base = targets_reached(set(), sc); cells = []
            for tg in G["targets"]:
                if not base[tg]: cells.append("Not reachable"); continue
                s1 = [c[0] for c in min_cuts(tg, sc) if len(c) == 1]
                cells.append(", ".join(s1) if s1 else "None in the register")
            print(f"| {name} | " + " | ".join(cells) + " |")
