"""TASK A audit: doors + horizontal circulation for INT R02 (INTERIOR_LAYOUT.json) vs shell C02.
Read-only on inputs. Run with C:/q2/v/Scripts/python.exe. Writes into C:/q2/out/A_doors/.
Labels: measured = computed from file geometry/values; interpreted = my reading of names/intent;
proposed = values that the source itself labels proposed; sweep = parameter sweep, not engine result.
"""
import json, csv, io, subprocess, math, itertools, collections, sys, os
import numpy as np
from shapely.geometry import box, LineString, Point, Polygon
from shapely.ops import unary_union

OUT = "C:/q2/out/A_doors/"
REPO = "C:/q2/r"
COMMIT = "4ce28d8"
INT = "production/assets/buildings/PI-BLD-0001-V01/INT/R02/06_Handoff/"
TOL = 0.01          # m, tolerance for "on edge"/"inside" classification (data are exact to 1e-9, see max_dev)
EXTERNAL = {"EXTERIOR", "PODIUM_BACK_OF_HOUSE"}   # non-room destination tokens found in the data

def git_show(path):
    return subprocess.run(["git", "-C", REPO, "show", f"{COMMIT}:{path}"], capture_output=True, check=True).stdout.decode("utf-8")

D = json.load(open("C:/q2/layout.json"))
rooms = {r["room_id"]: r for r in D["rooms"]}
doors = D["doors"]
cams = D["cameras"]
sched_doors = list(csv.DictReader(io.StringIO(git_show(INT + "DOOR_SCHEDULE.csv"))))
sched_rooms = list(csv.DictReader(io.StringIO(git_show(INT + "ROOM_SCHEDULE.csv"))))
sched_rooms = {r["room_id"]: r for r in sched_rooms}

findings = []   # dict rows
def add(section, subject, level, check, result, value="", param="", label="measured", detail=""):
    findings.append(dict(section=section, subject=subject, level=level, check=check, result=result,
                         value=value, param=param, label=label, detail=detail))

def rect(r):
    return (r["x_m"], r["y_m"], r["x_m"] + r["width_m"], r["y_m"] + r["depth_m"])

def dist_to_rect(px, py, R):
    x0, y0, x1, y1 = R
    return math.hypot(max(x0 - px, 0, px - x1), max(y0 - py, 0, py - y1))

def shared_edge(A, B):
    """A,B rect tuples. returns dict kind touch/overlap/gap"""
    ax0, ay0, ax1, ay1 = A; bx0, by0, bx1, by1 = B
    ox = min(ax1, bx1) - max(ax0, bx0)   # overlap extent in x (neg = gap)
    oy = min(ay1, by1) - max(ay0, by0)
    if ox > TOL and oy > TOL:
        return dict(kind="overlap", area=ox * oy)
    if abs(ox) <= TOL and oy > TOL:      # vertical shared edge, runs along y
        return dict(kind="touch", axis="y", coord=(max(ax0, bx0) + min(ax1, bx1)) / 2, lo=max(ay0, by0), hi=min(ay1, by1))
    if abs(oy) <= TOL and ox > TOL:      # horizontal shared edge, runs along x
        return dict(kind="touch", axis="x", coord=(max(ay0, by0) + min(ay1, by1)) / 2, lo=max(ax0, bx0), hi=min(ax1, bx1))
    gx = max(0, -ox); gy = max(0, -oy)
    return dict(kind="gap", gap=math.hypot(gx, gy))

# ---------------------------------------------------------------- 1. door validation
dtab = []
maxdev = 0.0
by_level_rooms = collections.defaultdict(list)
for r in rooms.values():
    by_level_rooms[r["level_id"]].append(r)

# same-level room overlaps (context for the door checks)
overlaps = []
for lv, rs in by_level_rooms.items():
    for a, b in itertools.combinations(rs, 2):
        s = shared_edge(rect(a), rect(b))
        if s["kind"] == "overlap":
            overlaps.append((a["room_id"], b["room_id"], s["area"]))
for a, b, ar in overlaps:
    add("rooms", f"{a}|{b}", rooms[a]["level_id"], "room rectangles overlap (area m2)", "INFO", round(ar, 3), label="measured",
        detail="planning zones overlap in plan; relevant when a door sits in the overlap")
add("rooms", "ALL", "ALL", "count of overlapping same-level room pairs", "INFO", len(overlaps), label="measured")

seen_id = collections.Counter(d["door_id"] for d in doors)
for d in doors:
    did = d["door_id"]; lv = d["level_id"]; w = d["clear_width_m"]; h = d["clear_height_m"]; ax = d["axis"]
    px, py = d["x_m"], d["y_m"]
    c = px if ax == "x" else py
    f = py if ax == "x" else px
    row = dict(door_id=did, level=lv, type=d["type"], x=px, y=py, axis=ax, w=w, h=h, from_room=d["from_room"], to_room=d["to_room"])
    issues = []
    # id prefix / level
    if not did.startswith(lv + "-"):
        issues.append("door_id prefix != level_id")
    ends = []
    for side in ("from_room", "to_room"):
        rid = d[side]
        if rid in EXTERNAL:
            ends.append((side, rid, None))
        elif rid in rooms:
            ends.append((side, rid, rooms[rid]))
        else:
            ends.append((side, rid, "MISSING"))
            issues.append(f"{side} {rid} not in rooms[]")
    # destination existence / level
    real = []
    for side, rid, r in ends:
        if r is None:
            row[side + "_kind"] = "NON_ROOM_TOKEN"
        elif r == "MISSING":
            row[side + "_kind"] = "MISSING"
        else:
            row[side + "_kind"] = "room"
            real.append((side, rid, r))
            if r["level_id"] != lv:
                issues.append(f"{side} {rid} is on level {r['level_id']} (door level {lv})")
            dd = dist_to_rect(px, py, rect(r))
            maxdev = max(maxdev, dd)
            row[side + "_dist_to_room_m"] = round(dd, 4)
            if dd > TOL:
                issues.append(f"door centre outside {rid} extent by {dd:.3f} m")
    row["n_real_rooms"] = len(real)
    # shared edge between the two rooms
    if len(real) == 2:
        A, B = rect(real[0][2]), rect(real[1][2])
        s = shared_edge(A, B)
        row["pair_relation"] = s["kind"]
        if s["kind"] == "touch":
            row["edge_axis"] = s["axis"]; row["edge_coord"] = round(s["coord"], 4)
            row["edge_lo"] = s["lo"]; row["edge_hi"] = s["hi"]
            off = abs(f - s["coord"]); maxdev = max(maxdev, off)
            row["offset_from_shared_edge_m"] = round(off, 4)
            if s["axis"] != ax:
                issues.append(f"axis {ax} != shared-edge axis {s['axis']}")
            if off > TOL:
                issues.append(f"door {off:.3f} m off shared edge")
            lo_s, hi_s = c - w / 2, c + w / 2
            over = max(0, s["lo"] - lo_s, hi_s - s["hi"])
            row["span_overhang_m"] = round(over, 4)
            row["end_margin_min_m"] = round(min(lo_s - s["lo"], s["hi"] - hi_s), 4)
            if over > TOL:
                issues.append(f"door span overhangs shared edge by {over:.3f} m")
        elif s["kind"] == "gap":
            issues.append(f"rooms do not touch: gap {s['gap']:.3f} m")
        else:
            issues.append(f"rooms overlap in plan (area {s['area']:.2f} m2)")
    elif len(real) == 1:
        side, rid, r = real[0]
        R = rect(r)
        x0, y0, x1, y1 = R
        # which edge is the door on?
        cands = []
        if abs(py - y0) <= TOL or abs(py - y1) <= TOL: cands.append("x")
        if abs(px - x0) <= TOL or abs(px - x1) <= TOL: cands.append("y")
        row["on_perimeter_axis"] = ",".join(cands)
        if ax not in cands:
            issues.append(f"door not on {rid} perimeter edge of axis {ax}")
        # does the opposite side touch another room (i.e. door actually opens into some other room)?
        other = [q["room_id"] for q in by_level_rooms[lv] if q["room_id"] != rid and dist_to_rect(px, py, rect(q)) <= TOL]
        row["other_rooms_at_door_point"] = ";".join(other)
        if other:
            issues.append("door to non-room token but other room(s) at door point: " + ";".join(other))
        if ax == "x":
            lo_s, hi_s, el, eh = c - w / 2, c + w / 2, x0, x1
        else:
            lo_s, hi_s, el, eh = c - w / 2, c + w / 2, y0, y1
        over = max(0, el - lo_s, hi_s - eh)
        row["span_overhang_m"] = round(over, 4)
        if over > TOL:
            issues.append(f"door span overhangs room edge by {over:.3f} m")
    # third rooms containing door centre
    pair_ids = {d["from_room"], d["to_room"]}
    third = [q["room_id"] for q in by_level_rooms[lv] if q["room_id"] not in pair_ids and dist_to_rect(px, py, rect(q)) <= TOL]
    row["third_rooms_at_door_point"] = ";".join(third)
    # (a third room whose boundary merely touches the door point is only an issue if it contains the point in its interior)
    third_int = [q["room_id"] for q in by_level_rooms[lv] if q["room_id"] not in pair_ids and
                 rect(q)[0] + TOL < px < rect(q)[2] - TOL and rect(q)[1] + TOL < py < rect(q)[3] - TOL]
    row["third_rooms_interior_at_door_point"] = ";".join(third_int)
    if third_int:
        issues.append("door centre lies in interior of third room(s): " + ";".join(third_int))
    # heights
    hs = [r["clear_height_m"] for _, _, r in real]
    row["min_room_clear_h"] = min(hs) if hs else ""
    if hs:
        row["lintel_headroom_m"] = round(min(hs) - h, 3)
        if h > min(hs) + 1e-9:
            issues.append(f"door clear_height {h} > room clear_height {min(hs)}")
    row["issues"] = " | ".join(issues)
    row["valid"] = "PASS" if not issues else "FLAG"
    dtab.append(row)

# classify flags: non-room token destinations are intended-but-unmodelled -> separate
for row in dtab:
    notes = []
    if row["from_room_kind"] == "NON_ROOM_TOKEN" or row["to_room_kind"] == "NON_ROOM_TOKEN":
        tok = row["from_room"] if row["from_room_kind"] == "NON_ROOM_TOKEN" else row["to_room"]
        notes.append(f"opens to non-room token {tok} (no room geometry in layout)")
    row["non_room_destination"] = "; ".join(notes)
    add("doors", row["door_id"], row["level"], "door geometry vs from/to rooms",
        row["valid"] if not notes else ("FLAG" if row["valid"] == "FLAG" else "INFO_NON_ROOM_DEST"),
        value=f"offset={row.get('offset_from_shared_edge_m','')}; overhang={row.get('span_overhang_m','')}; end_margin_min={row.get('end_margin_min_m','')}",
        param=f"tol={TOL} m", label="measured", detail=(row["issues"] + (" || " if row["issues"] and notes else "") + "; ".join(notes)))

n_pass = sum(r["valid"] == "PASS" for r in dtab)
add("doors", "ALL", "ALL", "doors passing geometry check (tol 0.01 m)", "INFO", f"{n_pass}/{len(dtab)}", label="measured",
    detail=f"max deviation of any door centre from room extent / shared edge = {maxdev:.6f} m")
# duplicates
dup_ids = [k for k, v in seen_id.items() if v > 1]
add("doors", "ALL", "ALL", "duplicate door_id", "PASS" if not dup_ids else "FAIL", len(dup_ids), detail=";".join(dup_ids))
pos = collections.defaultdict(list)
pair = collections.defaultdict(list)
for d in doors:
    pos[(d["level_id"], d["x_m"], d["y_m"], d["axis"])].append(d["door_id"])
    pair[(d["level_id"], frozenset((d["from_room"], d["to_room"])))].append(d["door_id"])
dpos = {k: v for k, v in pos.items() if len(v) > 1}
add("doors", "ALL", "ALL", "doors with identical (level,x,y,axis)", "PASS" if not dpos else "FAIL", len(dpos), detail=str(dpos))
dpair = {k: v for k, v in pair.items() if len(v) > 1}
for (lv, p), ids in dpair.items():
    # overlapping spans?
    ds = [d for d in doors if d["door_id"] in ids]
    spans = sorted([((d["x_m"] if d["axis"] == "x" else d["y_m"]) - d["clear_width_m"] / 2,
                     (d["x_m"] if d["axis"] == "x" else d["y_m"]) + d["clear_width_m"] / 2, d["door_id"]) for d in ds])
    ov = [(a[2], b[2]) for a, b in zip(spans, spans[1:]) if b[0] < a[1] - 1e-9]
    add("doors", ";".join(ids), lv, "multiple doors between same room pair", "INFO" if not ov else "FLAG", len(ids),
        label="measured", detail=f"pair={sorted(p)}; spans overlap={ov}; type(s)={sorted({d['type'] for d in ds})} "
        "(interpreted: three passenger-lift entrances into one shaft room)")
# id gaps
for lv in ["L00", "L01", "L02", "L03", "L25", "L26"]:
    nums = sorted(int(d["door_id"].split("-D")[1]) for d in doors if d["level_id"] == lv)
    series = collections.defaultdict(list)
    for n in nums:
        series[n // 80].append(n)
    for k, v in series.items():
        full = set(range(min(v), max(v) + 1))
        miss = sorted(full - set(v))
        if miss:
            add("doors", lv, lv, "door_id numbering gap", "INFO", ",".join(f"D{m:03d}" for m in miss), label="measured",
                detail="no door record with this number in this level; whether intentional is unknown")
# check level z consistency of rooms vs door level
add("doors", "ALL", "ALL", "doors whose from/to room is on another level", "PASS" if not any("level" in r["issues"] and "is on level" in r["issues"] for r in dtab) else "FAIL",
    sum("is on level" in r["issues"] for r in dtab), detail="none of the 102 doors crosses a level; no vertical (stair/lift) door records exist")

# ---------------------------------------------------------------- 2. graphs
door_edges = collections.defaultdict(list)
for d in doors:
    door_edges[frozenset((d["from_room"], d["to_room"]))].append(d["door_id"])
conn_dir = set()
for rid, r in rooms.items():
    for t in filter(None, r["connections"].split(";")):
        conn_dir.add((rid, t))
conn_und = {frozenset(e) for e in conn_dir}
# asymmetric connection listings
asym = sorted((a, b) for (a, b) in conn_dir if b in rooms and (b, a) not in conn_dir)
add("graph", "ALL", "ALL", "connections listed one-way only (A lists B, B does not list A)", "PASS" if not asym else "FLAG", len(asym), detail=str(asym))
only_doors = sorted(tuple(sorted(e)) for e in door_edges if e not in conn_und)
only_conn = sorted(tuple(sorted(e)) for e in conn_und if e not in door_edges)
add("graph", "ALL", "ALL", "room pairs with a door but not in `connections`", "PASS" if not only_doors else "FLAG", len(only_doors), detail=str(only_doors))
add("graph", "ALL", "ALL", "room pairs in `connections` but with no door", "PASS" if not only_conn else "FLAG", len(only_conn), detail=str(only_conn))
add("graph", "ALL", "ALL", "distinct door edges / distinct connection edges", "INFO", f"{len(door_edges)}/{len(conn_und)}")
# non-room tokens
add("graph", "ALL", "ALL", "non-room tokens used in connections/doors", "INFO",
    ";".join(sorted({t for (_, t) in conn_dir if t not in rooms} | {x for d in doors for x in (d['from_room'], d['to_room']) if x not in rooms})),
    label="measured")
# compare with DOOR_SCHEDULE.csv
sd = {r["door_id"]: r for r in sched_doors}
ld = {d["door_id"]: d for d in doors}
add("schedule", "DOOR_SCHEDULE.csv", "ALL", "row count / id-set equality vs layout JSON doors", "PASS" if set(sd) == set(ld) and len(sched_doors) == len(doors) else "FAIL",
    f"{len(sched_doors)} vs {len(doors)}", detail=f"only_in_csv={sorted(set(sd)-set(ld))}; only_in_json={sorted(set(ld)-set(sd))}")
fmis = []
for did in sorted(set(sd) & set(ld)):
    for k in ["level_id", "x_m", "y_m", "clear_width_m", "clear_height_m", "axis", "from_room", "to_room", "type", "status"]:
        a, b = sd[did][k], ld[did][k]
        try:
            same = abs(float(a) - float(b)) < 1e-9
        except ValueError:
            same = str(a) == str(b)
        if not same:
            fmis.append((did, k, a, b))
add("schedule", "DOOR_SCHEDULE.csv", "ALL", "field mismatches CSV vs JSON (10 fields x 102 doors)", "PASS" if not fmis else "FAIL", len(fmis), detail=str(fmis))
cmis = [(rid, sched_rooms[rid]["connections"], rooms[rid]["connections"]) for rid in rooms if rid in sched_rooms and sched_rooms[rid]["connections"] != rooms[rid]["connections"]]
add("schedule", "ROOM_SCHEDULE.csv", "ALL", "`connections` mismatches ROOM_SCHEDULE vs JSON", "PASS" if not cmis and set(sched_rooms) == set(rooms) else "FAIL", len(cmis),
    detail=f"rooms only in one source: {sorted(set(sched_rooms)^set(rooms))}; diffs={cmis}")
rmis = []
for rid in rooms:
    if rid in sched_rooms:
        for k in ["level_id", "x_m", "y_m", "width_m", "depth_m", "clear_height_m", "access", "name"]:
            a, b = sched_rooms[rid][k], rooms[rid][k]
            try:
                same = abs(float(a) - float(b)) < 1e-9
            except ValueError:
                same = str(a) == str(b)
            if not same: rmis.append((rid, k, a, b))
add("schedule", "ROOM_SCHEDULE.csv", "ALL", "geometry/name/access field mismatches vs JSON", "PASS" if not rmis else "FAIL", len(rmis), detail=str(rmis))

# per-level adjacency from doors
adj = collections.defaultdict(lambda: collections.defaultdict(set))
doorcount = collections.Counter()
for d in doors:
    a, b = d["from_room"], d["to_room"]
    adj[a][b].add(d["door_id"]); adj[b][a].add(d["door_id"])
    doorcount[a] += 1; doorcount[b] += 1
adjc = collections.defaultdict(set)
for (a, b) in conn_dir:
    adjc[a].add(b); adjc[b].add(a)

def bfs(start, graph, allowed=None):
    seen = {start}; q = [start]
    while q:
        n = q.pop()
        for m in (graph[n].keys() if isinstance(graph[n], dict) else graph[n]):
            if m in seen: continue
            if allowed is not None and m not in allowed and m not in EXTERNAL: continue
            seen.add(m); q.append(m)
    return seen

# orphans
orph = [rid for rid in rooms if doorcount[rid] == 0]
add("graph", "ALL", "ALL", "rooms with zero doors (orphans, door-based)", "PASS" if not orph else "FAIL", len(orph), detail=";".join(orph))
orph_c = [rid for rid in rooms if not adjc[rid]]
add("graph", "ALL", "ALL", "rooms with empty `connections` (orphans, connection-based)", "PASS" if not orph_c else "FAIL", len(orph_c), detail=";".join(orph_c))

LEVELS = ["L00", "L01", "L02", "L03", "L25", "L26"]
# entrance identification (interpreted)
ent_door = [d for d in doors if d["from_room"] == "EXTERIOR" or d["to_room"] == "EXTERIOR"]
add("graph", "L00", "L00", "public entrance identification", "INFO",
    ";".join(f"{d['door_id']}->{d['to_room'] if d['from_room']=='EXTERIOR' else d['from_room']}" for d in ent_door),
    label="interpreted",
    detail="Only one door touches token EXTERIOR: L00-D001 (type portal, 8 x 4.5 m) into L00-RM001 'Arrival atrium'. Cameras 1-4 sit in L00-RM001 "
    "and shots 03/04 (EntranceIn/EntranceOut) look through x=0,y~-52..-58 [cameras: shot3 (0,-58)->(0,-20); shot4 (0,-42)->(0,-56)]. "
    "Second non-room token PODIUM_BACK_OF_HOUSE at L00-D010 is the staff/service entry (A01 access diagram: 'Staff entrance / service lift'; RM006 access=service). "
    "Not ambiguous for the public entrance; no notes[] text names an entrance.")

reach_rows = []
comp_report = {}
for lv in LEVELS:
    rs = [r["room_id"] for r in by_level_rooms[lv]]
    graph = {rid: adj[rid] for rid in rs}
    # components (door graph)
    left = set(rs); comps = []
    while left:
        s = next(iter(left)); comp = {x for x in bfs(s, adj) if x in rooms}
        comp &= set(rs); comps.append(sorted(comp)); left -= comp
    comp_report[lv] = comps
    add("graph", lv, lv, "connected components of door graph (rooms of this level only)", "PASS" if len(comps) == 1 else "FLAG", len(comps),
        detail=("" if len(comps) == 1 else str(comps)))
    # same via connections
    left = set(rs); compsc = []
    while left:
        s = next(iter(left)); comp = {x for x in bfs(s, adjc) if x in rooms} & set(rs); compsc.append(sorted(comp)); left -= comp
    add("graph", lv, lv, "connected components of `connections` graph", "PASS" if len(compsc) == 1 else "FLAG", len(compsc))
    # degree / dead ends
    for rid in rs:
        nb = {x for x in adj[rid]}
        nbr = nb & set(rooms)
        nb_ext = nb - set(rooms)
        if doorcount[rid] == 1:
            add("graph", rid, lv, "room has exactly ONE door", "INFO", f"neighbour={sorted(nb)}", label="measured",
                detail=f"name='{rooms[rid]['name']}', access={rooms[rid]['access']}; dead end unless it is a terminal use (interpreted)")
        elif len(nb) == 1:
            add("graph", rid, lv, "room has several doors but ONE distinct neighbour (still a dead end)", "INFO",
                f"doors={sorted(set().union(*adj[rid].values()))}; neighbour={sorted(nb)}", label="measured", detail=f"name='{rooms[rid]['name']}'")
    # articulation rooms (cut vertices) in door graph restricted to level rooms (+ external tokens ignored)
    for rid in rs:
        rest = set(rs) - {rid}
        if not rest: continue
        s = next(iter(rest))
        seen = {s}; q = [s]
        while q:
            n = q.pop()
            for m in adj[n]:
                if m in rest and m not in seen: seen.add(m); q.append(m)
        if seen != rest:
            lost = sorted(rest - seen)
            add("graph", rid, lv, "cut room: removing it disconnects other rooms (door graph)", "INFO", f"{len(lost)} rooms cut off",
                label="measured", detail="cut off: " + ";".join(lost))

# L00 reachability from public entrance (door graph and connections graph)
l00 = {r["room_id"] for r in by_level_rooms["L00"]}
reach_d = {x for x in bfs("EXTERIOR", adj) if x in rooms}
reach_c = {x for x in bfs("EXTERIOR", adjc) if x in rooms}
add("graph", "L00", "L00", "L00 rooms reachable from EXTERIOR (public entrance D001) via doors", "PASS" if reach_d >= l00 else "FAIL",
    f"{len(reach_d & l00)}/{len(l00)}", detail=f"unreachable={sorted(l00-reach_d)}")
add("graph", "L00", "L00", "L00 rooms reachable from EXTERIOR via `connections`", "PASS" if reach_c >= l00 else "FAIL",
    f"{len(reach_c & l00)}/{len(l00)}", detail=f"unreachable={sorted(l00-reach_c)}")
# without the staff token: path from public entrance not using service-access rooms as transit
pub_transit = {rid for rid in l00 if rooms[rid]["access"] != "service"}
seen = {"EXTERIOR"}; q = ["EXTERIOR"]
while q:
    n = q.pop()
    for m in adj[n]:
        if m in seen: continue
        if m in rooms and m not in pub_transit: continue
        seen.add(m); q.append(m)
unreach_pub = sorted(l00 - seen)
add("graph", "L00", "L00", "L00 rooms reachable from public entrance WITHOUT passing through a service-access room", "INFO",
    f"{len(seen & l00)}/{len(l00)}", label="interpreted",
    detail=f"only reachable via service rooms (or not at all): {unreach_pub}. 'access' strings are the schedule's; access control itself is not tested.")
# staff entry reachability
reach_s = {x for x in bfs("PODIUM_BACK_OF_HOUSE", adj) if x in rooms}
add("graph", "L00", "L00", "L00 rooms reachable from PODIUM_BACK_OF_HOUSE (staff door D010) via doors", "INFO", f"{len(reach_s & l00)}/{len(l00)}",
    detail=f"not reachable from staff door: {sorted(l00-reach_s)}")

# upper levels reachability
for lv in ["L01", "L02", "L03", "L25", "L26"]:
    rs = {r["room_id"] for r in by_level_rooms[lv]}
    for start_name, start in (("lift hall RM080", f"{lv}-RM080"), ("stair A RM090", f"{lv}-RM090"), ("service lift RM093", f"{lv}-RM093")):
        rch = {x for x in bfs(start, adj) if x in rooms} & rs
        add("graph", lv, lv, f"rooms reachable on this level from {start_name} (door graph)", "PASS" if rch == rs else "FLAG", f"{len(rch)}/{len(rs)}",
            label="measured", detail=f"unreachable={sorted(rs-rch)}")

# vertical links: NOT present as door/connection records. Interpreted building-wide reachability with stacked cores
def stack_edges():
    E = collections.defaultdict(set)
    for suffix in ("RM090", "RM091", "RM092", "RM093"):
        ids = [f"{lv}-{suffix}" for lv in LEVELS]
        for a, b in zip(ids, ids[1:]):
            E[a].add(b); E[b].add(a)
    return E
VE = stack_edges()
allg = collections.defaultdict(set)
for a in adj:
    for b in adj[a]: allg[a].add(b)
for a in VE:
    allg[a] |= VE[a]
tot = {x for x in bfs("EXTERIOR", allg) if x in rooms}
add("graph", "ALL", "ALL", "all-81-room reachability from EXTERIOR using stacked core links (RM090-093 same id on consecutive scheduled levels)", "INFO",
    f"{len(tot)}/{len(rooms)}", label="interpreted",
    detail="NO vertical edge exists in doors[] or connections[]; the stacked-core links are my interpretation of MODELING_BRIEF ('Stack core zones on the six scheduled levels and interpolate through intervening floors'). "
    f"Unreachable under that interpretation: {sorted(set(rooms)-tot)}. L04-L24 have no layout, so L03->L25 continuity is unverifiable from data.")
add("graph", "ALL", "ALL", "vertical continuity between levels (stair/lift flights, lift cab, landings)", "UNKNOWN", "", label="measured",
    detail="doors[] holds only same-level doors; lift doors are type 'lift' between RM080 and RM092 / RM093 and RM094 only. No flight, cab, or landing geometry in layout JSON.")

# ---------------------------------------------------------------- 3. capsule sweep
SWEEP = [0.6, 0.7, 0.8, 1.0]
sw_rows = []
for d in doors:
    r = dict(door_id=d["door_id"], level=d["level_id"], type=d["type"], clear_width_m=d["clear_width_m"], clear_height_m=d["clear_height_m"])
    for dia in SWEEP:
        r[f"pass_d{dia}"] = d["clear_width_m"] >= dia - 1e-9
        r[f"slack_per_side_d{dia}_m"] = round((d["clear_width_m"] - dia) / 2, 3)
    for ch in (1.8, 2.0):
        r[f"headroom_over_{ch}_m"] = round(d["clear_height_m"] - ch, 3)
    sw_rows.append(r)
for dia in SWEEP:
    fails = [r["door_id"] for r in sw_rows if not r[f"pass_d{dia}"]]
    add("capsule_sweep", f"d={dia}", "ALL", "doors with clear_width_m < capsule diameter (PARAMETER SWEEP, not engine result)", "PASS" if not fails else "FAIL",
        len(fails), param=f"diameter={dia} m", label="measured (arithmetic on schedule widths)", detail=";".join(fails))
wmin = min(d["clear_width_m"] for d in doors)
narrow = [d["door_id"] for d in doors if d["clear_width_m"] == wmin]
add("capsule_sweep", "ALL", "ALL", "narrowest clear_width_m in schedule", "INFO", wmin, label="measured",
    detail=f"{len(narrow)} doors: {';'.join(narrow)}. Any capsule diameter > {wmin} m fails these (sweep arithmetic only). At d=1.0 the per-side slack of these is {(wmin-1.0)/2:.2f} m.")
wc = collections.Counter(d["clear_width_m"] for d in doors)
add("capsule_sweep", "ALL", "ALL", "clear_width_m distribution", "INFO", json.dumps(dict(sorted(wc.items()))), label="measured")
hmin = min(d["clear_height_m"] for d in doors); hmax = max(d["clear_height_m"] for d in doors)
add("capsule_sweep", "ALL", "ALL", "door clear_height_m min / max", "INFO", f"{hmin} / {hmax}", label="measured",
    detail=f"min {hmin}: {';'.join(d['door_id'] for d in doors if d['clear_height_m']==hmin)}; max {hmax}: {';'.join(d['door_id'] for d in doors if d['clear_height_m']==hmax)}")
for ch in (1.8, 2.0):
    fails = [d["door_id"] for d in doors if d["clear_height_m"] < ch]
    add("capsule_sweep", f"h={ch}", "ALL", f"doors with clear_height_m < character height", "PASS" if not fails else "FAIL", len(fails),
        param=f"character height={ch} m", label="measured (arithmetic)", detail=f"smallest headroom {hmin-ch:.2f} m over {ch} m character at the lift doors; capsule height for camera not tested")
rh = max(r["clear_height_m"] for r in rooms.values())
add("capsule_sweep", "ALL", "ALL", "tallest room clear_height_m", "INFO", rh, label="measured",
    detail=";".join(r["room_id"] for r in rooms.values() if r["clear_height_m"] == rh) + f"; room heights present: {sorted({r['clear_height_m'] for r in rooms.values()})}")
mr = min(min(r["width_m"], r["depth_m"]) for r in rooms.values())
add("capsule_sweep", "ALL", "ALL", "smallest room plan dimension (m)", "INFO", mr, label="measured",
    detail=";".join(r["room_id"] for r in rooms.values() if min(r["width_m"], r["depth_m"]) == mr))
ez = [round(c["camera_z_m"] - rooms[c["room_id"]]["z_m"], 3) for c in cams]
add("capsule_sweep", "cameras", "ALL", "camera height above level floor (m): min/max", "INFO", f"{min(ez)} / {max(ez)}", label="measured",
    detail="camera heights are reconstruction cameras, NOT a character capsule/eye-height specification")
add("capsule_sweep", "ALL", "ALL", "hinged-door swing, hinge side, leaf thickness, threshold, lift cab inner width, stair headroom", "UNKNOWN", "", label="measured",
    detail="schedule gives only clear_width_m/clear_height_m/type; no swing, hinge or threshold data, so swing-vs-capsule conflicts were not tested")

# ---------------------------------------------------------------- 4. shell check for exterior doors
# reuse slicing helper from refit.py (copied by exec of its header, not edited)
src = open("C:/q2/refit.py").read().split("L=json.load")[0]
g = {}
exec(src, g)
mesh = g["mesh"]; slice_segs = g["slice_segs"]
shell_rows = []

def objs_near(x0, y0, x1, y1, zlo, zhi):
    out = []
    for nm, (v, t) in mesh.items():
        if v[:, 2].max() < zlo or v[:, 2].min() > zhi: continue
        if v[:, 0].max() < x0 or v[:, 0].min() > x1 or v[:, 1].max() < y0 or v[:, 1].min() > y1: continue
        out.append(nm)
    return out

# D001 portal
d1 = ld["L00-D001"]
cx, cy, w, h = d1["x_m"], d1["y_m"], d1["clear_width_m"], d1["clear_height_m"]
near = objs_near(cx - 20, cy - 12, cx + 20, cy + 6, 0, h)
add("shell_C02", "L00-D001", "L00", "shell objects within 20 x 18 m window of the portal, z 0..4.5", "INFO", ";".join(near), label="measured")
vz = [0.5, 2.25, 4.0]
for z in vz:
    segs = []
    for nm in near:
        for s in slice_segs([nm], z):
            segs.append((nm, s))
    door_line = LineString([(cx - w / 2, cy), (cx + w / 2, cy)])
    for nm in sorted({n for n, _ in segs}):
        ss = [s for n, s in segs if n == nm]
        dmin = min(s.distance(Point(cx, cy)) for s in ss)
        # nearest segment y at x=cx (ray along y through the portal axis)
        ray = LineString([(cx, cy - 15), (cx, cy + 5)])
        ys = []
        for s in ss:
            ip = s.intersection(ray)
            if not ip.is_empty:
                ys.extend([p.y for p in (ip.geoms if hasattr(ip, "geoms") else [ip]) if p.geom_type == "Point"])
        crosses = [s for s in ss if s.intersects(door_line)]
        shell_rows.append(dict(door="L00-D001", z=z, object=nm, dist_door_centre_to_nearest_segment_m=round(dmin, 3),
                               y_where_x0_axis_crosses=";".join(f"{y:.3f}" for y in sorted(set(round(y, 3) for y in ys))), segments_crossing_door_span=len(crosses)))
        add("shell_C02", "L00-D001", "L00", f"horizontal slice z={z}: {nm}", "INFO",
            f"nearest={dmin:.3f} m; y at x=0 axis: {sorted(set(round(y,3) for y in ys))}; segments crossing door span: {len(crosses)}", label="measured")

# Podium_wall_1 front face coverage of the door opening (xz projection of triangles lying on a y-plane)
v, t = mesh["Podium_wall_1"]
tri = v[t]
front = [tr for tr in tri if np.allclose(tr[:, 1], tr[0, 1], atol=1e-6) and tr[0, 1] < -40]
yfront = sorted({round(float(tr[0, 1]), 3) for tr in front})
polys = [Polygon([(p[0], p[2]) for p in tr]) for tr in front if Polygon([(p[0], p[2]) for p in tr]).area > 1e-9]
cover = unary_union(polys)
opening = box(cx - w / 2, 0.0, cx + w / 2, h)
cov_area = cover.intersection(opening).area
add("shell_C02", "L00-D001", "L00", "Podium_wall_1 front plane y (m)", "INFO", yfront, label="measured",
    detail=f"front wall quad x-range {min(p[0] for tr in front for p in tr):.1f}..{max(p[0] for tr in front for p in tr):.1f}, z {min(p[2] for tr in front for p in tr):.2f}..{max(p[2] for tr in front for p in tr):.2f}; zero-thickness surface (single quad pair per wall segment, 16 triangles total, no aperture)")
add("shell_C02", "L00-D001", "L00", "door y vs Podium_wall_1 front plane (offset, m)", "FLAG" if abs(cy - yfront[0]) > TOL else "PASS", round(cy - yfront[0], 3),
    param=f"tol={TOL}", label="measured", detail=f"door y={cy}; wall y={yfront[0]}; door is {abs(cy-yfront[0]):.2f} m inside (behind) the wall surface; room RM001 front edge y={rooms['L00-RM001']['y_m']}")
add("shell_C02", "L00-D001", "L00", "fraction of door opening rectangle (x ±4, z 0..4.5) covered by solid Podium_wall_1 triangles", "FLAG" if cov_area > 1e-6 else "PASS",
    f"{cov_area/opening.area:.3f}", label="measured",
    detail="Podium_wall_1 has no aperture at the portal: the shell wall is closed across the entrance at this z range (wall starts z=0.2, so the 0..0.2 sliver is uncovered). "
    "Whether the C02 builder intends the glass wall to be replaced by the entry frame is unknown.")
# Main_entry frame
v, t = mesh["Main_entry_clear_18x14"]
mn, mx = v.min(0), v.max(0)
add("shell_C02", "L00-D001", "L00", "Main_entry_clear_18x14 bbox (x,y,z)", "INFO", f"x {mn[0]:.2f}..{mx[0]:.2f}; y {mn[1]:.2f}..{mx[1]:.2f}; z {mn[2]:.2f}..{mx[2]:.2f}", label="measured",
    detail=f"frame mid-plane y={(mn[1]+mx[1])/2:.2f}; portal door y={cy}: frame rear face is {abs(mx[1]-cy):.2f} m in front of the door, frame mid-plane {abs((mn[1]+mx[1])/2-cy):.2f} m in front; "
    "frame is a 2.2 m deep arch (outer x ±10.5, inner ±9 at z<=4.5)")
inner_half = 9.0
add("shell_C02", "L00-D001", "L00", "portal x-span (±4) inside entry arch inner opening (±9 at z<=4.5)", "PASS", f"margin {inner_half-w/2:.1f} m per side", label="measured")
v, t = mesh["Entry_glass_canopy"]; mn, mx = v.min(0), v.max(0)
add("shell_C02", "L00-D001", "L00", "Entry_glass_canopy bbox vs portal", "INFO", f"x {mn[0]:.2f}..{mx[0]:.2f}; y {mn[1]:.2f}..{mx[1]:.2f}; z {mn[2]:.2f}..{mx[2]:.2f}", label="measured",
    detail=f"canopy underside z={mn[2]:.2f} is {mn[2]-h:.2f} m above portal top ({h}); canopy rear edge y={mx[1]:.2f} equals door y={cy}")
v, t = mesh["Front_amber_atrium_skin"]
sel = v[(np.abs(v[:, 0]) <= 8.001) & (v[:, 2] <= 4.6)]
add("shell_C02", "L00-D001", "L00", "Front_amber_atrium_skin lowest edge", "INFO", f"z {v[:,2].min():.2f}; y at that edge {sorted(set(float(q) for q in np.round(v[v[:,2]<4.6][:,1],3)))}; x ±{np.abs(v[v[:,2]<4.6][:,0]).max():.1f}", label="measured",
    detail="amber atrium skin starts at z=4.5 = portal height, y=-52.6 (0.6 m in front of door plane); x ±8 vs portal ±4")
# D010 back-of-house
d10 = ld["L00-D010"]
px, py = d10["x_m"], d10["y_m"]
for z in (1.35,):
    near10 = objs_near(px - 25, py - 25, px + 25, py + 25, z - 0.1, z + 0.1)
    allseg = []
    for nm in near10:
        for s in slice_segs([nm], z): allseg.append((nm, s))
    best = sorted(((s.distance(Point(px, py)), nm) for nm, s in allseg))[:1]
    ys0 = LineString([(px - 40, py), (px + 5, py)])
    xs = []
    for nm, s in allseg:
        ip = s.intersection(ys0)
        if not ip.is_empty and ip.geom_type == "Point": xs.append((round(ip.x, 3), nm))
    add("shell_C02", "L00-D010", "L00", f"nearest C02 shell segment to door centre at z={z} (m)", "FLAG", f"{best[0][0]:.3f} ({best[0][1]})" if best else "none", label="measured",
        detail=f"door at ({px},{py}) opens west to token PODIUM_BACK_OF_HOUSE; shell crossings of the line y={py} west of the door: {sorted(xs)}. "
        "Door is not on a shell wall line; between the door and Podium_wall_1 (x=-54.5) lies unmodelled space (no room/zone in layout).")
    shell_rows.append(dict(door="L00-D010", z=z, nearest_object=best[0][1] if best else "", nearest_dist_m=round(best[0][0], 3) if best else "", crossings_west=str(sorted(xs))))
add("shell_C02", "ALL", "L25/L26", "other exterior/shell-facing doors", "INFO", "none", label="measured",
    detail="Only L00-D001 (EXTERIOR) and L00-D010 (PODIUM_BACK_OF_HOUSE) leave the room set. L01-L03/L25/L26 doors are all room-to-room. Upper-level shell fit is another task.")

# ---------------------------------------------------------------- write outputs
def wcsv(path, rows, cols=None):
    if not rows: return
    cols = cols or list(rows[0].keys())
    for r in rows:
        for k in r:
            if k not in cols: cols.append(k)
    with open(path, "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=cols); w.writeheader(); w.writerows(rows)

for i, r in enumerate(findings, 1): r["finding_id"] = f"A-{i:04d}"
cols = ["finding_id", "section", "subject", "level", "check", "result", "value", "param", "label", "detail"]
wcsv(OUT + "findings.csv", findings, cols)
wcsv(OUT + "door_table.csv", dtab)
wcsv(OUT + "capsule_sweep.csv", sw_rows)
wcsv(OUT + "shell_checks.csv", shell_rows)
edges = [dict(edge="|".join(sorted(e)), in_doors=e in door_edges, door_ids=";".join(door_edges.get(e, [])), in_connections=e in conn_und) for e in sorted(set(door_edges) | conn_und, key=lambda e: sorted(e))]
wcsv(OUT + "graph_edges.csv", edges)
summary = dict(
    inputs=dict(layout="C:/q2/layout.json", repo_commit=COMMIT, door_schedule=INT + "DOOR_SCHEDULE.csv", shell_glb="SHELL-C02 glb via C:/q2/refit.py slicing helper", tolerance_m=TOL),
    counts=dict(rooms=len(rooms), doors=len(doors), cameras=len(cams), door_pass=n_pass, door_flag=len(doors) - n_pass),
    result_counts=dict(collections.Counter(f["result"] for f in findings)),
    door_geometry_flags=[dict(door_id=r["door_id"], issues=r["issues"], non_room=r["non_room_destination"]) for r in dtab if r["valid"] != "PASS" or r["non_room_destination"]],
    max_deviation_m=maxdev,
    findings=findings)
json.dump(summary, open(OUT + "findings.json", "w"), indent=1, default=str)
print(json.dumps({k: v for k, v in summary.items() if k != "findings"}, indent=1, default=str))
