"""Shared slicing / margin helpers for the C03_r4 room-fit review (numpy + shapely only).
Source frame: metres, Z up, front = -Y, origin = tower centre. Nothing here modifies any input file."""
import numpy as np, json, struct
import shapely
from shapely.geometry import box, LineString, Polygon, MultiLineString, Point
from shapely.ops import unary_union, polygonize, linemerge, nearest_points

PREC = 1e-4


# ------------------------------------------------------------------ loading
def load_npz(path):
    d = np.load(path)
    names = sorted({k.rsplit("__", 1)[0] for k in d.files})
    return {n: (d[n + "__v"], d[n + "__t"].astype(np.int64)) for n in names}


def load_glb_source_frame(path):
    """Own minimal GLB reader. glTF is Y-up, -Z forward; the C02 export maps source (x,y,z) -> glTF (x, z, -y),
    so source = (gx, -gz, gy). Honors byteStride; one primitive per node; asserts no node transforms."""
    b = open(path, "rb").read()
    ln = struct.unpack("<I", b[8:12])[0]
    off = 12; js = bn = None
    while off < ln:
        cl, ct = struct.unpack("<II", b[off:off + 8]); cd = b[off + 8:off + 8 + cl]; off += 8 + cl
        if ct == 0x4E4F534A: js = json.loads(cd)
        elif ct == 0x004E4942: bn = cd
    ctype = {5126: np.float32, 5125: np.uint32, 5123: np.uint16, 5121: np.uint8}
    ncomp = {"SCALAR": 1, "VEC3": 3}

    def acc(i):
        a = js["accessors"][i]; bv = js["bufferViews"][a["bufferView"]]
        o = bv.get("byteOffset", 0) + a.get("byteOffset", 0); nc = ncomp[a["type"]]; dt = ctype[a["componentType"]]
        stride = bv.get("byteStride")
        if stride and stride != nc * np.dtype(dt).itemsize:
            raw = np.frombuffer(bn, dtype=np.uint8, count=stride * a["count"], offset=o).reshape(a["count"], stride)
            return raw[:, :nc * np.dtype(dt).itemsize].copy().view(dt).reshape(a["count"], nc)
        return np.frombuffer(bn, dtype=dt, count=a["count"] * nc, offset=o).reshape(-1, nc)

    parts = {}
    for n in js["nodes"]:
        assert not any(k in n for k in ("matrix", "rotation", "translation", "scale", "children")), "node transform present"
        for p in js["meshes"][n["mesh"]]["primitives"]:
            v = acc(p["attributes"]["POSITION"]).astype(float)
            src = np.c_[v[:, 0], -v[:, 2], v[:, 1]]
            t = acc(p["indices"]).reshape(-1, 3).astype(np.int64)
            parts[n["name"]] = (src, t)
    return parts


# ------------------------------------------------------------------ slicing
def slice_segments(v, t, z, axis=2):
    """Exact plane slice (coordinate `axis` == z) of a triangle mesh. Returns (n,2,2) segments in the remaining two
    coordinates (for axis=2: x,y; axis=0: y,z; axis=1: x,z). Rule 's>0' decides sides, so on-plane vertices are
    treated consistently."""
    others = [i for i in range(3) if i != axis]
    tri = v[t]
    s = tri[:, :, axis] - z
    pos = s > 0
    cross = pos.any(1) & ~pos.all(1)
    if not cross.any():
        return np.zeros((0, 2, 2))
    tri = tri[cross]; s = s[cross]; pos = pos[cross]
    pts = np.full((len(tri), 3, 2), np.nan)
    for e, (a, c) in enumerate(((0, 1), (1, 2), (2, 0))):
        m = pos[:, a] != pos[:, c]
        u = s[m, a] / (s[m, a] - s[m, c])
        pts[m, e] = tri[m, a][:, others] + u[:, None] * (tri[m, c][:, others] - tri[m, a][:, others])
    valid = ~np.isnan(pts[:, :, 0])
    nvalid = valid.sum(1)
    k2 = np.where(nvalid == 2)[0]
    out = np.zeros((len(k2), 2, 2))
    for j, k in enumerate(k2):
        idx = np.where(valid[k])[0]
        out[j, 0] = pts[k, idx[0]]; out[j, 1] = pts[k, idx[1]]
    ln = np.hypot(out[:, 0, 0] - out[:, 1, 0], out[:, 0, 1] - out[:, 1, 1])
    return out[ln > 1e-9]


def segs_to_lines(segs, prec=PREC):
    if len(segs) == 0:
        return None
    ls = [shapely.set_precision(LineString([tuple(a), tuple(b)]), prec) for a, b in segs]
    ls = [l for l in ls if (not l.is_empty) and l.length > 0]
    return unary_union(ls) if ls else None


_cache = {}


def slice_lines(parts, names, val, axis=2, tag=""):
    allseg = []
    for n in names:
        key = (tag, n, axis, round(val, 4))
        if key in _cache:
            sg = _cache[key]
        else:
            v, t = parts[n]
            lo, hi = v[:, axis].min(), v[:, axis].max()
            sg = slice_segments(v, t, val, axis) if (lo <= val <= hi) else np.zeros((0, 2, 2))
            _cache[key] = sg
        if len(sg): allseg.append(sg)
    return segs_to_lines(np.concatenate(allseg)) if allseg else None


def merged_lines(lines):
    if lines is None: return []
    m = linemerge(lines) if lines.geom_type != "LineString" else lines
    return [m] if m.geom_type == "LineString" else list(m.geoms)


def filled_even_odd(lines):
    """Even-odd fill of the closed rings of a slice (solid cross-section area; open shells give nothing)."""
    reg = Polygon()
    for g in merged_lines(lines):
        if g.is_closed and len(g.coords) >= 4:
            reg = reg.symmetric_difference(Polygon(g).buffer(0))
    return reg


def outer_region(lines):
    """Filled region bounded by the OUTERMOST closed ring of a slice (used for a thin closed shell / open skin surface)."""
    polys = list(polygonize(lines)) if lines is not None else []
    if not polys: return None
    u = unary_union(polys)
    g = u if u.geom_type == "Polygon" else max(u.geoms, key=lambda p: p.area)
    return Polygon(g.exterior)


# ------------------------------------------------------------------ margins
def _worst_outside(rect, region, ns=81):
    minx, miny, maxx, maxy = rect.bounds
    best = (0.0, None, None)
    ring = region.exterior
    pts = [("SW", minx, miny), ("SE", maxx, miny), ("NE", maxx, maxy), ("NW", minx, maxy)]
    for nm, x, y in pts:
        p = Point(x, y)
        d = 0.0 if region.covers(p) else ring.distance(p)
        if d > best[0]: best = (d, nm, (x, y))
    for (ax, ay), (bx, by), nm in (((minx, miny), (maxx, miny), "S edge"), ((maxx, miny), (maxx, maxy), "E edge"),
                                    ((maxx, maxy), (minx, maxy), "N edge"), ((minx, maxy), (minx, miny), "W edge")):
        for q in np.linspace(0, 1, ns)[1:-1]:
            x, y = ax + q * (bx - ax), ay + q * (by - ay)
            p = Point(x, y)
            d = 0.0 if region.covers(p) else ring.distance(p)
            if d > best[0] + 1e-9: best = (d, nm, (x, y))
    return best


CORNER_LABEL = {"SW": "SW corner (-x,-y front-left)", "SE": "SE corner (+x,-y front-right)",
                "NE": "NE corner (+x,+y rear-right)", "NW": "NW corner (-x,+y rear-left)"}


def signed_margin(rect, region):
    """Returns (margin_m, where, point). margin > 0: rectangle inside region, value = min distance from the rectangle
    outline to the region outline. margin < 0: -(largest distance of any rectangle point outside the region);
    `where` names the worst corner/edge, point its xy."""
    if region.covers(rect):
        d = rect.exterior.distance(region.exterior)
        a, b = nearest_points(rect.exterior, region.exterior)
        return float(d), "min-clearance point", (round(a.x, 3), round(a.y, 3))
    d, nm, pt = _worst_outside(rect, region)
    return -float(d), CORNER_LABEL.get(nm, nm), (round(pt[0], 3), round(pt[1], 3))


def classify(m, allowance=1.2, tol=1e-3):
    if m is None: return "NO_SLICE"
    if m >= allowance - tol: return "FITS"
    if m >= 0: return "INSIDE_BELOW_ALLOWANCE"
    return "OUTSIDE"


def boundary_edge_count(v, t, tol=1e-5):
    """Number of mesh edges used by exactly one triangle after welding vertices at `tol`. 0 = closed (no open boundary)."""
    key = np.round(v / tol).astype(np.int64)
    _, inv = np.unique(key, axis=0, return_inverse=True); inv = inv.ravel()
    tt = inv[t]
    ok = (tt[:, 0] != tt[:, 1]) & (tt[:, 1] != tt[:, 2]) & (tt[:, 0] != tt[:, 2]); tt = tt[ok]
    e = np.sort(np.concatenate([tt[:, [0, 1]], tt[:, [1, 2]], tt[:, [2, 0]]]), axis=1)
    _, c = np.unique(e, axis=0, return_counts=True)
    return int((c == 1).sum())
