"""
Build a roof as a PLANAR PARTITION of the surveyed footprint, cut only by
straight lines, refined until the planes explain the LiDAR.

The design constraint: most roofs are simple. They are straight lines at a
few angles, never organic shapes. Large buildings are the same principles
repeated -- a hotel is many house-like roofs on one footprint, a warehouse
is several flat or pitched sections at differing pitches and cut-offs.

Two consequences, and they are the whole module.

STRAIGHT BY CONSTRUCTION. Every facet boundary is either a footprint edge
(surveyed by LINZ, already straight) or a cut line. No boundary is ever traced
from a raster. That alone removes a recurring defect:
the shipped facets on 29 Edinburgh Dr carry 1335-1835 vertices each on a roof
that is four rectangles, and on 1/5 Sydney St 874-1035 each. A partition cannot
produce those shapes -- the vertex count is bounded by the number of cuts.

COMPLEXITY EARNED, NOT ASSUMED. Fitting one template per building would fit
a simple roof where the real roof is more complex. So nothing is assumed
about how many faces a roof has. A region is kept whole when one plane already explains its
points; it is cut when a plane does not, and each half is then asked the same
question. A simple gable stops after one cut. A hotel keeps going. The stopping
rule is fit quality, so complexity is spent only where the roof actually has it.

Cut directions come from the footprint itself. Roofs are built on walls, so
ridges, hips and valleys run parallel or perpendicular to the walls below far
more often than not, and the surveyed outline is a better source for those
angles than anything recoverable from a 5.7 pts/m2 cloud.

Map of this module (grep the function name, line numbers rot):

  1. Plane fitting and partition core: _fit_plane / _fit_plane_robust,
     _partition (the recursive cut engine), partition_by_planes
  2. Point utilities: top_surface (top-of-cloud filter), _points_in,
     explained_fraction
  3. GEOMETRY SOURCES, in the precedence the build applies them --
     partition_with_labels / facets_from_drawn_faces (the owner's markup,
     exempt from all quality gates), facets_from_selected_faces (the
     precomputed SAM/line/LiDAR winner behind SOLAR_SELECTED_FACES=1,
     one-plane gate + RESIDUAL FILL so coverage is guaranteed),
     line_facets (vision-line polygonisation), partition_roof (old path)
  4. Footprint hygiene: trim_to_roof (courtyards, decks)

The precedence contract and per-rule history live in
docs/developers/reviewers-guide.md.
"""

import json
import math
import os
import sys
import warnings
from pathlib import Path

import time

import numpy as np
import shapely
from shapely.geometry import LineString, Point, Polygon
from shapely.ops import split as shapely_split, snap, unary_union

warnings.filterwarnings("ignore")
# ...but never deprecations. A blanket ignore is exactly how 68 calls to
# shapely.vectorized -- an API documented for REMOVAL, under an unpinned
# shapely>=2.0 -- stayed invisible until 31 Aug. Third-party noise stays
# suppressed; a countdown to the pipeline breaking does not.
warnings.filterwarnings("default", category=DeprecationWarning)
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import config

# A facet is accepted when this share of its points lie within the band below.
# 0.15 m is a little over twice the DSM's own noise, so a genuine plane clears
# it easily and a plane spanning two faces cannot.
ACCEPT_INLIER = 0.85
INLIER_BAND_M = 0.15

MIN_FACET_M2 = 6.0          # below ~3 panels a face is not worth racking
MIN_PIECE_M2 = 4.0          # a cut may not leave a sliver smaller than this
# Depth alone is the WRONG stopping rule and it was quietly ruining the hardest
# roofs. Cuts do not halve a region evenly -- a ridge shaves a strip off one
# side -- so a large remainder can descend seven levels while barely shrinking,
# exhaust its budget and be returned whole. On 1/5 Sydney St that surrendered a
# 138 m2 face at 15% on-plane, 40% of the footprint, even though _best_cut had
# a 25% cut available for it. Depth is now generous and the real brakes are
# size and a per-building face cap, both of which track what is actually being
# spent rather than how many times the function has recursed.
MAX_DEPTH = 14
MAX_FACES = 60              # a hotel needs many; nothing real needs more
MIN_POINTS = 25

# A wall is not a roof. 26 Panorama Terrace is a stepped house and the pipeline
# put 36.8 m2 of it -- 31% of the modelled roof -- on faces of 42.3 and 44.5
# degrees, which on that building are the risers between levels. 1 Church St had
# a 10.2 m2 face at 42.8 degrees fitting its own points at 29.6%. District-wide
# 10.3% of every panel, carrying 9.2% of the claimed generation, sits above 35
# degrees.
#
# But slope alone must not disqualify a face, and the measurement says why:
# across 510 faces from 90 random pilot buildings, faces at 40 degrees or more
# fit under 70% in 32% of cases against 11% for shallower ones -- so steep faces
# are three times as likely to be wrong, and two thirds of them are still fine.
# Queenstown has genuinely steep roofs, so a face is dropped only when it is
# BOTH steep and badly fitted.
STEEP_FACE_DEG = 40.0
STEEP_FACE_MIN_FIT = 0.70

# A WELL-FITTED wall. The filter above cannot catch the real risers, and the
# measurement on 26 Panorama Terrace shows why: its two step risers sit at 42.3
# and 44.5 degrees and fit 89.0% and 89.8% -- a wall is a perfect plane, so the
# better the wall, the higher the fit. What separates a riser from a steep roof
# is its RUN: the horizontal extent along its own gradient. A riser is a strip
# standing up -- its z-range divided by tan(slope) is the height of one storey
# step over its pitch, 1.4-2.5 m on every riser measured -- while a genuine
# steep roof face runs 3 m or more downhill. Measured runs: Panorama risers
# 1.6 m and 2.5 m, 15B Frankton's 37.5-degree strip 1.4 m.
STEEP_RUN_DEG = 35.0         # faces this steep are tested as possible risers
STEEP_MIN_RUN_M = 3.0        # a riser has less downhill run than this
RISER_SLOPE_GAP_DEG = 15.0   # ...and every face it touches is this much flatter

# A wall-clock ceiling on the cut search for ONE building.
#
# Bounding the search by a count of candidate cuts was tried first and it is the
# wrong meter: the cost of one evaluation is a polygon split plus two plane fits
# over whatever points fall in the region, so it scales with point density. A
# 219 m2 house spends 4,782 evaluations and finishes in under a second, while
# 4722059 (16,010 m2, 226 m across, 73,226 points) spends ~3 ms on each one. Any
# count low enough to bound the big roof also truncates ordinary buildings --
# measured: a 12,000 cap left a 1,725 m2 building clipped mid-search while it
# had been finishing comfortably in 14 s.
#
# Time bounds the actual pathology and nothing else. Every roof that completes
# quickly is bit-for-bit unchanged, because the deadline is never reached; only
# a roof that is genuinely running long gets stopped, and it keeps the faces it
# has already found -- still watertight, still a valid partition, just coarser.
# Anything that ends up badly fitted is withheld by the confidence gate in
# build_layout_geojson rather than published wrong.
CUT_TIME_BUDGET_S = 60.0     # base; scaled up with roof area, see partition_roof.
# 60s flat starved exactly the roofs that matter most: 32 Frankton Road
# (4,032 m2, 31,776 points) hit the deadline before the search made one good
# cut and shipped as a 5,128 m2 sheet fitting 12.9% -- with 1,138 panels on it.
# The budget exists to stop a stall, not to decide segmentation quality, so it
# scales with the work: a house keeps 60s it never uses, a big commercial roof
# gets up to 240s.
CUT_TIME_BUDGET_MAX_S = 240.0
CUT_TIME_PER_M2_S = 0.05
_cut_deadline = [None]
_cut_evals = [0]
CUT_BUDGET_EXHAUSTED = [0]

ANGLE_TOL_DEG = 4.0         # footprint edge directions this close are one direction
MAX_OFFSETS_PER_DIRECTION = 120   # cap on how many cut positions one direction is
# tried at. The sweep costs a polygon split and two plane fits PER POSITION, at
# every node of the recursion, so its cost grows with the span of the roof --
# fine at house scale, ruinous above it. Building 4722059 on Frankton Flats is
# 16,010 m2: ~200 m across is ~800 positions per direction per node, and it ran
# for over an hour at 100% CPU without finishing, stalling two full rebuilds.
# The cap only binds above a ~30 m span (120 * 0.25 m), so every house and most
# commercial roofs sweep at exactly the old 0.25 m and are bit-for-bit
# unchanged; only genuinely large roofs are coarsened, and 0.25 m precision on a
# 200 m warehouse was never meaningful anyway.
OFFSET_STEP_M = 0.25        # how finely each candidate direction is swept. A ridge cut
# landing half a metre off leaves a strip of the WRONG plane on both sides of it,
# which drags the fit down on exactly the roofs whose structure was found correctly.
# A cut only has to help at all, not pay for itself immediately. Requiring a
# real gain from each single cut was tried and it makes the recursion blind:
# on 1/5 Sydney St, a twelve-unit roof, the whole footprint fits one plane at
# 13% and the BEST available single cut reaches only 16%, because both halves
# are still multi-plane messes. That roof needs about ten cuts before the fit
# improves sharply, and a one-step-lookahead test can never see past the first.
# So the stopping rule is "this region is now explained" -- or too small, or too
# deep -- and over-splitting is handled afterwards by _merge_bridgeable, which
# undoes any cut a panel could lie across anyway.
MIN_SPLIT_GAIN = 0.005
# How much usable area a cut may cost, PER POINT of fit it buys. An absolute cap
# was tried first and is wrong: one legitimate ridge cut across a 15 m roof
# already costs about 7 m2 of setback, so any flat cap tight enough to stop
# over-fragmentation also stops the first honest cut, and every roof collapsed
# to a single facet at 38% on-plane.
#
# Scaling it by the fit gain is the honest trade. A cut that takes a roof from
# 30% to 90% on-plane has fixed the building and has earned a lot of setback; a
# cut that buys two points has not earned any.
# Swept, not guessed. 0.5 was shipped first and was badly wrong: it cost 20
# points of fit on complex roofs (64% on-plane against 86% with the rule off)
# to buy a facet count that was not needed -- 47 Stanley St fell from 22 facets
# at 96% to 4 at 53%, which is under-modelling a roof, not making it blocky.
#
#   cost/fit    hard roofs              random roofs
#   0.5         64% on-plane,  4 facets   83%,  4
#   2.0         84%,          11          93%,  6
#   unlimited   86%,          12          93%,  6
#
# 2.0 takes essentially all the available fit while houses still come back at
# about six faces, which is the blockiness real roofs have. Past 2.0 nothing
# changes, so the rule is only ever binding on the roofs where it should be.
SETBACK_COST_PER_FIT = 2.0
# THE PARTITION'S SETBACK IS NOT THE PANEL SETBACK. Cut economics were tuned
# with a 0.25 m strip: a cut has to buy more fit than the racking area its
# ridge strip costs. When config.RIDGE_SETBACK_M went to 0.1 for the panels,
# every cut became 2.5x cheaper here, the recursion bought
# fit it should not have, and 40 Avalon Crescent (#4747072) went from 3
# faces and 81% of its roof to one face and 18% -- bisected to that one
# constant. What panels keep clear of a ridge is a product decision; what a
# partition pays for a cut is a tuning of this module, and stays put.
PARTITION_SETBACK_M = 0.25

# A "fold" test was tried here -- treat a face carrying points far off its own
# plane as containing a physical drop, and cut it regardless of setback cost.
# It does not work, and the reason is worth keeping: the signal does not
# separate the cases. 5 Isle St, confirmed correct at three faces, has a face
# with 10.6% of its points more than 0.5 m off plane; 7 Anderson Heights,
# confirmed wrong, has 10.0% and 10.2%. Any threshold that cuts
# one cuts the other. Nor does WHERE those points sit help -- on both roofs they
# cluster within half a metre of a facet edge, which is just bleed from the
# neighbouring plane.


def _fit_plane(pts):
    """Least-squares plane through points, as (a, b, c) with z = ax + by + c.

    Solved about the points' own centroid, then shifted back. Solving on raw
    NZTM coordinates -- x near 1.2 million, y near 5 million, against a column
    of ones -- is a condition number around 1e6, and it does not merely lose a
    little precision: it silently returns planes that do not fit their own
    points. Two faces of 5 Isle St measured 0.1 degrees apart with a 0.00 m step
    at their join, and the plane fitted to their union scored 16% on-plane
    against 99% for each of them separately, which blocked a merge that should
    obviously have happened and left that roof at 5 faces where it has 3."""
    x0, y0 = pts[:, 0].mean(), pts[:, 1].mean()
    A = np.column_stack([pts[:, 0] - x0, pts[:, 1] - y0, np.ones(len(pts))])
    coef, *_ = np.linalg.lstsq(A, pts[:, 2], rcond=None)
    a, b = float(coef[0]), float(coef[1])
    return a, b, float(coef[2]) - a * x0 - b * y0


def _fit_plane_robust(pts, iterations=6):
    """Trimmed fit, so a chimney or a parapet does not tilt the whole face."""
    keep = np.ones(len(pts), bool)
    plane = _fit_plane(pts)
    for _ in range(iterations):
        r = pts[:, 2] - (plane[0] * pts[:, 0] + plane[1] * pts[:, 1] + plane[2])
        nxt = np.abs(r - np.median(r[keep])) < INLIER_BAND_M * 2
        if nxt.sum() < MIN_POINTS or (nxt == keep).all():
            break
        keep = nxt
        plane = _fit_plane(pts[keep])
    return plane


def _inlier_fraction(pts, plane):
    r = pts[:, 2] - (plane[0] * pts[:, 0] + plane[1] * pts[:, 1] + plane[2])
    return float((np.abs(r - np.median(r)) < INLIER_BAND_M).mean())


def _usable(poly, setback=None):
    """Area left after the ridge setback -- what panel packing actually gets."""
    setback = PARTITION_SETBACK_M if setback is None else setback
    if poly.is_empty:
        return 0.0
    try:
        return float(poly.buffer(-setback).area)
    except Exception:
        return 0.0


def _points_in(poly, pts):
    if len(pts) == 0:
        return pts
    return pts[shapely.contains_xy(poly, pts[:, 0], pts[:, 1])]


def _edge_directions(poly):
    """Distinct directions of the footprint's own edges, longest first.

    Roofs are built on walls: ridges and hips run parallel or perpendicular to
    the outline far more often than not, and the LINZ outline is surveyed, so
    these angles are exact in a way nothing recovered from the point cloud is."""
    coords = np.asarray(poly.exterior.coords)
    segs = coords[1:] - coords[:-1]
    lens = np.hypot(segs[:, 0], segs[:, 1])
    angs = np.degrees(np.arctan2(segs[:, 1], segs[:, 0])) % 180.0
    order = np.argsort(-lens)
    out = []
    for i in order:
        if lens[i] < 1.0:
            continue
        a = angs[i]
        if all(min(abs(a - b), 180 - abs(a - b)) > ANGLE_TOL_DEG for b in out):
            out.append(float(a))
    # Every wall direction, its perpendicular, and its two diagonals. The
    # diagonals are not decoration: a hip BISECTS the corner between two walls,
    # so a hip line runs at 45 degrees to both, and without them the partition
    # cannot cut a hip roof at all -- it is forced to approximate one with
    # rectangular cuts, which is why 5 Isle St stalled at two faces and 45%
    # on-plane. A 45-degree mitre joint is common roof geometry.
    perp = [(a + 90.0) % 180.0 for a in out]
    diag = [(a + 45.0) % 180.0 for a in out] + [(a + 135.0) % 180.0 for a in out]
    seen, uniq = [], []
    for a in out + perp + diag:
        if all(min(abs(a - b), 180 - abs(a - b)) > ANGLE_TOL_DEG for b in seen):
            seen.append(a)
            uniq.append(a)
    return uniq


def _cut(poly, angle_deg, offset):
    """Split a polygon with an infinite line at this angle and offset."""
    theta = np.radians(angle_deg)
    d = np.array([np.cos(theta), np.sin(theta)])
    n = np.array([-d[1], d[0]])
    c = np.array(poly.centroid.coords[0])
    span = max(poly.bounds[2] - poly.bounds[0], poly.bounds[3] - poly.bounds[1]) * 2 + 10
    mid = c + n * offset
    line = LineString([mid - d * span, mid + d * span])
    try:
        parts = list(shapely_split(poly, line).geoms)
    except Exception:
        return []
    return [p for p in parts if isinstance(p, Polygon) and p.area >= MIN_PIECE_M2]


def _score(poly, pts):
    """Area-weighted inlier fraction if this region were one facet."""
    sub = _points_in(poly, pts)
    if len(sub) < MIN_POINTS:
        return None, 0.0
    plane = _fit_plane_robust(sub)
    return plane, _inlier_fraction(sub, plane)


# A fold is not "many points off the plane" -- that test does not work, and the
# numbers say so plainly. Measured on two roofs with opposite verdicts:
#
#   7 Anderson (WRONG)          faces at 11.0% and 8.0% of points beyond 0.5 m
#   5 Isle     (RIGHT)          faces at  2.3%, 6.6% and 10.6% beyond 0.5 m
#
# 5 Isle's correct 44 m2 face has a LONGER tail than Anderson's wrong 64.6 m2
# face. Any threshold that cuts one shatters the other, which is why the earlier
# fold-fraction and fold-location attempts were abandoned.
#
# What separates them is the SHAPE of the off-plane set. On 5 Isle the low
# points are rooftop clutter: compact blobs scattered over a surface that really
# is one plane. On 7 Anderson they are the valleys between three pyramid hips --
# long connected bands running clean across the face. So the test is spatial: a
# fold is a connected low region that is elongated AND spans most of the way
# across the region it sits in. Clutter is neither.
FOLD_DROP_M = 0.40           # how far below the plane counts as "low"
FOLD_CELL_M = 0.6            # grid the low points onto this, then label components
FOLD_MIN_CELLS = 8           # smaller connected sets are clutter, not structure
FOLD_MIN_SPAN_SHARE = 0.55   # a fold runs most of the way across the face
FOLD_MIN_ELONGATION = 2.2    # and it is long and thin, not a blob


def _fold_evidence(poly, pts, plane):
    """True when the points below `plane` form a band crossing `poly`.

    Detects a roof that drops through the middle of a face -- the 7 Anderson
    Heights defect -- while ignoring the scattered
    low clutter that sits on a face which really is one plane."""
    sub = _points_in(poly, pts)
    if len(sub) < MIN_POINTS:
        return False
    r = sub[:, 2] - (plane[0] * sub[:, 0] + plane[1] * sub[:, 1] + plane[2])
    r = r - np.median(r)
    low = sub[r < -FOLD_DROP_M]
    if len(low) < FOLD_MIN_CELLS:
        return False
    try:
        from scipy import ndimage
    except Exception:
        return False
    minx, miny, maxx, maxy = poly.bounds
    nx = max(2, int(np.ceil((maxx - minx) / FOLD_CELL_M)))
    ny = max(2, int(np.ceil((maxy - miny) / FOLD_CELL_M)))
    if nx * ny > 400000:
        return False
    grid = np.zeros((ny, nx), dtype=bool)
    ix = np.clip(((low[:, 0] - minx) / FOLD_CELL_M).astype(int), 0, nx - 1)
    iy = np.clip(((low[:, 1] - miny) / FOLD_CELL_M).astype(int), 0, ny - 1)
    grid[iy, ix] = True
    labels, n = ndimage.label(grid, structure=np.ones((3, 3), dtype=int))
    if n == 0:
        return False
    face_span = max(maxx - minx, maxy - miny)
    for lab in range(1, n + 1):
        ys, xs = np.nonzero(labels == lab)
        if len(xs) < FOLD_MIN_CELLS:
            continue
        px = xs * FOLD_CELL_M + minx
        py = ys * FOLD_CELL_M + miny
        c = np.column_stack([px - px.mean(), py - py.mean()])
        # principal axes of the connected low region
        try:
            axes = np.linalg.svd(c, full_matrices=False)[2]
        except Exception:
            continue
        proj = c @ axes.T
        length = proj[:, 0].max() - proj[:, 0].min()
        width = proj[:, 1].max() - proj[:, 1].min() if proj.shape[1] > 1 else 0.0
        if length < FOLD_MIN_SPAN_SHARE * face_span:
            continue
        if width > 1e-6 and length / max(width, FOLD_CELL_M) < FOLD_MIN_ELONGATION:
            continue
        return True
    return False


# Where the ridge drops, the roof changes section, and that is a cut whether or
# not the plane fit asks for one.
#
# On 7 Anderson Heights two panel planes were placed overlapping a ridge
# where the roof drops in the middle: the dip was not accounted for.
# Measured on that roof, taking the 97th percentile of height in 1 m slices
# along the building's long axis: the ridge sits at 381.42 m from -8.5 to -3.5,
# falls to 380.26 m at -0.5, and returns to 381.47 m from 1.5 to 6.5. A 1.16 m
# dip in the middle of a 21 m roof, with the north slope running straight over
# it as one 64.6 m2 face.
#
# The plane fit cannot see this on its own: both sections have the same pitch
# and aspect, so a plane through both scores well. The signal is in the upper
# envelope, not the residuals, which is why it is measured separately here and
# offered to _best_cut as an extra candidate position rather than left to the
# generic sweep to stumble on.
RIDGE_SLICE_M = 1.0          # along-axis resolution of the ridge profile
RIDGE_TOP_PCT = 97           # what counts as "the ridge" inside one slice
RIDGE_DROP_M = 0.45          # a dip this far below both neighbouring peaks is a section change
RIDGE_EDGE_MARGIN_M = 2.0    # ignore dips at the very ends, those are the hips


def _ridge_drop_offsets(poly, pts):
    """Positions along the region's long axis where the ridge line dips.

    Returns (angle_deg, [offsets]) for a cut perpendicular to that axis, in the
    same convention _cut uses, or None when the ridge is continuous."""
    sub = _points_in(poly, pts)
    if len(sub) < 4 * MIN_POINTS:
        return None
    try:
        rect = np.asarray(poly.minimum_rotated_rectangle.exterior.coords)
    except Exception:
        return None
    e = rect[1:] - rect[:-1]
    L = np.hypot(e[:, 0], e[:, 1])
    if len(L) == 0 or L.max() <= 0:
        return None
    i = int(np.argmax(L))
    u = e[i] / L[i]
    c = np.array(poly.centroid.coords[0])
    s = (sub[:, :2] - c) @ u
    lo, hi = s.min(), s.max()
    if hi - lo < 4 * RIDGE_SLICE_M:
        return None
    edges = np.arange(lo, hi + 1e-9, RIDGE_SLICE_M)
    mids, tops = [], []
    for k in range(len(edges) - 1):
        m = (s >= edges[k]) & (s < edges[k + 1])
        if m.sum() < 5:
            continue
        mids.append(0.5 * (edges[k] + edges[k + 1]))
        tops.append(np.percentile(sub[m, 2], RIDGE_TOP_PCT))
    if len(tops) < 5:
        return None
    mids, tops = np.array(mids), np.array(tops)
    offsets = []
    for k in range(1, len(tops) - 1):
        if mids[k] - lo < RIDGE_EDGE_MARGIN_M or hi - mids[k] < RIDGE_EDGE_MARGIN_M:
            continue
        if tops[k] > tops[k - 1] or tops[k] > tops[k + 1]:
            continue                      # not a local minimum
        drop = min(tops[:k].max() - tops[k], tops[k + 1:].max() - tops[k])
        if drop >= RIDGE_DROP_M:
            offsets.append(float(mids[k]))
    if not offsets:
        return None
    # _cut takes the direction of the LINE; perpendicular to the long axis
    angle = float((np.degrees(np.arctan2(u[1], u[0])) + 90.0) % 180.0)
    n = np.array([-np.sin(np.radians(angle)), np.cos(np.radians(angle))])
    # express each offset in the same projection _cut uses
    return angle, [float(o * (u @ n)) for o in offsets]


def _best_cut(poly, pts, base_score):
    """The straight line that best explains this region as two planes."""
    if _cut_deadline[0] is not None and time.process_time() > _cut_deadline[0]:
        return None
    best = None

    # A ridge drop is a section change and gets its own candidate positions,
    # scored the same way as every other cut so it only wins if it explains the
    # surface better.
    rd = _ridge_drop_offsets(poly, pts)
    if rd is not None:
        angle, offs = rd
        for off in offs:
            parts = _cut(poly, angle, off)
            if len(parts) < 2:
                continue
            tot = num = 0.0
            worst = 1.0
            ok = True
            for part in parts:
                pl, sc = _score(part, pts)
                if pl is None:
                    ok = False
                    break
                num += sc * part.area
                tot += part.area
                worst = min(worst, sc)
            if ok and tot > 0:
                combined = num / tot
                if combined > base_score + MIN_SPLIT_GAIN and (best is None or combined > best[0]):
                    best = (combined, parts, worst)

    for angle in _edge_directions(poly):
        theta = np.radians(angle)
        n = np.array([-np.sin(theta), np.cos(theta)])
        coords = np.asarray(poly.exterior.coords)
        c = np.array(poly.centroid.coords[0])
        proj = (coords - c) @ n
        lo, hi = proj.min(), proj.max()
        if hi - lo < 2 * OFFSET_STEP_M:
            continue
        step = max(OFFSET_STEP_M, (hi - lo) / MAX_OFFSETS_PER_DIRECTION)
        for off in np.arange(lo + step, hi - step + 1e-9, step):
            _cut_evals[0] += 1
            if _cut_deadline[0] is not None and time.process_time() > _cut_deadline[0]:
                CUT_BUDGET_EXHAUSTED[0] += 1
                return best
            parts = _cut(poly, angle, float(off))
            if len(parts) < 2:
                continue
            tot = num = 0.0
            ok = True
            for part in parts:
                pl, sc = _score(part, pts)
                if pl is None:
                    ok = False
                    break
                num += sc * part.area
                tot += part.area
            if not ok or tot <= 0:
                continue
            combined = num / tot
            if combined > base_score + MIN_SPLIT_GAIN and (best is None or combined > best[0]):
                best = (combined, parts)
    return best


def _cut_on_line(poly, A, B, C, cx, cy):
    """Split a polygon along A(x-cx) + B(y-cy) + C = 0.

    Everything is in coordinates local to (cx, cy), and both reasons are
    NZTM's fault. Anchoring the line at its closest point to the ORIGIN puts
    that anchor about 5,000 km away, so a line segment a few tens of metres
    long never reaches the building and the split silently does nothing. And
    a plane's intercept is its height at x=0, y=0, which for NZTM is an
    astronomical number, so differencing two of them loses all the precision
    that matters. Both vanish once the origin is the polygon itself."""
    n = np.hypot(A, B)
    if n < 1e-9:
        return []
    d = np.array([-B, A]) / n              # direction along the line
    origin = np.array([cx, cy])
    pt0 = origin - np.array([A, B]) * (C / (n ** 2))   # nearest point ON the line
    span = max(poly.bounds[2] - poly.bounds[0], poly.bounds[3] - poly.bounds[1]) * 2 + 10
    line = LineString([pt0 - d * span, pt0 + d * span])
    try:
        parts = list(shapely_split(poly, line).geoms)
    except Exception:
        return []
    return [q for q in parts if isinstance(q, Polygon) and q.area >= MIN_PIECE_M2]


def _refine_cut(poly, pts, parts):
    """Move a swept cut onto the two planes' own intersection line.

    The sweep can only place a cut to within OFFSET_STEP_M, and a ridge that
    lands even 25 cm off leaves a strip of the WRONG plane on both sides of it,
    which is what kept fit lagging while structure was already correct. But two
    planes that meet do so along an exact line -- that line IS the ridge or hip,
    and it is available in closed form. Solve for it and re-cut there.

    Only for planes that actually intersect: near-parallel faces at different
    heights are a step, not a fold, and their intersection is meaningless or
    infinitely far away, so the swept cut stands."""
    if len(parts) != 2:
        return parts
    pa, _ = _score(parts[0], pts)
    pb, _ = _score(parts[1], pts)
    if pa is None or pb is None:
        return parts
    cx, cy = poly.centroid.x, poly.centroid.y
    A, B = pa[0] - pb[0], pa[1] - pb[1]
    # height gap between the two planes AT the centroid, not at x=0,y=0
    C = ((pa[0] * cx + pa[1] * cy + pa[2]) - (pb[0] * cx + pb[1] * cy + pb[2]))
    if np.hypot(A, B) < 1e-3:
        return parts        # parallel: a step in height, keep the swept cut
    refined = _cut_on_line(poly, A, B, C, cx, cy)
    if len(refined) < 2:
        return parts

    def weighted(ps):
        tot = num = 0.0
        for q in ps:
            _, sc = _score(q, pts)
            num += sc * q.area
            tot += q.area
        return num / tot if tot else 0.0

    return refined if weighted(refined) > weighted(parts) else parts


# Big planes first; their intersections ARE the roof lines.
#
# An edge detector draws a maze over a simple roof. Roofs are made of big
# flat planes, generally large, that connect smoothly at angled
# edges most of the time."
#
# That inverts the problem. Hunting edges in imagery and inferring planes from
# them is backwards and fails in both directions -- texture produces lines that
# are not roof features, and a real ridge that is a soft intensity step
# produces no line at all. But two planes that meet do so along their exact
# analytic intersection: no detection, no threshold, no false positives. Find
# the planes and the ridges, hips and valleys come out for free, straight and
# in the right place.
#
# The size prior is the whole point and is what previous attempts at this got
# wrong -- roof_reconstruct fitted planes to whatever the points supported and
# shattered roofs into strips. A plane has to be BIG to exist at all here.
PLANE_MIN_AREA_M2 = 12.0        # a face smaller than ~6 panels is not a roof plane
PLANE_MIN_FOOTPRINT_SHARE = 0.04
PLANE_TOL_M = 0.20              # a point this close to a plane is on it
PLANE_MAX = 10                  # real roofs are simple; past this it is not planes any more
PLANE_RANSAC_ITERS = 250
PLANE_SAMPLE_RADIUS_M = 6.0     # 3-point samples drawn locally, or a plane gets fitted
# through three points on three different faces and describes nothing


def _detect_large_planes(pts, footprint, rng, max_planes=None):
    """Greedy RANSAC for the few LARGE planes a roof is actually made of.

    Take the best-supported plane, remove its points, repeat -- stopping as soon
    as the best remaining plane is too small to be a roof face rather than
    grinding on until every leftover point has one."""
    if len(pts) < MIN_POINTS:
        return []
    min_area = max(PLANE_MIN_AREA_M2, PLANE_MIN_FOOTPRINT_SHARE * footprint.area)
    pt_area = footprint.area / max(len(pts), 1)      # plan area each point stands for
    min_pts = max(MIN_POINTS, int(min_area / max(pt_area, 1e-9)))

    remaining = pts
    planes = []
    tree = None
    cap = PLANE_MAX if max_planes is None else max_planes
    while len(planes) < cap and len(remaining) >= min_pts:
        from scipy.spatial import cKDTree
        tree = cKDTree(remaining[:, :2])
        best, best_n = None, 0
        for _ in range(PLANE_RANSAC_ITERS):
            i = rng.integers(len(remaining))
            near = tree.query_ball_point(remaining[i, :2], PLANE_SAMPLE_RADIUS_M)
            if len(near) < 3:
                continue
            pick = rng.choice(near, size=3, replace=False)
            trio = remaining[pick]
            v1, v2 = trio[1] - trio[0], trio[2] - trio[0]
            nrm = np.cross(v1, v2)
            if abs(nrm[2]) < 1e-6:
                continue
            a, b = -nrm[0] / nrm[2], -nrm[1] / nrm[2]
            c = trio[0, 2] - a * trio[0, 0] - b * trio[0, 1]
            n = int((np.abs(remaining[:, 2] - (a * remaining[:, 0] + b * remaining[:, 1] + c))
                     < PLANE_TOL_M).sum())
            if n > best_n:
                best, best_n = (a, b, c), n
        if best is None or best_n < min_pts:
            break
        inl = np.abs(remaining[:, 2] - (best[0] * remaining[:, 0]
                                        + best[1] * remaining[:, 1] + best[2])) < PLANE_TOL_M
        planes.append(_fit_plane_robust(remaining[inl]))
        remaining = remaining[~inl]
    return planes


def _plane_intersection_cuts(planes, poly):
    """(angle, offset) for every pair of planes that meet, in _cut's convention.

    This is the replacement for detecting roof lines. Two planes intersect along
    one exact line; near-parallel pairs are skipped because their intersection is
    meaningless or far away -- those are steps in height, not folds."""
    cx, cy = poly.centroid.x, poly.centroid.y
    out = []
    for i in range(len(planes)):
        for j in range(i + 1, len(planes)):
            pa, pb = planes[i], planes[j]
            A, B = pa[0] - pb[0], pa[1] - pb[1]
            if np.hypot(A, B) < 1e-3:
                continue
            C = ((pa[0] * cx + pa[1] * cy + pa[2]) - (pb[0] * cx + pb[1] * cy + pb[2]))
            n = np.hypot(A, B)
            ang = float((np.degrees(np.arctan2(A, -B))) % 180.0)   # line dir _|_ to (A,B)
            off = float(-C / n)
            out.append((ang, off))
    return out


def _partition(poly, pts, depth=0, budget=None):
    if budget is None:
        budget = [MAX_FACES]
    plane, score = _score(poly, pts)
    if plane is None:
        return []

    # Acceptance needs BOTH: enough points near the plane, and no fold.
    #
    # The inlier fraction alone is blind to how far the outliers are, and that
    # is not a small blind spot. 7 Anderson Heights had a 73 m2 face scoring
    # exactly 85% -- the acceptance bar -- while 10% of its points sat more than
    # half a metre off it and nearly 5% over a metre. That is a roof dropping
    # through the middle of a face, and it was accepted as one plane, so the
    # recursion never even asked whether a cut would help, and two panel
    # planes were placed overlapping the ridge where the roof drops.
    #
    # A tail that far out is structure, not noise. Roughness raises the count of
    # points just outside the band; a fold puts them metres away.
    # A region is one face only if it fits a plane, does not fold, and its ridge
    # does not drop. The ridge test has to sit in ACCEPTANCE and not merely in
    # the cut search: two sections of the same pitch and aspect fit a common
    # plane well, so 7 Anderson's north slope scored 86.8% -- above the bar --
    # and was accepted whole before any cut was considered, running straight
    # over a 1.16 m dip.
    folded = _fold_evidence(poly, pts, plane)
    drops = _ridge_drop_offsets(poly, pts) if not folded else None
    if ((score >= ACCEPT_INLIER and not folded and drops is None) or depth >= MAX_DEPTH
            or poly.area < 2 * MIN_FACET_M2 or budget[0] <= 1):
        return [(poly, plane)]
    best = _best_cut(poly, pts, score)
    if best is None:
        return [(poly, plane)]      # no straight cut explains it better -- keep it whole
    parts = _refine_cut(poly, pts, best[1])

    # A cut has to earn the panel area it costs. Every facet is eroded by the
    # ridge setback before packing, so cutting one face into two loses a strip
    # down the middle permanently -- and a fit improvement that cannot be used,
    # because the pieces are too narrow to rack panels on, is worth nothing.
    #
    # Without this the recursion buys fit indefinitely: measured on random pilot
    # roofs it produced 20 facets on a 255 m2 house and 25 on 333 m2, about
    # 13 m2 each. Real houses have two to eight planes, large and blocky,
    # with few vertices.
    gain = max(0.0, best[0] - score)
    cost = _usable(poly) - sum(_usable(q) for q in parts)
    # The setback economics protect a face that is already a plane from being
    # fragmented for a fit gain too small to be worth the racking area. They must
    # not protect a FOLDED face: there the cut is not buying fit, it is putting
    # the ridge where the roof actually bends, and paying a setback strip for
    # that is the whole point. Measured on 7 Anderson Heights: the fold test
    # correctly flagged its 75.4 m2 face, the recursion asked for a cut, and this
    # veto threw it away (cost 2.81 m2 against a 1.97 m2 threshold) -- so the
    # fold detection changed nothing until the veto learned to stand down.
    if not folded and drops is None and cost > SETBACK_COST_PER_FIT * gain * max(_usable(poly), 1e-9):
        return [(poly, plane)]
    out = []
    budget[0] -= 1          # this cut spends one face from the building's budget
    for part in parts:
        out.extend(_partition(part, _points_in(part, pts), depth + 1, budget))
    return out or [(poly, plane)]


def _slope_aspect(plane):
    a, b, _ = plane
    slope = float(np.degrees(np.arctan(np.hypot(a, b))))
    aspect = float((np.degrees(np.arctan2(-a, -b)) + 360.0) % 360.0)
    return slope, aspect


def _plane_angle(p, q):
    na = np.array([-p[0], -p[1], 1.0]); na /= np.linalg.norm(na)
    nb = np.array([-q[0], -q[1], 1.0]); nb /= np.linalg.norm(nb)
    return float(np.degrees(np.arccos(np.clip(abs(na @ nb), -1.0, 1.0))))


BRIDGE_MAX_STEP_M = 0.10

# Two faces produced by the same cut can end up separated by a hairline crack --
# coincident edges whose vertices differ in the last bits of floating point. GEOS
# reports them as touching but unions them into a MultiPolygon, and the bridge
# merge then refuses the pair because "the union is not a Polygon".
#
# That is not a corner case here, it is the 7 Anderson Heights defect: the
# hip-end triangles are triangles, and were being cut into two smaller
# triangles by continuing the main ridgeline through
# them." Both hip ends were split by the ridge cut and both pairs were perfectly
# coplanar -- aspects 315.2/315.2 and 138.4/136.5, angle well inside the bridge
# limit, sharing an 8.4 m and a 6.7 m edge at zero distance -- and both merges
# were thrown away over a sliver of about 0.02 m2.
#
# Snapping one face's vertices onto the other's within a centimetre closes the
# crack without moving any edge a distance anyone could see.
MERGE_SNAP_M = 0.01

# Two pieces of ONE plane, separated only because something was carved between
# them, are one face. The bridge merge normally has to earn back racking area --
# gain > 0.5 m2 of setback -- which is the right bar when the question is
# whether a genuine seam is worth keeping. It is the wrong bar when there is no
# seam at all.
#
# 7 Anderson Heights: the north slope is notched by the recessed feature in the
# middle of the roof, so its two parts meet along a neck of just 0.77 m. Merging
# them recovers 0.008 m2 of setback and the economics threw it away, leaving 9
# faces where the markup has 8. They are 0.78 degrees apart with a 0.001 m step at
# the join, and merged they fit 93.7% -- better than the 86.8% a single
# uncut face scored. That is one plane by every measure that matters.
SAME_PLANE_ANGLE_DEG = 1.5   # tighter than the bridge angle: this is "identical", not "close"
SAME_PLANE_STEP_M = 0.05


def _step_at_join(pa, pb, poly_a, poly_b):
    """Height gap between two planes WHERE THEY ADJOIN.

    Without this the merge is wrong in a way an angle test cannot see: two
    parallel faces at different levels have identical normals, so they read as
    0 degrees apart and get merged straight across a step. That is exactly what
    happened here -- the recursion built 5 correct faces on 5 Isle St at 87-99%
    on-plane and the merge collapsed them to 2 at 45%. Third time this same bug
    has appeared in this codebase; comparing planes at their shared boundary
    rather than comparing normals is the only thing that catches it."""
    shared = poly_a.buffer(0.3).intersection(poly_b.buffer(0.3))
    if shared.is_empty:
        return float("inf")
    c = shared.centroid
    za = pa[0] * c.x + pa[1] * c.y + pa[2]
    zb = pb[0] * c.x + pb[1] * c.y + pb[2]
    return abs(float(za - zb))


def _merge_bridgeable(faces, pts):
    """Undo cuts a panel could lie across.

    A cut that buys fit but not enough to stop a panel spanning it costs the
    ridge setback on both sides for nothing. 5 degrees over a 1.7 m panel is a
    15 cm rise, past what a rigid frame bridges."""
    # Pair testing is memoised. The loop used to restart the whole O(N^2) sweep
    # after every successful merge, re-running _points_in and _fit_plane_robust
    # on pairs it had already rejected -- O(N^3) in the expensive geometry ops.
    # It still terminated (a merge always drops the face count by one), so it
    # never showed up as a hang in testing, just as a build that sat at 100% CPU
    # on one worker. On a Frankton Flats roof at the 60-face cap that is ~100k
    # plane fits and about an hour on one building, which is what stalled the
    # 28 Aug rebuild twice. A rejected pair can only become viable again if one
    # of its two faces is itself replaced by a merge, so remembering rejections
    # by face identity is exact -- this is a speedup, not an approximation.
    faces = list(faces)
    uid = {id(f): n for n, f in enumerate(faces)}
    next_uid = len(faces)
    rejected = set()
    changed = True
    while changed and len(faces) > 1:
        changed = False
        for i in range(len(faces)):
            for j in range(i + 1, len(faces)):
                key = (uid[id(faces[i])], uid[id(faces[j])])
                if key in rejected:
                    continue
                (pi, li), (pj, lj) = faces[i], faces[j]
                if not pi.buffer(0.25).intersects(pj):
                    rejected.add(key)
                    continue
                if _plane_angle(li, lj) > 5.0:
                    rejected.add(key)
                    continue
                if _step_at_join(li, lj, pi, pj) > BRIDGE_MAX_STEP_M:
                    rejected.add(key)
                    continue
                u = unary_union([pi, snap(pj, pi, MERGE_SNAP_M)])
                if u.geom_type != "Polygon":
                    closed = unary_union([pi.buffer(MERGE_SNAP_M),
                                          pj.buffer(MERGE_SNAP_M)]).buffer(-MERGE_SNAP_M)
                    if closed.geom_type != "Polygon":
                        rejected.add(key)
                        continue
                    u = Polygon(closed.exterior, [r for r in closed.interiors])
                gain = (u.buffer(-PARTITION_SETBACK_M).area
                        - pi.buffer(-PARTITION_SETBACK_M).area
                        - pj.buffer(-PARTITION_SETBACK_M).area)
                same_plane = (_plane_angle(li, lj) <= SAME_PLANE_ANGLE_DEG
                              and _step_at_join(li, lj, pi, pj) <= SAME_PLANE_STEP_M)
                if gain <= 0.5 and not same_plane:
                    rejected.add(key)
                    continue
                sub = _points_in(u, pts)
                if len(sub) < MIN_POINTS:
                    rejected.add(key)
                    continue
                pl = _fit_plane_robust(sub)
                # The merged face has to still be a plane. Angle, step and area
                # gain all pass on faces that individually fit well but whose
                # UNION does not -- a gentle curve is exactly that, every
                # adjacent pair within the bridge angle while the whole sweep is
                # not one plane. Unchecked, this built a 138 m2 face on 1/5
                # Sydney St sitting at 15% on-plane out of pieces that were
                # each fine, and nothing downstream could recover from it
                # because the recursion had already finished.
                merged_fit = _inlier_fraction(sub, pl)
                worst_before = min(_inlier_fraction(_points_in(pi, pts), li),
                                   _inlier_fraction(_points_in(pj, pts), lj))
                # A merge made on "same plane" grounds rather than on recovered
                # area has to clear the acceptance bar outright -- it is claiming
                # the two pieces ARE one plane, so the union must look like one.
                bar = ACCEPT_INLIER if (gain <= 0.5) else min(ACCEPT_INLIER, worst_before - 0.02)
                if merged_fit < bar:
                    rejected.add(key)
                    continue
                merged = (u, pl)
                faces = [f for k, f in enumerate(faces) if k not in (i, j)] + [merged]
                uid[id(merged)] = next_uid
                next_uid += 1
                changed = True
                break
            if changed:
                break
    return faces


# How many planes a roof actually has: a house between 1 and 10, a big hotel
# or business roof between 1 and 30. That is the prior this whole module was
# missing, and it is why a 93%-on-plane score could sit on a roof that was
# clearly wrong: fit says nothing about whether a shape looks like a roof.
PLANES_TYPICAL_MAX = 10          # a house
PLANES_LARGE_MAX = 30            # a hotel or a large commercial roof
PLANES_LARGE_ROOF_M2 = 600.0     # above this footprint, allow the higher count
MAX_INTERSECTION_LINES = 24      # cutting by every pair explodes; keep the best


def top_surface(pts, cell_m=0.5, drop_m=0.5):
    """Keep only the points on the TOP surface of each plan cell. Under an eave
    of a multi-level building LiDAR records both the upper roof edge and the
    lower roof beneath it at the same plan location; a roof model is a function
    z(x, y), so those lower returns are unexplainable by construction and they
    poison plane fits, region labels and any points-explained metric alike
    (measured on #5119630: two roof levels, 29% of points on the lower one,
    facet planes fitted through the mixture explaining 0% of their polygons).
    The lower level's EXPOSED area keeps its points -- there it IS the top."""
    if len(pts) == 0:
        return pts
    ix = np.floor(pts[:, 0] / cell_m).astype(np.int64)
    iy = np.floor(pts[:, 1] / cell_m).astype(np.int64)
    key = (ix - ix.min()) * (iy.max() - iy.min() + 1) + (iy - iy.min())
    order = np.argsort(key, kind="stable")
    ks, zs = key[order], pts[order, 2]
    top = np.empty(len(pts))
    start = 0
    for end in np.append(np.where(np.diff(ks) != 0)[0] + 1, len(ks)):
        top[start:end] = zs[start:end].max()
        start = end
    keep_sorted = zs > top - drop_m
    keep = np.zeros(len(pts), dtype=bool)
    keep[order] = keep_sorted
    return pts[keep]


def dedupe_planes(planes, footprint, angle_tol_deg=5.0, height_tol_m=0.35):
    """Drop planes that are the same surface fitted twice. Two genuinely
    separate faces sharing pitch AND aspect AND height are coplanar -- one
    plane serves both, and the adjacency merge separates their polygons."""
    cx, cy = footprint.centroid.x, footprint.centroid.y
    kept = []
    for p in planes:
        dup = False
        for q in kept:
            na = np.array([-p[0], -p[1], 1.0]); na /= np.linalg.norm(na)
            nb = np.array([-q[0], -q[1], 1.0]); nb /= np.linalg.norm(nb)
            ang = np.degrees(np.arccos(np.clip(na @ nb, -1, 1)))
            dz = abs((p[0] * cx + p[1] * cy + p[2]) - (q[0] * cx + q[1] * cy + q[2]))
            if ang < angle_tol_deg and dz < height_tol_m:
                dup = True
                break
        if not dup:
            kept.append(p)
    return kept


def explained_fraction(faces, pts, band=INLIER_BAND_M):
    """Share of ALL the building's points a facet set explains: a point counts
    when it falls inside some facet whose plane passes within `band` of it.
    One number rewarding both coverage and correctness -- a wedge spanning two
    real faces covers its points but explains few of them, and a correct facet
    set that abandons half the roof explains at most the half it kept."""
    if len(pts) == 0:
        return 0.0
    ok = np.zeros(len(pts), dtype=bool)
    for f in faces:
        poly = f["geometry"] if isinstance(f, dict) else f[0]
        a, b, c = ((f["plane_a"], f["plane_b"], f["plane_c"]) if isinstance(f, dict)
                   else f[1])
        m = shapely.contains_xy(poly, pts[:, 0], pts[:, 1])
        if not m.any():
            continue
        resid = np.abs(pts[m, 2] - (a * pts[m, 0] + b * pts[m, 1] + c))
        idx = np.where(m)[0]
        ok[idx[resid < band]] = True
    return float(ok.mean())


def _reflex_corner_cuts(poly):
    """Cut lines through each REFLEX (concave) footprint corner, along both
    adjoining wall directions. An L- or U-shaped building's wings meet at its
    reflex corners; the roof sections separate along lines through them. The
    plane-intersection cuts cannot draw these boundaries when the two wings'
    faces are near-parallel (same pitch, different wing) -- parallel planes
    have no intersection line -- and that is exactly the geometry of every
    multi-wing hip roof, so without these the cells straddle wings and whole
    faces get merged across the valley (measured on #5119630: two 52 m2
    cross-wing sheets, explained fraction 0.51)."""
    ring = np.asarray(poly.exterior.coords[:-1])
    if len(ring) < 4:
        return []
    # shoelace: positive = CCW
    area2 = float(np.sum(ring[:, 0] * np.roll(ring[:, 1], -1)
                         - np.roll(ring[:, 0], -1) * ring[:, 1]))
    ccw = area2 > 0
    c = np.array(poly.centroid.coords[0])
    out = []
    n_pts = len(ring)
    for i in range(n_pts):
        p0, p1, p2 = ring[i - 1], ring[i], ring[(i + 1) % n_pts]
        v1, v2 = p1 - p0, p2 - p1
        if np.hypot(*v1) < 0.5 or np.hypot(*v2) < 0.5:
            continue        # survey jitter, not a wall corner
        cross = v1[0] * v2[1] - v1[1] * v2[0]
        if (cross < 0) != ccw:
            continue        # convex corner in this orientation
        for v in (v1, v2):
            ang = float(np.degrees(np.arctan2(v[1], v[0])) % 180.0)
            theta = np.radians(ang)
            nrm = np.array([-np.sin(theta), np.cos(theta)])
            out.append((ang, float((p1 - c) @ nrm)))
    return out


def partition_with_labels(building_id, footprint, pts, labels, planes):
    """Arrangement partition where the ASSIGNMENT comes from labelled points
    (region growing), not residual voting. Residual voting cannot tell two
    coplanar faces on different wings apart -- same plane, same residuals --
    and unary_union then welds them into one cross-valley sheet. Labels are
    contiguous regions by construction, so a wing can only ever claim cells
    its own points sit in.

    labels: per-point region id, -1 for unassigned. planes: (a,b,c) per id."""
    inside_mask_pts = pts
    inside = _points_in(footprint, inside_mask_pts)
    if len(inside) < MIN_POINTS:
        return []
    # labels must correspond to pts row-for-row; recompute the footprint mask
    # the same way _points_in does so they stay aligned.
    m = shapely.contains_xy(footprint, pts[:, 0], pts[:, 1])
    pin, lin = pts[m], np.asarray(labels)[m]

    # Cut lines: every pair of genuinely DISTINCT planes (their intersection is
    # a ridge/hip/valley) plus the wing separations at reflex corners.
    uniq = dedupe_planes(list(planes), footprint)
    cuts = (_plane_intersection_cuts(uniq, footprint)[:MAX_INTERSECTION_LINES]
            + _reflex_corner_cuts(footprint))
    cells = [footprint]
    for ang, off in cuts:
        nxt = []
        for c in cells:
            parts = _cut(c, ang, off)
            nxt.extend(parts if len(parts) >= 2 else [c])
        cells = nxt
        if len(cells) > 200:
            break

    labelled = []
    for cell in cells:
        if cell.area < MIN_PIECE_M2:
            continue
        mm = shapely.contains_xy(cell, pin[:, 0], pin[:, 1])
        votes = lin[mm]
        votes = votes[votes >= 0]
        if len(votes) < 4:
            labelled.append((cell, None))
            continue
        ids, counts = np.unique(votes, return_counts=True)
        labelled.append((cell, int(ids[np.argmax(counts)])))
    known = [(g, i) for g, i in labelled if i is not None]
    if not known:
        return []
    for k, (g, i) in enumerate(labelled):
        if i is None:
            labelled[k] = (g, min(known, key=lambda t: t[0].distance(g))[1])

    out = []
    for rid in sorted({i for _, i in labelled}):
        mine = [g for g, i in labelled if i == rid]
        merged = unary_union(mine)
        for poly in (merged.geoms if merged.geom_type == "MultiPolygon" else [merged]):
            if poly.area < MIN_FACET_M2:
                continue
            sub = _points_in(poly, pin)
            plane = (_fit_plane_robust(sub) if len(sub) >= MIN_POINTS
                     else tuple(planes[rid]))
            slope, aspect = _slope_aspect(plane)
            if slope > config.MAX_ROOF_SLOPE_DEG:
                continue
            if slope >= STEEP_FACE_DEG and _inlier_fraction(sub, plane) < STEEP_FACE_MIN_FIT:
                continue
            out.append({
                "building_id": building_id,
                "geometry": Polygon(poly.exterior, [r for r in poly.interiors]),
                "plane_a": plane[0], "plane_b": plane[1], "plane_c": plane[2],
                "slope_deg": slope, "aspect_deg": aspect,
                "area_m2": float(poly.area), "point_count": int(len(sub)),
            })
    return out


# Points a face needs before its plane is worth fitting. Matches the threshold
# _diagnose_no_facets uses to call a roof "no_lidar" -- below this there is not
# enough survey under the face to say what plane it is on.
MIN_POINTS_PER_FACE = 12

# The smallest face kept when the geometry came from the manual markup.
#
# MIN_FACET_M2 is 6.0 -- "below ~3 panels a face is not worth racking" -- which
# is a decision about PANELS being used to discard GEOMETRY. Measured across
# 85 marked roofs it threw away 19.3% of the drawn faces (119 of 615), and
# where every face on a roof was small the whole roof fell through to the LiDAR
# partition and lost its markup entirely.
#
# A 3 m2 dormer face is real roof. Keeping it costs nothing -- panel fitting
# will place nothing on it -- and losing it changes the shape of the roof.
# 0.8, not 1.5: markups mark sub-2 m2 dormer faces individually
# (#4732152: eighteen faces at 1.3-2.0 m2, seven of which the old
# threshold silently deleted -- 22 drawn, 15 built). A face too small to
# rack simply gets no panels; deleting drawn geometry for it violates
# markup-wins. The floor now only rejects degenerate slivers.
DRAWN_MIN_FACET_M2 = 0.8

# A markup has to describe most of the roof before it is allowed to BE the
# roof. #4735242 is a 1,054 m2 building whose drawn faces came to a single
# 15.3 m2 piece -- 1% of it -- and because label geometry wins outright, that
# one face replaced the whole partition and the building shipped 0 panels
# instead of 156.
#
# Measured across the 92 labelled roofs, coverage is a median 100% and only
# that one sits below 70%, so this is a guard against a partial markup rather
# than a threshold anything normal has to clear.
LINES_LEAD = os.environ.get("SOLAR_LINES_LEAD", "0") == "1"
FLAT_ROOF_MAX_SLOPE_DEG = 5.0   # below this there is no fold to cut on
DRAWN_MAX_SLOPE_DEG = 85.0    # a drawn face is roof unless it is a wall
DRAWN_COVER_MIN = 0.50

# A drawn face that, alongside other faces, spills past the outline or
# encloses the rest is the arrangement's enclosing face, not a roof plane.
OUTER_FACE_OVERSPILL = 1.02   # a face bigger than the building cannot be one of its planes
OUTER_FACE_CONTAINS = 0.90    # ...nor can one that swallows every other face

# How far a drawn or predicted line may be pushed along its own direction to
# reach the roof edge. Measured on the markups: endpoints sit a median 1.4 m
# from the eave on 7 Anderson and 3.9 m on 1 Memorial, with a 10.7 m worst
# case -- people stop drawing where the crease visually stops, not at the
# boundary. 2.5 m (label_geometry's default) leaves most faces unclosed.
LINE_SEAL_M = 6.0


def _seal_network(segs, boundary, max_ext=None):
    """Close a drawn line network into something polygonize can use.

    THE RULE IS GRAPH DEGREE, which is what the previous attempts got wrong.
    label_geometry.extend_dangling skips any end that comes within 25 cm of
    another line, so on a real markup -- where the lines are drawn to meet each
    other -- almost nothing is ever extended and the network never reaches the
    eave. Drawn endpoints sit a median 1.4 m from the roof edge on 7 Anderson
    and 3.9 m on 1 Memorial, connected to each other but not to the boundary,
    and the faces therefore never close. Extending EVERY end instead is worse:
    it drives edges out from junctions in the middle of the roof that nobody
    drew.

    A node where two lines meet is finished. A node where exactly one line ends
    is not, and it is the only kind worth pushing. So the network is noded
    first, degree is counted per node, and only degree-1 ends are extended --
    along their own line's direction, stopping at the first thing they meet.
    """
    import math
    from shapely.geometry import LineString, Point
    from shapely.ops import unary_union
    from collections import defaultdict

    if max_ext is None:
        max_ext = LINE_SEAL_M
    lines = [LineString(s) for s in segs if LineString(s).length > 1e-9]
    if not lines:
        return []
    noded = unary_union(lines)
    parts = [g for g in getattr(noded, "geoms", [noded])
             if g.geom_type == "LineString"]
    if not parts:
        return []

    def key(p):
        return (round(p[0], 2), round(p[1], 2))

    deg = defaultdict(int)
    for ln in parts:
        cs = list(ln.coords)
        deg[key(cs[0])] += 1
        deg[key(cs[-1])] += 1

    out = [list(ln.coords) for ln in parts]
    for ln in parts:
        cs = list(ln.coords)
        for idx, back in ((0, 1), (-1, -2)):
            p = cs[idx]
            if deg[key(p)] != 1:
                continue          # a junction: already sealed
            q = cs[back]
            dx, dy = p[0] - q[0], p[1] - q[1]
            L = math.hypot(dx, dy)
            if L == 0:
                continue
            ux, uy = dx / L, dy / L
            # start a hair along the ray so it does not re-hit its own endpoint
            a = (p[0] + ux * 1e-6, p[1] + uy * 1e-6)
            far = (p[0] + ux * max_ext, p[1] + uy * max_ext)
            others = [o for o in parts if o is not ln]
            targets = unary_union(others + [boundary]) if others else boundary
            try:
                hit = LineString([a, far]).intersection(targets)
            except Exception:
                continue
            if hit.is_empty:
                continue
            cands = []
            for g in ([hit] if hit.geom_type != "GeometryCollection"
                      else list(hit.geoms)):
                if g.geom_type == "Point":
                    cands.append(g)
                elif hasattr(g, "geoms"):
                    cands += [x for x in g.geoms if x.geom_type == "Point"]
                elif g.geom_type == "LineString" and not g.is_empty:
                    cands.append(Point(g.coords[0]))
            if not cands:
                continue
            nearest = min(cands, key=lambda c: Point(p).distance(c))
            out.append([p, (nearest.x, nearest.y)])
    return out


# ------------------------------------------------- selected faces (imagery)

# Faces chosen by the candidate selector (tools/predict_faces.py): SAM's
# reading or the line network's, whichever the evidence scored higher --
# validated against the manual markup at 0.776 of a 0.782 oracle on the 28
# benchmark roofs, and checked by eye on the winners page.
# Precomputed per building because the selector needs SAM and torch, which
# have no business inside the build environment. Off unless the flag is set.
SELECTED_FACES_DIR = (Path(__file__).resolve().parent.parent
                      / "data" / "selected_faces")
# DEFAULTS ON, because production does. It defaulted OFF while every
# shipping path exported SOLAR_SELECTED_FACES=1, so any tool that forgot
# the variable silently measured and rendered the OLD geometry path --
# not what ships. That cost three wrong answers in one day, the worst of
# them a contact sheet of twelve roofs for review, all drawn from the wrong
# pipeline. A default that disagrees
# with production is a trap, not a safety net; opt OUT with
# SOLAR_SELECTED_FACES=0 to build the old path deliberately.
USE_SELECTED_FACES = os.environ.get("SOLAR_SELECTED_FACES", "1") == "1"
# Below this share of the roof's LiDAR returns explained, a precomputed
# reading is not trusted and the LiDAR partition decides (SOLAR_SELECTED_MIN_SCORE
# to experiment). 34 Ballarat St ran on a 2-face "line" reading at 0.36.
SELECTED_MIN_SCORE = float(os.environ.get("SOLAR_SELECTED_MIN_SCORE", "0.30"))
# A reading scored under SELECTED_TRUST must COMPETE: the LiDAR partition is
# also run, and replaces the reading when it explains clearly more of the
# returns (SELECTED_COMPETE_MARGIN). A hard bar at 0.60 instead fixed 34
# Ballarat St (0.36, two strips) and 3 Rees St (0.32, jagged photo faces:
# LiDAR partition explained 0.74) but threw away good readings that merely
# scored low -- the clean pyramid on 4735292 lost its hips.
SELECTED_TRUST = float(os.environ.get("SOLAR_SELECTED_TRUST", "0.60"))
SELECTED_COMPETE_MARGIN = float(os.environ.get("SOLAR_SELECTED_COMPETE_MARGIN", "0.05"))
SELECTED_MIN_COVER = float(os.environ.get("SOLAR_SELECTED_MIN_COVER", "0.85"))  # see _partition_facets
SELECTED_ALT_MIN_AREA = float(os.environ.get("SOLAR_SELECTED_ALT_MIN_AREA", "0.92"))  # the LiDAR path must keep the roof


# IDENTICAL ROOFS, ONE READING (src/repeat_roofs.py). Where a building is one
# of a set of copies of a roof, the set's agreed reading replaces its own: on
# 6/60 Hallenstein St six copies had been read five ways. An agreed reading
# scored under SELECTED_TRUST still competes with the LiDAR path, and must
# keep the roof (REPEAT_CONTEST, REPEAT_KEEP_ROOF). On by default; SOLAR_REPEAT_ROOFS=0 turns it off.
REPEAT_FACES_DIR = SELECTED_FACES_DIR.parent / "repeat_faces"
USE_REPEAT_ROOFS = os.environ.get("SOLAR_REPEAT_ROOFS", "1") == "1"
# An agreed reading that covers clearly less roof than the LiDAR path gives
# way to it (src/roof_segmentation.py). SOLAR_REPEAT_KEEP_ROOF=0 turns it off.
REPEAT_KEEP_ROOF = os.environ.get("SOLAR_REPEAT_KEEP_ROOF", "1") == "1"
# An agreed reading scored under SELECTED_TRUST competes with the LiDAR path
# like any reading (src/roof_segmentation.py). SOLAR_REPEAT_CONTEST=0 exempts it.
REPEAT_CONTEST = os.environ.get("SOLAR_REPEAT_CONTEST", "1") == "1"


def selected_doc(building_id):
    """The reading a building is built from: its set's agreed reading when
    there is one (SOLAR_REPEAT_ROOFS), else its own selected faces; None
    when it has neither."""
    if building_id is None:
        return None
    # the vision referee's pick comes first when it is on (src/reading_referee.py)
    from src.reading_referee import REFEREE_FACES_DIR, USE_READING_REFEREE
    dirs = (([REFEREE_FACES_DIR] if USE_READING_REFEREE else [])
            + ([REPEAT_FACES_DIR] if USE_REPEAT_ROOFS else []) + [SELECTED_FACES_DIR])
    for d in dirs:
        fp = d / f"{building_id}.json"
        if not fp.exists():
            continue
        try:
            return json.loads(fp.read_text())
        except (OSError, ValueError):
            return None
    return None


def selected_score(building_id):
    """The precomputed reading's own score, or None when there is none."""
    try:
        doc = selected_doc(building_id)
        return None if doc is None else float(doc.get("score", 0.0))
    except (TypeError, ValueError):
        return None


def selected_agreed(building_id):
    """True when the building's reading is its repeat set's agreed one."""
    doc = selected_doc(building_id)
    return bool(doc) and doc.get("source") == "repeat"
SELECTED_MIN_PLANE_INLIER = 0.45  # a facet must be A plane     # below this, neither reading earned trust


BIG_FACE_KEEP_M2 = 100.0   # a machine face this big ships even over the vertex cap
# ...but only if it is convincingly ONE plane. The ten-corner cap had been a
# planarity proxy by accident: a SAM mask that covers a whole hip roof has
# many corners and spans several planes, and the cap threw it out, after
# which residual fill cut the area into real faces. Letting it ship at the
# ordinary 0.45 inlier bar (23 Sep re-lay, bisected to 2a44ad96) turned
# #5372674 from 6 facets into one at confidence 0.42 (withheld), #4747072
# from 3 into one, and #4737389's 28 facets / 85% of the roof into 4 / 32%.
BIG_FACE_MIN_PLANE_INLIER = 0.80


def _regularise_machine_face(poly, footprint):
    """(polygon, forced) or None. Enforce the module's founding invariant on
    faces from the selected chain: STRAIGHT BY CONSTRUCTION. SAM masks and LiDAR raster tilings
    arrive as traced boundaries -- lightly smoothed wobble: fuzzy roof
    lines on #4734994, jagged overlapping faces on #4735106. No real roof
    line is fuzzy. A face either becomes a low-vertex polygon whose edges
    snap to the building's dominant axes, or it does not ship (residual
    fill covers its area with clean partition cuts).
    """
    import numpy as np
    import shapely.affinity as _aff
    if poly.geom_type != "Polygon" or poly.is_empty:
        return None
    # the walls' direction, not the bounding rectangle's (src/outline_axis.py)
    from src.outline_axis import face_axis_deg
    ax = face_axis_deg(footprint, poly)
    if ax is None:
        cc = list(footprint.minimum_rotated_rectangle.exterior.coords)
        ax = np.degrees(np.arctan2(cc[1][1] - cc[0][1], cc[1][0] - cc[0][0]))
    rot = _aff.rotate(poly, -ax, origin=(0, 0))
    # THE VERTEX CAP SCALES WITH THE FACE. A flat 10-corner limit was right
    # for a house face and wrong for a commercial wing: 22 Earl Street's
    # 1,115 m2 and 937 m2 faces both regularised cleanly at every tolerance,
    # had more than ten corners because the wing genuinely has more than ten
    # corners, and were DROPPED -- a fifth of the roof gone, with residual
    # fill scraping back 154 m2 of it. Ten corners per 150 m2 on top of the
    # base ten, capped at thirty; and a face over BIG_FACE_KEEP_M2 ships at
    # the coarsest tolerance rather than not at all, because deleting it is
    # the larger error.
    max_vertices = int(min(30, 10 + poly.area / 150.0))
    fallback = None
    for tol in (0.3, 0.5, 0.8, 1.2):
        cand = rot.simplify(tol)
        if cand.geom_type != "Polygon" or cand.is_empty:
            continue
        cs = list(cand.exterior.coords)[:-1]
        # snap near-axis-parallel edges truly parallel (the straightness
        # that a traced boundary lacks)
        snapped = []
        for i in range(len(cs)):
            x0, y0 = cs[i]
            xp, yp = cs[i - 1]
            if abs(x0 - xp) < 0.45:
                x0 = (x0 + xp) / 2
                if snapped:
                    snapped[-1] = (x0, snapped[-1][1])
            if abs(y0 - yp) < 0.45:
                y0 = (y0 + yp) / 2
                if snapped:
                    snapped[-1] = (snapped[-1][0], y0)
            snapped.append((x0, y0))
        if len(snapped) < 3:
            continue
        out = Polygon(snapped)
        if not out.is_valid or out.is_empty:
            continue
        if abs(out.area - poly.area) < 0.25 * poly.area:
            back = _aff.rotate(out, ax, origin=(0, 0))
            if back.is_valid and back.geom_type == "Polygon":
                if len(snapped) <= max_vertices:
                    return back, False
                fallback = back      # over the cap, but a real, clean polygon
    if fallback is not None and poly.area >= BIG_FACE_KEEP_M2:
        return fallback, True
    return None


def residual_fill(building_id, footprint, pts, faces):
    """Facets for whatever of the footprint `faces` does not cover.

    COVERAGE IS A GUARANTEE, NOT A SIDE EFFECT. A machine face used to
    leave its area EMPTY: a pyramid whose two sunny faces had failed the
    one-plane gate shipped panels only on the shady side.

    Shared by BOTH paths. It lived inside partition_roof only,
    so every building on the vision chain -- 13,376 of them -- silently
    skipped it: #4724740 shipped 8 facets over 63% of its roof and left a
    216 m2 flat middle -- unobstructed, no lines -- with no facet, hence
    no panels, hence nothing on the map but empty roof.

    The residue goes back to the LiDAR partition, and its facets carry no
    from_selected flag, so they face every downstream drop as usual.
    """
    out = []
    try:
        if not faces:
            return out
        covered = unary_union([f["geometry"] for f in faces])
        residual = footprint.difference(covered.buffer(0.05))
        if residual.area <= max(12.0, 0.12 * footprint.area):
            return out
        inside_r = _points_in(footprint, pts)
        for cell in getattr(residual, "geoms", [residual]):
            if cell.geom_type != "Polygon" or cell.area < 8.0:
                continue
            fill = list(_partition(cell, _points_in(cell, inside_r)))
            # The fill drew a facet web over a cluttered flat (#4734913).
            # A roof line should only exist where there is confidence in
            # it. The boundary between two fill facets whose
            # planes barely differ is exactly such a line -- merge them until
            # every remaining boundary separates planes that clearly disagree.
            merged = True
            while merged and len(fill) > 1:
                merged = False
                for i in range(len(fill)):
                    for j2 in range(i + 1, len(fill)):
                        pi, pli = fill[i]
                        pj, plj = fill[j2]
                        si, ai = _slope_aspect(pli)
                        sj, aj = _slope_aspect(plj)
                        d_asp = abs((ai - aj + 180) % 360 - 180)
                        alike = (abs(si - sj) < 7.0
                                 and (max(si, sj) < 8.0 or d_asp < 30.0))
                        if not alike:
                            continue
                        if not pi.buffer(0.1).intersects(pj):
                            continue
                        u = pi.union(pj).buffer(0.05).buffer(-0.05)
                        if u.geom_type != "Polygon":
                            continue
                        sub_u = _points_in(u, inside_r)
                        pl_u = (_fit_plane_robust(sub_u) if len(sub_u) > 12
                                else (pli if pi.area >= pj.area else plj))
                        fill[i] = (u, pl_u)
                        del fill[j2]
                        merged = True
                        break
                    if merged:
                        break
            for poly2, plane2 in fill:
                slope2, aspect2 = _slope_aspect(plane2)
                if slope2 > config.MAX_ROOF_SLOPE_DEG:
                    continue
                sub2 = _points_in(poly2, inside_r)
                out.append({
                    "building_id": building_id,
                    "geometry": Polygon(poly2.exterior,
                                        [r for r in poly2.interiors]),
                    "plane_a": plane2[0], "plane_b": plane2[1],
                    "plane_c": plane2[2],
                    "slope_deg": slope2, "aspect_deg": aspect2,
                    "area_m2": float(poly2.area),
                    "point_count": int(len(sub2)),
                })
    except Exception as exc:
        print(f"  roof_partition: residual fill failed ({exc!r})", flush=True)
    return out


def facets_from_selected_faces(building_id, footprint, pts):
    """Facets straight from the precomputed winner, planes from LiDAR.

    Same construction as facets_from_drawn_faces: the rings are taken as
    the geometry, LiDAR contributes only each face's plane, sparse or
    unfittable faces borrow a neighbour's plane rather than vanishing.
    """
    if not USE_SELECTED_FACES or building_id is None:
        return []
    # narrow on purpose (selected_doc catches only OSError/ValueError): a bare
    # except here swallowed a missing import for a whole debugging session,
    # exactly as this module's own docstrings warn
    doc = selected_doc(building_id)
    if doc is None:
        return []
    if doc.get("score", 0.0) < SELECTED_MIN_SCORE:
        return []
    inside = _points_in(footprint, pts)
    if len(inside) < MIN_POINTS:
        inside = pts
    out = []
    pending = []
    for ring in doc.get("faces") or []:
        try:
            poly = Polygon(ring)
            if not poly.is_valid:
                poly = poly.buffer(0)
        except Exception:
            continue
        if (poly.is_empty or poly.geom_type != "Polygon"
                or poly.area < DRAWN_MIN_FACET_M2):
            continue
        # straight-by-construction, enforced at the seam: a traced boundary
        # either regularises to a clean low-vertex polygon or does not ship
        reg = _regularise_machine_face(poly, footprint)
        _dbg = os.environ.get("SOLAR_FACE_DEBUG")
        if reg is None:
            if _dbg:
                print(f"[face {building_id}] {poly.area:.0f} m2 {len(poly.exterior.coords) - 1} corners: regulariser dropped it")
            continue
        poly, forced = reg
        sub = _points_in(poly, inside)
        plane = _fit_plane_robust(sub) if len(sub) >= MIN_POINTS_PER_FACE \
            else None
        if _dbg:
            print(f"[face {building_id}] {poly.area:.0f} m2 {len(poly.exterior.coords) - 1} corners forced={forced} "
                  f"pts={len(sub)} inlier={_inlier_fraction(sub, plane) if plane is not None else None}")
        if forced and (plane is None
                       or _inlier_fraction(sub, plane) < BIG_FACE_MIN_PLANE_INLIER):
            continue          # over the cap and not one plane: residual fill cuts it properly
        if plane is not None:
            # A FACE THAT IS NOT ONE PLANE IS NOT A FACE. #4740503's balcony
            # panels rode in on an 835 m2 SAM mask whose plane inlier was
            # 0.13 -- a mask spanning the main roof AND three terrace levels.
            # Machine-chosen geometry earns no borrowed plane for that: it is
            # dropped outright, and the fitter simply places nothing there.
            # (Drawn faces never hit this path; sparse faces still
            # borrow below.)
            if _inlier_fraction(sub, plane) < SELECTED_MIN_PLANE_INLIER:
                continue
        bad = plane is None
        if not bad:
            slope, aspect = _slope_aspect(plane)
            if slope > DRAWN_MAX_SLOPE_DEG:
                bad = True
            elif (slope >= STEEP_FACE_DEG
                  and _inlier_fraction(sub, plane) < STEEP_FACE_MIN_FIT):
                bad = True
        if bad:
            pending.append(poly)
            continue
        out.append({
            "building_id": building_id,
            "geometry": Polygon(poly.exterior, [r for r in poly.interiors]),
            "plane_a": plane[0], "plane_b": plane[1], "plane_c": plane[2],
            "slope_deg": slope, "aspect_deg": aspect,
            "area_m2": float(poly.area), "point_count": int(len(sub)),
            "from_selected": True,
        })
    # PLAIN POLYGONS, because that is what this function's pending list holds.
    #
    # This loop said `for poly, _no_panel in pending` -- the shape used by
    # facets_from_drawn_faces, where a face carries the markup's "no panels here"
    # flag. It was changed here by mistake while that flag was being added
    # there, and this function's two producers still append a bare Polygon.
    #
    # The cost was invisible and large. Any building on the selected-faces
    # chain with even one PENDING face -- a face too sparse to fit its own
    # plane, or one whose fit is unusable -- raised TypeError, which
    # partition_roof catches and reports as "selected faces unavailable"
    # before falling back to the old RANSAC path. So the reading was
    # discarded and the old path answered instead, with no error anyone would
    # see. It showed on the map: 30 Brunswick Street, a 5,272 m2 roof
    # with a 37-face LiDAR reading, came out as "Too complex to finish
    # modelling" -- the fallback collapsed it to 2 facets and ran past its
    # 1,800-second budget.
    for poly in pending:
        best = None
        for f in out:
            try:
                shared = poly.buffer(0.2).intersection(f["geometry"]).area
            except Exception:
                continue
            if shared > 0 and (best is None or f["area_m2"] > best["area_m2"]):
                best = f
        if best is None:
            continue
        out.append({
            "building_id": building_id,
            "geometry": Polygon(poly.exterior, [r for r in poly.interiors]),
            "plane_a": best["plane_a"], "plane_b": best["plane_b"],
            "plane_c": best["plane_c"],
            "slope_deg": best["slope_deg"], "aspect_deg": best["aspect_deg"],
            "area_m2": float(poly.area), "point_count": 0,
            "from_selected": True, "plane_borrowed": True,
        })
    # COVERAGE IS A GUARANTEE ON THIS PATH TOO. Until 18 Sep only
    # partition_roof filled the residue, so a vision reading that covered
    # part of a roof left the rest with no facet at all -- and no facet
    # means no panels, no obstructions, nothing. #4724740 shipped 63%
    # coverage and a bare 216 m2 flat middle.
    filled = residual_fill(building_id, footprint, pts, out)
    if os.environ.get("SOLAR_FACE_DEBUG"):
        print(f"[face {building_id}] selected kept {len(out)} ({sum(f['area_m2'] for f in out):.0f} m2), "
              f"residual fill added {len(filled)} ({sum(f['geometry'].area for f in filled):.0f} m2) of footprint {footprint.area:.0f} m2")
    out.extend(filled)
    return out


# How many parts one face may be cut into by open-ended drawn lines. A face that
# falls apart into five is not a fold being honoured, it is a bad cut.
OPEN_LINE_MAX_PARTS = 4
OPEN_LINE_MIN_PART_M2 = 2.0


# How different two sides of a cut must be for the cut to be worth making.
OPEN_LINE_MIN_ASPECT_DEG = 20.0
OPEN_LINE_MIN_SLOPE_DEG = 5.0
# and how much better two planes must fit than one
OPEN_LINE_MIN_RMS = 0.15
OPEN_LINE_MIN_RMS_GAIN = 0.20
# A cut through a joined end skips the fit-gain test, so each part must carry
# a plane of its own instead: enough returns, and most of them on it. Without
# this, parts that could not be read borrowed a neighbour's plane or fitted a
# steep sliver -- #4739074 read a flat deck at 24.6 deg, #4747486 grew a
# 39 deg sliver at a junction.
JOIN_PART_MIN_POINTS_X = 4
JOIN_PART_MIN_FIT = 0.70


def _planes_differ(parts, poly, pts, joined=False):
    """Is this face genuinely two planes, or one plane with a line drawn on it?

    Two tests, both of which must pass. The pieces have to face the sun
    differently -- that is the only way a cut changes the estimate -- and
    the whole face has to fit ONE plane materially worse than the pieces fit
    two, which is what says the fold is in the survey and not just in the
    drawing.

    `joined`: the cut runs a drawn end the last DANGLE_JOIN_M to the line it
    was drawn to meet, so the fold is authored, not guessed. The fit-gain test
    is skipped -- on #5372566 the drawn triangle fits 1.1 deg against the rest
    of the face's 8.2 deg, but the rest is rough (rms 0.45 m), so two planes
    fit only 11% better than one -- and each part must instead fit a plane of
    its own (JOIN_PART_MIN_FIT).
    """
    import numpy as np

    def rms(sub):
        pl = _fit_plane_robust(sub)
        if pl is None:
            return None, None
        r = sub[:, 2] - (pl[0] * sub[:, 0] + pl[1] * sub[:, 1] + pl[2])
        return float(np.sqrt((r ** 2).mean())), _slope_aspect(pl)

    whole = _points_in(poly, pts)
    if len(whole) < MIN_POINTS_PER_FACE * 2:
        return False
    r_one, _ = rms(whole)
    if r_one is None:
        return False
    subs = []
    fits = []
    for q in parts:
        sub = _points_in(q, pts)
        if len(sub) < MIN_POINTS_PER_FACE * (JOIN_PART_MIN_POINTS_X if joined else 1):
            return False          # cannot tell, so do not cut
        r, sa = rms(sub)
        if r is None:
            return False
        if joined and _inlier_fraction(sub, _fit_plane_robust(sub)) < JOIN_PART_MIN_FIT:
            return False          # a part that is not one plane would be read wrong
        subs.append((r, len(sub)))
        fits.append(sa)
    n = sum(k for _, k in subs)
    r_two = (sum(r * r * k for r, k in subs) / max(n, 1)) ** 0.5
    if not joined and (r_one < OPEN_LINE_MIN_RMS
                       or r_two > (1.0 - OPEN_LINE_MIN_RMS_GAIN) * r_one):
        return False
    for i in range(len(fits)):
        for j in range(i + 1, len(fits)):
            (s1, a1), (s2, a2) = fits[i], fits[j]
            da = abs(a1 - a2) % 360.0
            da = min(da, 360.0 - da)
            if abs(s1 - s2) >= OPEN_LINE_MIN_SLOPE_DEG:
                return True
            if min(s1, s2) >= 3.0 and da >= OPEN_LINE_MIN_ASPECT_DEG:
                return True
    return False


def _split_on_open_lines(building_id, footprint, pts, faces):
    """Cut drawn faces where a drawn line stops short of an edge.

    The labelling tool exports faces from a planar subdivision, so a line with
    a free end bounds no region and never reaches the build. Measured on the
    three roofs repeatedly flagged for it, that is the WHOLE of the "missing
    lines" defect: every closed line drawn is reproduced, every open-ended one
    is dropped.

    roof_line_source.drawn_network closes a free end only where the LiDAR fold
    carries on across the gap, and only over a short gap -- see the long note
    there, and in particular why this is not the 19 Sep experiment that
    extended every dropped line to the boundary and cost 17.6 points of
    fidelity.

    A face is replaced by its parts only if the cut produces at least two
    sensible ones. Anything else leaves the face exactly as he drew it.
    """
    try:
        from src.roof_line_source import drawn_network, EXTEND_DANGLING
    except Exception:
        return faces
    if not EXTEND_DANGLING or not faces:
        return faces
    joins = []
    try:
        net = drawn_network(building_id, footprint, pts, joined=joins)
    except Exception:
        return faces
    if not net:
        return faces
    from shapely.geometry import Polygon
    from shapely.ops import split as _split
    try:
        cut = unary_union(net)
    except Exception:
        return faces

    out = []
    for f in faces:
        try:
            poly = Polygon(f["ring"])
            if not poly.is_valid:
                poly = poly.buffer(0)
            if poly.is_empty or poly.geom_type != "Polygon" or poly.area < 4.0:
                out.append(f)
                continue
            parts = [q for q in _split(poly, cut).geoms
                     if q.geom_type == "Polygon" and q.area > OPEN_LINE_MIN_PART_M2]
        except Exception:
            out.append(f)
            continue
        if len(parts) < 2 or len(parts) > OPEN_LINE_MAX_PARTS:
            out.append(f)
            continue
        # the cut must not have shaved the face -- the parts have to account
        # for it, or something other than a fold has been subtracted
        if sum(q.area for q in parts) < 0.97 * poly.area:
            out.append(f)
            continue
        # A CUT HAS TO CHANGE THE ANSWER TO BE WORTH THE FACE.
        #
        # Every split costs one exact match against the faces the labelling
        # tool derived, because neither child equals the parent. Measured over
        # the bench that is one-for-one: 9 more drawn lines found, 7 fewer faces
        # exact. So a cut only earns its keep where the two sides really are
        # different roof -- a different way to face the sun, which is the
        # whole reason a fold matters to the estimate. Where the planes agree,
        # the fold is cosmetic, the panel keepout already stops panels
        # spanning it, and the map draws it from the markup layer.
        joined = any(j.intersects(poly) for j in joins)
        if not _planes_differ(parts, poly, pts, joined=joined):
            out.append(f)
            continue
        for q in parts:
            out.append({"ring": list(q.exterior.coords),
                        "m2": float(q.area),
                        "usable": f.get("usable", True)})
    return out


def facets_from_drawn_faces(building_id, footprint, pts):
    """Build facets straight from the tool-derived rings in roof_labels.json.

    No sealing, no noding, no topology inference -- the arrangement is already
    settled. All that is added here is what the labels cannot know: the plane
    each face sits on, fitted from the LiDAR under it.

    A face the labeller marked `usable: false` -- the "no panels here" click --
    is dropped rather than fitted. A face with too few returns under it is
    dropped too: the ring is his, but a plane needs points.
    """
    from shapely.geometry import Polygon

    try:
        from src.roof_line_source import drawn_faces
    except Exception:
        return []
    faces = drawn_faces(building_id)
    if not faces:
        return []
    # DROP THE ARRANGEMENT'S OUTER FACE. facesFor() walks a planar subdivision
    # and can return the enclosing face alongside the real ones -- on #4725584
    # that is a 4,962 m2 ring on a 4,032 m2 building, larger than the building,
    # sitting beside 37 genuine faces of 84 m2 and below.
    #
    # Kept as a facet it becomes the whole roof: it spans several real planes,
    # so its on-plane fit is 0.16, it is rejected by BIG_ROOF_FACET_MIN_FIT,
    # and the building shipped 18 panels against 465 live.
    #
    # Only when there are OTHER faces. A roof marked as a single plane
    # legitimately has one face covering 100% of the outline, and eleven marked
    # roofs are exactly that -- dropping those would delete the markup instead
    # of cleaning it.
    #
    # DONE BEFORE THE COVERAGE CHECK, which is the whole point. Dropping the
    # enclosing face leaves #4725584 with 200 m2 of detail faces on a 4,032 m2
    # building -- 5% -- and #4734685 with 1%. That is not markup describing a
    # roof, and the coverage guard below then correctly hands both to the LiDAR
    # partition. Drop it afterwards instead and coverage is computed at 131%,
    # the guard passes, and the building ships 31 tiny facets and 18 panels.
    # WHAT MAKES A FACE THE ARRANGEMENT'S OUTER FACE, rather than simply large.
    #
    # The first version dropped any face covering >= 90% (the old OUTER_FACE_FRAC) of the
    # footprint. That is true of the artefact and also of a roof drawn as
    # ONE plane, and the `len(faces) >= 2` guard did not save those: a roof
    # marked as one plane plus one small "no panels here" patch has two faces,
    # so its only real plane was deleted and the remaining 5% failed the
    # coverage check below. #5372585 -- a 210.8 m2 plane on a 221.8 m2 building
    # plus an 11 m2 no-panel patch -- was rejected entirely that way.
    #
    # An outer face is the COMPLEMENT of the others, so it gives itself away by
    # either enclosing them or spilling outside the footprint:
    #
    #   roof       face/footprint   contains the others
    #   #5372585            0.951                  0%   a drawn plane
    #   #5371108            0.161                  0%   a drawn plane
    #   #5372588            1.000                100%   artefact
    #   #4725584            1.230                 17%   artefact (4,962 m2
    #                                                   on a 4,032 m2 building)
    #
    # Neither test alone separates all four: containment misses #4725584, and
    # the area ratio misses #5372588 at 1.0002. Together they classify every
    # case correctly.
    if len(faces) >= 2:
        polys = []
        for f in faces:
            try:
                q = Polygon(f["ring"])
                polys.append(q if q.is_valid else q.buffer(0))
            except Exception:
                polys.append(None)

        filled = Polygon(footprint.exterior)

        def _is_outer(i):
            q = polys[i]
            if q is None or q.is_empty:
                return False
            if q.area > OUTER_FACE_OVERSPILL * footprint.area:
                return True
            # A COURTYARD HID THE ARTEFACT. #4725584's footprint arrives with
            # its courtyard filled (5,172 m2 against 4,032 with the hole), so
            # the 4,962 m2 complement face stopped overspilling and shipped
            # 1,383 panels across the drawn ridges. Against the FILLED
            # footprint it is 96% -- no real plane is 90% of a roof that
            # carries five other faces beside it. The many-faces gate keeps
            # #5372585's legitimate 95% single plane (two faces) safe.
            if len(faces) >= 6 and q.area > 0.9 * filled.area:
                return True
            rest = [p for j, p in enumerate(polys)
                    if j != i and p is not None and not p.is_empty]
            if not rest:
                return False
            try:
                u = unary_union(rest)
                return q.intersection(u).area / max(u.area, 1e-9) >= OUTER_FACE_CONTAINS
            except Exception:
                return False

        keep = [f for i, f in enumerate(faces) if not _is_outer(i)]
        if keep:
            faces = keep

    try:
        cover = sum(f.get("m2") or 0.0 for f in faces) / max(footprint.area, 1e-9)
    except Exception:
        cover = 1.0
    if cover < DRAWN_COVER_MIN:
        return []          # a partial markup: let the partition do the roof

    inside = _points_in(footprint, pts)
    if len(inside) < MIN_POINTS:
        inside = pts

    faces = _split_on_open_lines(building_id, footprint, inside, faces)

    out = []
    pending = []
    for f in faces:
        # A "NO PANELS HERE" FACE IS STILL A FACE. Dropping it entirely
        # also deleted its boundaries, so a drawn line simply vanished
        # from the roof: #4735623 lost a valley line that was the edge of a
        # face marked unusable. It is kept now, carrying no_panel, so the
        # geometry is the roof as drawn and
        # the fitter still places nothing on it. This is what the
        # drawn_faces docstring always claimed: "knowing a face exists but
        # takes no panels is more useful than not knowing it exists."
        _no_panel = not f.get("usable", True)
        try:
            poly = Polygon(f["ring"])
            if not poly.is_valid:
                poly = poly.buffer(0)
        except Exception:
            continue
        if (poly.is_empty or poly.geom_type != "Polygon"
                or poly.area < DRAWN_MIN_FACET_M2):
            continue
        sub = _points_in(poly, inside)
        if len(sub) < MIN_POINTS_PER_FACE:
            # Too few returns to fit a plane of its own. The face is still real
            # -- at 4.9 returns/m2 a 4 m2 dormer holds about twenty points --
            # so it borrows the plane of the largest face it touches rather
            # than being deleted.
            sub = None
        if sub is None:
            pending.append((poly, _no_panel))
            continue
        # A BAD PLANE IS NOT A REASON TO DELETE A DRAWN FACE.
        #
        # These three tests exist to reject walls and rubbish surfaces found by
        # the LiDAR partition. On a drawn face they reject something else:
        # the FIT, not the face. At 4.9 returns/m2 a 7 m2 dormer carries about
        # thirty points, and thirty noisy points still routinely fit a plane steeper
        # than MAX_ROOF_SLOPE. Measured on the two worst roofs in the benchmark,
        # this was the whole of the loss -- #4735237 lost 7 of 23 faces to slope
        # and steep-fit, #5372610 lost 3 of 6:
        #
        #   #4735237  kept 13, slope>55 4, steep+poor fit 3, too sparse 3
        #   #5372610  kept  2, slope>55 1, steep+poor fit 2
        #
        # The markup is the authority on which parts of the roof are roof. So a face
        # whose own fit is unusable borrows a neighbour's plane, exactly as a
        # face with too few points already does, and is only dropped if it has
        # no neighbour to borrow from. That keeps the guard against genuine
        # walls -- a wall drawn in isolation still goes -- without deleting
        # marked geometry.
        plane = _fit_plane_robust(sub)
        bad_fit = plane is None
        if not bad_fit:
            slope, aspect = _slope_aspect(plane)
            # Panels can be placed steeper than 55 degrees when needed.
            # MAX_ROOF_SLOPE_DEG stays at 55 for geometry the LiDAR
            # guessed, where it is the guard against calling a wall a roof.
            # On a drawn face it was answering a question the markup has
            # already answered, and steep roofs are exactly where the fitted slope is
            # least trustworthy anyway. Only a near-vertical face is still
            # refused here, since that is a wall however it was produced.
            if slope > DRAWN_MAX_SLOPE_DEG:
                bad_fit = True
            elif (slope >= STEEP_FACE_DEG
                  and _inlier_fraction(sub, plane) < STEEP_FACE_MIN_FIT):
                bad_fit = True
        if bad_fit:
            pending.append((poly, _no_panel))
            continue
        out.append({
            "building_id": building_id,
            "geometry": Polygon(poly.exterior, [r for r in poly.interiors]),
            "plane_a": plane[0], "plane_b": plane[1], "plane_c": plane[2],
            "slope_deg": slope, "aspect_deg": aspect,
            "area_m2": float(poly.area), "point_count": int(len(sub)),
            "from_labels": True,
            **({"no_panel": True} if _no_panel else {}),
        })

    # Faces with too little survey under them take the plane of the largest
    # neighbour they share an edge with. Better a small face on its neighbour's
    # plane than the roof reverting to a partition that ignores the markup.
    for poly, _no_panel in pending:
        best = None
        for f in out:
            try:
                shared = poly.buffer(0.2).intersection(f["geometry"]).area
            except Exception:
                continue
            if shared > 0 and (best is None or f["area_m2"] > best["area_m2"]):
                best = f
        if best is None:
            continue
        out.append({
            "building_id": building_id,
            "geometry": Polygon(poly.exterior, [r for r in poly.interiors]),
            "plane_a": best["plane_a"], "plane_b": best["plane_b"],
            "plane_c": best["plane_c"],
            "slope_deg": best["slope_deg"], "aspect_deg": best["aspect_deg"],
            "area_m2": float(poly.area), "point_count": 0,
            "from_labels": True, "plane_borrowed": True,
            **({"no_panel": True} if _no_panel else {}),
        })
    # A LINE THE LABELLING TOOL DID NOT USE STILL SPLITS A FACE.
    #
    # Three roofs were missing drawn valley and ridge lines. Measured, one
    # rule accounts for
    # all three with no exceptions: every line whose two ends CLOSE is
    # reproduced as a facet boundary, and every line with a FREE end is
    # dropped -- the tool exports faces from a planar subdivision, and a
    # dangling edge bounds no region.
    #
    # Extending every dropped line to the boundary was tried first and cost
    # 17.6 points of fidelity (94.8% -> 77.2%, facets 5 -> 25). What ships is
    # the narrow version above: a free end is run out only while the LiDAR
    # fold carries on across the gap, only over a short gap, and only where
    # two planes fit the face better than one.
    #
    # The trade it makes is exact and could not be resolved by measuring:
    #
    #   faces matching the markup   97.0% -> 95.8%
    #   drawn lines found           80.8% -> 81.4%
    #
    # one-for-one by construction, because splitting a face always loses the
    # parent's exact match and neither child replaces it. The real question
    # was which of two authored things wins when they disagree -- the drawn
    # LINES, or the FACES the tool exported after dropping one. The decision:
    # the lines win; run them out.
    return out


# MEASURED AND NOT USED FOR MODEL LINES. line_facets subdivides by segment
# rather than cutting on infinite lines, which is right for drawn geometry
# and wrong for geometry a detector guessed. Re-tested after MIN_SCORE rose to
# 0.90, so most false lines are already gone:
#
#   model path            found   undrawn   clutter   facets
#   cuts (current)        82.5%    22.4%      119      8.0
#   subdivision           57.6%    14.4%       47      3.7
#
# It does not become good at 0.90, it becomes CONSERVATIVE: half the invented
# edges, and a quarter of the real creases gone with them. Bigger, cleaner
# faces that run straight over drawn folds -- which is what puts a panel
# across a ridge, the failure this work exists to fix.
#
# Written down because the numbers flatter it in isolation. Fewer facets and
# less clutter is the stated goal, and reported alone this reads as progress.
def line_facets(building_id, footprint, pts, segs):
    """Faces built by planar subdivision of ROOF-LINE SEGMENTS.

    Works for any source of segments -- drawn lines, or the ones the
    model predicted over imagery it has never seen. The second is the point:
    the markups exist to train a detector that then runs over every tile, so
    whatever consumes lines has to serve 15,000 unlabelled roofs, not 114
    labelled ones.

    THE POINT OF DOING IT THIS WAY. Feeding drawn lines to _cut was tried first
    and made things worse across 28 of his completed roofs -- lines found
    84.1% -> 82.6%, edges he never drew 22.3% -> 27.7%. _cut slices a whole
    cell with an INFINITE line, while a drawn ridge is a segment with extent, so
    a 3 m dormer crease sliced the entire roof. The note above the cut loop
    already said what was missing: "a way to cut only the stretch a crease
    actually covers".

    This is that way. The drawn segments and the roof boundary are polygonized
    together, so every face edge is either a line he drew or the edge of the
    building, and nothing is extrapolated across the roof.

    THE BOUNDARY IS THE TRIMMED FOOTPRINT, NOT label_geometry's drawn hull.
    That module builds a convex hull of the drawn points, which is right when
    the surveyed outline is untrusted -- its own docstring explains why -- but
    wrong here: a convex hull of an L-shaped roof covers the notch, and panels
    would be placed over open air. Downstream fitting, obstructions and areas
    all work in footprint space, so the footprint is what the faces must live
    in.

    Returns [] when there are no usable segments, so callers can fall through.
    """
    from shapely.geometry import Polygon
    from shapely.ops import polygonize

    try:
        from src.label_geometry import snap_endpoints
    except Exception:
        return []
    if not segs:
        return []

    segs = [((s[0], s[1]), (s[2], s[3])) for s in segs]
    # Ends within SNAP_M become one node first: two lines drawn to "the same"
    # corner are the same corner, and without this they are two degree-1 ends
    # that both get extended past each other.
    segs = snap_endpoints(segs)
    # Then seal by GRAPH DEGREE -- only ends where exactly one line terminates,
    # stopping at the first line or roof edge met. See _seal_network for why the
    # touch-rule and the extend-everything variants both fail on a real markup.
    segs = _seal_network(segs, footprint.exterior)
    if not segs:
        return []

    # NODE THE ARRANGEMENT BEFORE POLYGONIZING. shapely's polygonize needs its
    # input split at every crossing; hand it raw segments that cross and it
    # returns almost nothing. This one missing call is why the whole approach
    # looked hopeless: 7 Anderson's 14 lines yielded 3 cells (one 177 m2 blob
    # and two slivers) un-noded, and 7 sensible faces noded. It is also why
    # label_geometry.faces_from_lines never worked and ended up imported by
    # nothing -- it polygonizes raw edges the same way.
    from shapely.geometry import LineString
    from shapely.ops import unary_union
    lines = [LineString(s) for s in segs] + [footprint.exterior]
    lines += [r for r in footprint.interiors]
    try:
        noded = unary_union(lines)
    except Exception:
        return []

    cells = []
    for poly in polygonize(noded):
        if not poly.is_valid or poly.area < MIN_FACET_M2:
            continue
        # polygonize also closes faces OUTSIDE the footprint where an extended
        # line and the boundary enclose a sliver of garden.
        if not poly.representative_point().within(footprint.buffer(0.01)):
            continue
        cells.append(poly)
    if not cells:
        return []

    inside = _points_in(footprint, pts)
    out = []
    for poly in cells:
        sub = _points_in(poly, inside)
        if len(sub) < MIN_POINTS_PER_FACE:
            continue
        plane = _fit_plane_robust(sub)
        if plane is None:
            continue
        slope, aspect = _slope_aspect(plane)
        if slope > config.MAX_ROOF_SLOPE_DEG:
            continue
        if slope >= STEEP_FACE_DEG and _inlier_fraction(sub, plane) < STEEP_FACE_MIN_FIT:
            continue
        out.append({
            "building_id": building_id,
            "geometry": Polygon(poly.exterior, [r for r in poly.interiors]),
            "plane_a": plane[0], "plane_b": plane[1], "plane_c": plane[2],
            "slope_deg": slope, "aspect_deg": aspect,
            "area_m2": float(poly.area), "point_count": int(len(sub)),
            "from_lines": True,
        })
    return out


def partition_by_planes(building_id, footprint, pts, seed=0, planes=None):
    """Big planes from the LiDAR, trimmed by each other and by the building edge.

    Make big planes from the roof angles the LiDAR shows, then trim each by
    the edge of the building or by another plane.

    Nothing is detected in imagery and no boundary is traced. A plane's extent is
    decided by where it stops being the best explanation of the points -- which
    is either where another plane takes over, along the exact line the two
    intersect, or the surveyed footprint edge. Both are straight by construction,
    so the result cannot be fuzzy and the faces meet cleanly at real angles.

    `planes` lets a caller supply the plane hypotheses (region growing finds
    much cleaner planes on complex hip roofs than the greedy detector here --
    greedy RANSAC's compromise planes at the joins were exactly why this path
    sat unused); None keeps the self-detecting behaviour."""
    rng = np.random.default_rng(seed)
    inside = _points_in(footprint, pts)
    if len(inside) < MIN_POINTS:
        return []
    if planes is None:
        cap = PLANES_LARGE_MAX if footprint.area > PLANES_LARGE_ROOF_M2 else PLANES_TYPICAL_MAX
        planes = _detect_large_planes(inside, footprint, rng, max_planes=cap)
    planes = dedupe_planes(planes, footprint)
    if not planes:
        return []

    # Cut by where the planes meet. Ordered by how much roof each pair actually
    # separates, so if the cap bites it is the least important joins that go.
    cuts = (_plane_intersection_cuts(planes, footprint)[:MAX_INTERSECTION_LINES]
            + _reflex_corner_cuts(footprint))
    cells = [footprint]
    for ang, off in cuts:
        nxt = []
        for c in cells:
            parts = _cut(c, ang, off)
            nxt.extend(parts if len(parts) >= 2 else [c])
        cells = nxt
        if len(cells) > 200:      # runaway guard on a pathological roof
            break

    # Each cell goes to the plane its own points support best; cells too sparse
    # to vote take the plane of the nearest cell that could.
    labelled = []
    for cell in cells:
        if cell.area < MIN_PIECE_M2:
            continue
        sub = _points_in(cell, inside)
        if len(sub) < 6:
            labelled.append((cell, None))
            continue
        res = [np.median(np.abs(sub[:, 2] - (a * sub[:, 0] + b * sub[:, 1] + c)))
               for a, b, c in planes]
        labelled.append((cell, int(np.argmin(res))))
    known = [(g, i) for g, i in labelled if i is not None]
    if not known:
        return []
    for k, (g, i) in enumerate(labelled):
        if i is None:
            labelled[k] = (g, min(known, key=lambda t: t[0].distance(g))[1])

    # Adjacent cells on the same plane are one face.
    out = []
    for pi in range(len(planes)):
        mine = [g for g, i in labelled if i == pi]
        if not mine:
            continue
        merged = unary_union(mine)
        for poly in (merged.geoms if merged.geom_type == "MultiPolygon" else [merged]):
            if poly.area < MIN_FACET_M2:
                continue
            sub = _points_in(poly, inside)
            plane = _fit_plane_robust(sub) if len(sub) >= MIN_POINTS else planes[pi]
            slope, aspect = _slope_aspect(plane)
            if slope > config.MAX_ROOF_SLOPE_DEG:
                continue
            if slope >= STEEP_FACE_DEG and _inlier_fraction(sub, plane) < STEEP_FACE_MIN_FIT:
                continue        # steep AND not a plane: a wall, not a roof face
            out.append({
                "building_id": building_id,
                "geometry": Polygon(poly.exterior, [r for r in poly.interiors]),
                "plane_a": plane[0], "plane_b": plane[1], "plane_c": plane[2],
                "slope_deg": slope, "aspect_deg": aspect,
                "area_m2": float(poly.area), "point_count": int(len(sub)),
            })
    return out


# The LINZ outline is the BUILDING, not the roof.
#
# The true roof outline of 7 Anderson Heights, as drawn, does not follow
# the footprint: the roof overhangs it on one side and sits inside it on
# another. Measured across five buildings, 6.6% to 18.8% of roof-height points
# fall outside the footprint, by up to 2 m. Those are eaves.
#
# This module cuts the footprint into faces, so every perimeter face was wrong
# at its edge before any ridge logic ran, and roof area was understated
# everywhere. The footprint is still the right SKELETON -- it is surveyed and
# straight -- so the roof outline is built by pushing it out to where the roof
# actually stops rather than by tracing points, which would reintroduce the
# fuzz the whole approach exists to avoid.
# Deliberately timid, because a uniform buffer grows toward the NEIGHBOURS too
# and their roofs sit at similar heights, so a loose test walks straight onto
# them: at 2.0 m and a 50% share this grew 7 Anderson Heights by 66% and 2/8
# Wakatipu by 81%, when the drawn roof outline is nearer 10% larger than the
# footprint. Held to a typical eave, and needing the ring to be almost entirely
# roof-height before it is accepted.
# OFF pending better work. (The per-edge attempt, roof_outline, and the
# post-partition _extend_to_eave were removed on 24 Sep 2026; git history
# has both.) The FINDING is solid and matters:
# 6.6% to 18.8% of roof-height points fall outside the LINZ footprint, by up to
# 2 m, so roof area is understated everywhere and every perimeter face is wrong
# at its edge. But a uniform buffer is the wrong instrument. The true roof
# outline of 7 Anderson Heights is not the footprint grown evenly -- the roof
# overhangs on one side and sits INSIDE it on another -- and growing uniformly
# took that roof to 16 faces against its real 8. This needs per-edge treatment:
# decide independently for each footprint edge how far the roof runs past it.
# The eave, if it comes back, is added AFTER partitioning, never before.
# Partitioning a grown outline was tried and is wrong -- 6.6% to 18.8% of roof-height points
# fall outside the LINZ footprint by up to 2 m, so roof area is understated
# everywhere -- and per-edge measurement matches the drawn outlines exactly
# (7 Anderson Heights runs 1.25 m past one long edge, 0.0 past the opposite one,
# 2.0 m past one end). But growing the outline makes face counts WORSE, in both
# the uniform and the per-edge form: with imagery cuts active, Anderson goes
# 10 -> 17 faces against its real 8 and 29 Edinburgh 4 -> 7 against 5, because
# the eave strips are then sliced by the same lines into slivers. Fixing this
# which is why the ring is now merged into the faces that already exist instead.
EAVE_MIN_EDGE_M = 1.5            # shorter edges are corner chamfers, not roof sides
EAVE_HEIGHT_SLACK_M = 0.4        # how far outside the roof's own height range still counts


# A strong imagery line is only cut if the roof actually CHANGES there.
#
# Cutting every strong line unconditionally fixed 7 Anderson Heights, whose hip
# creases the LiDAR cannot resolve, and broke 5 Isle St, which went from the 3
# faces confirmed by markup to 4. The markup note on that roof is the clue:
# its largest plane has a significant angle across it and is still one plane.
# The imagery sees a line there -- a
# seam, a stain, a shadow, a tonal band across a sloped surface -- and it is not
# a roof line.
#
# The earlier mistake was asking the LiDAR the wrong question. "Does cutting
# improve the fit" is answerable only where the LiDAR already resolves the
# feature, so it rejected Anderson's hips. "Do the two sides have different
# ORIENTATIONS" is answerable from the same coarse data, because it compares two
# large samples rather than resolving a crease: a ridge or hip turns the roof,
# a stain does not. A height step counts too -- parallel faces at different
# levels are a real edge.
LINE_MIN_TURN_DEG = 8.0       # plane orientation must change by this across the line
LINE_MIN_STEP_M = 0.20        # ...or the two sides sit at different heights
LINE_MIN_SIDE_POINTS = 30


# How much of the chord a cut would make across a cell must actually be covered
# by the detected line, before that cell is cut.
#
# THIS IS THE THING THE FILE HAS SAID WAS MISSING SINCE AUGUST: "what is missing
# is a way to cut only the stretch a crease actually covers". _cut takes an
# (angle, offset) and slices the WHOLE cell with the infinite line, so a 1.8 m
# detection divides an 11 m roof -- 107 Beach Street, a 127 m2 roof, was
# sliced by lines of 1.8, 2.0, 2.1, 3.1 and 5.5 m.
#
# The length bar in roof_line_source is a blunt version of the same idea: it
# judges a line against the whole BUILDING. This judges it against the CELL it
# is about to divide, which is the question that actually matters -- a 3 m
# crease is ample to split a 3 m dormer and absurd for a 20 m warehouse bay.
CUT_COVER_MIN = 0.55


def _reanchor(ang, off, src_poly, dst_poly):
    """An offset measured from one polygon's centroid, expressed from another's.

    THE BUG THIS FIXES, which produced the spurious lines on 107 Beach
    Street. model_lines returns offsets measured from the FOOTPRINT's
    centroid -- its docstring says so -- but _cut re-anchors whatever offset it
    is given to the centroid of the polygon it is cutting. The first cell IS the
    footprint, so the first cut lands correctly; every cell produced by that cut
    has a different centroid, so the same (ang, off) then describes a different
    absolute line in each one, and later cuts land where no crease is.

    Measured signature of the drift: coverage of the observed segment over the
    chord it would cut has p90 = 1.00 (the first-cell cuts, right frame) against
    a median of 0.00 (the drifted ones) -- 68% of 247 cuts sit below 0.55.

    A line is {p : n.(p - c) = off}. Re-expressing from src to dst centroid:
    n.(p - dst) = n.(p - src) - n.(dst - src).
    """
    a = math.radians(float(ang))
    nx, ny = -math.sin(a), math.cos(a)
    s, d = src_poly.centroid, dst_poly.centroid
    return float(off) - (nx * (d.x - s.x) + ny * (d.y - s.y))


def _covers_cell(cell, seg, ang, off):
    """Does the detected segment actually span the cut it is proposing?

    The chord is where the infinite line crosses this cell. The segment is what
    was observed. Cutting is justified when the observation covers enough of
    the chord; where it does not, this cell is simply left alone and the cut
    still applies to whichever cells the crease does run through.
    """
    from shapely.geometry import LineString
    try:
        a = math.radians(float(ang))
        nx, ny = -math.sin(a), math.cos(a)
        c = cell.centroid
        px, py = c.x + nx * float(off), c.y + ny * float(off)
        dx, dy = math.cos(a), math.sin(a)
        span = max(cell.bounds[2] - cell.bounds[0],
                   cell.bounds[3] - cell.bounds[1]) * 2.0 + 10.0
        chord = LineString([(px - dx * span, py - dy * span),
                            (px + dx * span, py + dy * span)]).intersection(cell)
    except Exception:
        return True                      # cannot tell: behave as before
    if chord.is_empty:
        return False
    clen = sum(g.length for g in getattr(chord, "geoms", [chord]))
    if clen <= 1e-6:
        return False
    try:
        observed = LineString([(seg[0], seg[1]), (seg[2], seg[3])])
        # a hand's width either side, so a crease drawn or detected slightly
        # off the fitted line still counts as covering it
        cov = chord.intersection(observed.buffer(0.6)).length
    except Exception:
        return True
    return (cov / clen) >= CUT_COVER_MIN

def _line_is_real(poly, pts, ang, off):
    """Does the roof change across this line, or is it only visible in the image?"""
    parts = _cut(poly, ang, off)
    if len(parts) != 2:
        return False
    a, b = (_points_in(parts[0], pts), _points_in(parts[1], pts))
    if len(a) < LINE_MIN_SIDE_POINTS or len(b) < LINE_MIN_SIDE_POINTS:
        return False
    pa, pb = _fit_plane_robust(a), _fit_plane_robust(b)
    if _plane_angle(pa, pb) >= LINE_MIN_TURN_DEG:
        return True
    return _step_at_join(pa, pb, parts[0], parts[1]) >= LINE_MIN_STEP_M


# The footprint can also be BIGGER than the roof, and that half was missed.
#
# On 7 Anderson Heights the roof overhangs the footprint on the upper-left
# and sits INSIDE it on the lower-left, and that is what put a panel over the
# edge of 62 Ballarat St. Measured there, three edges overshoot the real roof by
# 0.5 to 1.25 m: about 29 m2 of dead ground inside the footprint, carrying
# panels on roof that does not exist.
#
# Trimmed BEFORE partitioning, unlike the eave, because dead ground must never
# become part of a face at all.
TRIM_MAX_M = 2.0
TRIM_STEP_M = 0.25
TRIM_MIN_BAND_POINTS = 3


def trim_to_roof(footprint, pts):
    """Footprint pulled IN wherever it overshoots the roof, edge by edge."""
    if len(pts) < MIN_POINTS or footprint.is_empty:
        return footprint
    inside = _points_in(footprint, pts)
    if len(inside) < MIN_POINTS:
        return footprint
    lo, hi = np.percentile(inside[:, 2], [5, 95])
    lo -= EAVE_HEIGHT_SLACK_M
    hi += EAVE_HEIGHT_SLACK_M
    at_roof = (pts[:, 2] >= lo) & (pts[:, 2] <= hi)
    if at_roof.sum() < MIN_POINTS:
        return footprint

    coords = np.asarray(footprint.exterior.coords)
    cuts = []
    for i in range(len(coords) - 1):
        a, b = coords[i], coords[i + 1]
        seg = b - a
        length = float(np.hypot(*seg))
        if length < EAVE_MIN_EDGE_M:
            continue
        d = seg / length
        n = np.array([d[1], -d[0]])
        if footprint.contains(Point(*((a + b) / 2 + n * 0.3))):
            n = -n                       # outward
        gap = 0.0
        for step in np.arange(0.0, TRIM_MAX_M + 1e-9, TRIM_STEP_M):
            band = Polygon([a - n * step, b - n * step,
                            b - n * (step + TRIM_STEP_M), a - n * (step + TRIM_STEP_M)])
            if band.is_empty or not band.is_valid:
                break
            m = at_roof & shapely.contains_xy(band, pts[:, 0], pts[:, 1])
            if int(m.sum()) >= TRIM_MIN_BAND_POINTS:
                break                    # roof starts here
            gap = float(step + TRIM_STEP_M)
        if gap > 0:
            cuts.append(Polygon([a, b, b - n * gap, a - n * gap]))

    if not cuts:
        return footprint
    trimmed = footprint.difference(unary_union(cuts))
    if trimmed.geom_type == "MultiPolygon":
        trimmed = max(trimmed.geoms, key=lambda q: q.area)
    if (trimmed.geom_type != "Polygon" or trimmed.is_empty
            or trimmed.area < 0.5 * footprint.area):
        return footprint                 # never lose half a building to this
    return Polygon(trimmed.exterior).simplify(0.05)


# A recessed section -- a length of roof sitting BELOW the surface around it --
# has to come out as its own region before anything is cut, because no line that
# spans the whole roof can isolate it.
#
# 7 Anderson Heights has one, confirmed by markup. Measured:
# the ridge runs at 381.42 m, drops to 380.26 m across the middle, and returns
# to 381.47 m. Earlier attempts hunted for its edges as shoulders in a 1-D ridge
# profile and put the cuts in the wrong place every time. In 2-D it is simply
# the set of points below the roof's own plane envelope.
#
# Two details matter. A pitched roof's surface is the LOWER envelope of its
# planes, so the reference has to be min() over the main faces and not any one
# plane -- against a single plane the hips read as recessed too, and 78 m2 of a
# 211 m2 roof got flagged. And the depth has to be a BAND: where the surveyed
# footprint overruns the roof, the points beyond the eave are wall or ground
# sitting about 2 m down, and they connect to the real recess and swallow it.
# Restricting to 0.45-1.8 m below separates them -- overlap with the traced
# section went from IoU 0.24 to 0.55.
RECESS_MIN_DEPTH_M = 0.45
RECESS_MAX_DEPTH_M = 1.80
RECESS_CELL_M = 0.75
RECESS_MIN_AREA_M2 = 6.0
RECESS_MAX_AREA_SHARE = 0.35    # more than this is not a section, it is the roof
RECESS_MIN_POINTS = 40
RECESS_MAX_FACES = 2       # a recessed section has two faces, not a partition of its own


def _recessed_region(footprint, pts, faces):
    """The recessed section of a roof, as a rectangle in the roof's own frame.

    `faces` is a first-pass partition, used only for its planes. Returns None
    when the roof has no such section."""
    if len(faces) < 2 or len(pts) < RECESS_MIN_POINTS:
        return None
    try:
        from scipy import ndimage
    except Exception:
        return None
    planes = [pl for _poly, pl in sorted(faces, key=lambda t: -t[0].area)[:4]]
    env = np.minimum.reduce([p[0] * pts[:, 0] + p[1] * pts[:, 1] + p[2] for p in planes])
    resid = pts[:, 2] - env
    core = pts[(resid < -RECESS_MIN_DEPTH_M) & (resid > -RECESS_MAX_DEPTH_M)]
    if len(core) < RECESS_MIN_POINTS:
        return None
    minx, miny, maxx, maxy = footprint.bounds
    nx = max(2, int(np.ceil((maxx - minx) / RECESS_CELL_M)))
    ny = max(2, int(np.ceil((maxy - miny) / RECESS_CELL_M)))
    if nx * ny > 200000:
        return None
    grid = np.zeros((ny, nx), dtype=bool)
    ix = np.clip(((core[:, 0] - minx) / RECESS_CELL_M).astype(int), 0, nx - 1)
    iy = np.clip(((core[:, 1] - miny) / RECESS_CELL_M).astype(int), 0, ny - 1)
    grid[iy, ix] = True
    grid = ndimage.binary_closing(grid, structure=np.ones((3, 3), dtype=bool))
    lab, n = ndimage.label(grid, structure=np.ones((3, 3), dtype=int))
    if n == 0:
        return None
    best = max(range(1, n + 1), key=lambda k: int(np.sum(lab == k)))
    if int(np.sum(lab == best)) * RECESS_CELL_M ** 2 < RECESS_MIN_AREA_M2:
        return None
    ys, xs = np.nonzero(lab == best)
    cx = minx + (xs + 0.5) * RECESS_CELL_M
    cy = miny + (ys + 0.5) * RECESS_CELL_M
    # a rectangle in the roof's own frame: roofs are straight lines, not blobs
    from src.outline_axis import dominant_axis_deg
    ax = dominant_axis_deg(footprint)   # the walls, not the bounding rectangle
    if ax is None:
        return None
    u = np.array([np.cos(np.radians(ax)), np.sin(np.radians(ax))])
    v = np.array([-u[1], u[0]])
    c = np.array(footprint.centroid.coords[0])
    xy = np.column_stack([cx, cy]) - c
    a, b = xy @ u, xy @ v
    # Measured on both axes, NOT stretched across the roof. Extending it eave to
    # eave was tried, on a misreading of the traced markup, and it is wrong
    # twice over: the section is about 28 m2 where the full width of that roof
    # would be nearer 55, and forcing the stretched region into the two faces
    # describes gave planes fitting 50% and 43% -- worse than not modelling it.
    # The traced corners came out aligned to north rather than to the roof, so
    # that reading was an artefact of tracing the drawn line by eye.
    poly = Polygon([c + u * aa + v * bb for aa, bb in
                    ((a.min(), b.min()), (a.max(), b.min()),
                     (a.max(), b.max()), (a.min(), b.max()))])
    try:
        poly = poly.intersection(footprint)
    except Exception:
        return None
    if (poly.is_empty or poly.geom_type != "Polygon"
            or poly.area < RECESS_MIN_AREA_M2
            or poly.area > RECESS_MAX_AREA_SHARE * footprint.area):
        return None
    return poly


# Bounds on the model-proposed cutting loop. Without them a large roof with
# hundreds of predictions splits into cells faster than the loop can retire
# them: the airport took 30 minutes and stopped a 24-region build.
MAX_MODEL_CUTS = 40          # a roof has a handful of primary creases, not 200
MAX_CELLS_FROM_MODEL = 60    # past this the roof is already finely divided


def _vision_cuts_available(building_id):
    """Only take the imagery-cut path when a model has actually predicted here.

    With no prediction file this is False and the partition behaves exactly as
    it did -- the flag it replaced was a hardcoded False, so a building with no
    model output must be bit-for-bit unchanged."""
    try:
        from src.roof_line_source import has_model
        return has_model(building_id)
    except Exception:
        return False


def partition_roof(building_id, footprint, pts, imagery_ds=None, use_selected=True):
    """Surveyed footprint + point cloud -> straight-edged, plane-backed facets.

    Strong imagery lines, if imagery is supplied, are cut FIRST and without the
    point cloud getting a vote. Everywhere else in this module a cut has to earn
    itself against the LiDAR, which is right when both sensors can see the
    feature and wrong when only one can. 7 Anderson Heights is the case that
    forced it: two hipped sections whose creases are unmistakable in 0.1 m
    imagery and almost absent from a point cloud that is near-flat across the
    whole roof. Every LiDAR-scored candidate there was rejected -- correctly, by
    its own logic, since cutting did not improve a fit that was never wrong
    about height -- so the faces ran straight over both hips and the panels
    followed: two panel planes placed over a ridge where the roof drops.

    Only lines carrying enough evidence to be a primary crease qualify; see
    roof_lines.strong_roof_lines."""
    _cut_evals[0] = 0          # the budget is per building, not per process
    # CPU time, not wall time. A wall-clock deadline is stolen by whatever else
    # is running: during a district rebuild the harness measured 32 Frankton Rd
    # at 16.5% weighted fit while the same code on an idle machine reached 33%,
    # because the other workers ate its 240 seconds. Each partition runs on one
    # thread, so process CPU time measures ITS work regardless of load.
    _cut_deadline[0] = time.process_time() + min(
        CUT_TIME_BUDGET_MAX_S, max(CUT_TIME_BUDGET_S, footprint.area * CUT_TIME_PER_M2_S))
    footprint = trim_to_roof(footprint, pts)
    inside = _points_in(footprint, pts)
    if len(inside) < MIN_POINTS:
        return []

    # Imagery cuts are OFF. Measured against four drawn roofs, they are
    # actively harmful:
    #
    #                  drawn   cuts ON   cuts OFF
    #   7 Anderson         8       12         8
    #   5 Isle St          3        3         3
    #   29 Edinburgh       5        3         5
    #   2/8 Wakatipu       8        9         8
    #
    # Off matches all four exactly; on matches one. The idea is still right --
    # 7 Anderson's hip creases are unmistakable in 0.1 m imagery and nearly
    # absent from a point cloud that is flat across that roof -- but cutting a
    # whole cell with a line detected over part of it fragments the roof faster
    # than it fixes it, and the rendered result is a jumble of arbitrary
    # polygons.
    #
    # What is missing is a way to cut only the stretch a crease actually covers.
    # Clipping the cut to the detected segment's extent was tried and did not
    # help, because on this roof the creases span most of the building anyway.
    # Turned back on, but ONLY for lines a model proposed, and only where the
    # LiDAR agrees. The original failure was Hough lines cutting a whole cell on
    # evidence covering part of it, which fragmented roofs faster than it fixed
    # them. Two things are different now.
    #
    # First, the proposals come from a model trained on hand-drawn roof lines,
    # so they are proposals about ROOF CREASES rather than about tonal edges --
    # a stain, a gutter shadow and a seam all read as Hough lines and none of
    # them are folds.
    #
    # Second, and the part that makes this safe: every proposed line still has
    # to pass _line_is_real against the point cloud. The model cannot force a
    # cut. It can only draw attention to a place the LiDAR then confirms is a
    # fold, which is exactly the case the partition misses on its own -- 19.5%
    # of panels currently straddle a drawn line.
    USE_IMAGERY_CUTS = _vision_cuts_available(building_id)

    cells = [footprint]

    # SUBDIVIDE BY SEGMENTS FIRST, and only fall back to half-plane cutting.
    #
    # A roof line is a segment with extent; _cut below slices a whole cell with
    # its infinite extension. That difference is the whole reason imagery cuts
    # were once turned off as "actively harmful" -- and it applies to the
    # model's lines exactly as it did to Hough's, because the geometry of the
    # cut is what fragments the roof, not where the line came from.
    #
    # Measured on 28 marked roofs, feeding drawn lines to _cut made agreement
    # WORSE (lines found 84.1% -> 82.6%, edges never drawn 22.3% -> 27.7%). This path polygonizes the segments against the roof
    # boundary instead, so no line is extrapolated past where it was seen.
    # THE FACES THE LABELLING TOOL ALREADY DERIVED.
    #
    # roof_labels.json carries a `faces` array per roof: rings the tool built
    # from the drawn lines in the browser, with an area and a usable flag, and
    # nothing has ever read them. Re-deriving faces from the lines in Python
    # was the wrong instinct -- it cost a sealing rule, a noding bug and two
    # measured regressions to reconstruct something already computed. It is
    # also the construction on screen when the roof was marked finished, so a
    # second derivation risks building geometry that was never approved.
    _lf = []
    try:
        _lf = facets_from_drawn_faces(building_id, footprint, pts)
    except Exception as exc:
        print(f"  roof_partition: drawn faces unavailable ({exc!r})", flush=True)
    if _lf:
        return _lf
    # the selector's winner ranks below the manual markup and above everything
    # fitted here -- same construction, weaker author
    try:
        _sf = facets_from_selected_faces(building_id, footprint, pts) if use_selected else []
    except Exception as exc:
        print(f"  roof_partition: selected faces unavailable ({exc!r})",
              flush=True)
        _sf = []
    if _sf:
        # COVERAGE IS GUARANTEED, quality gates or not. Dropping a garbage
        # machine face used to leave its area EMPTY: a pyramid whose two sunny
        # faces had failed the one-plane gate shipped panels only on the
        # shady side. The
        # residue now goes back to the LiDAR partition, whose facets carry no
        # from_selected flag and so face every downstream drop as usual.
        _sf.extend(residual_fill(building_id, footprint, pts, _sf))
        return _sf

    # A FLAT ROOF HAS NO FOLDS, so imagery cuts on one are noise.
    #
    # Four town-centre roofs were flagged with roof lines way off on a very
    # simple roof. They are flat. #4734914 varies 0.87 m across
    # 224 m2 and fits a plane at 0.3 degrees; #4734913 1.22 m at 1.0; #4734994
    # at 3.7. The build gave them 4, 11 and 7 facets pitched at 8-10 degrees,
    # with hips that do not exist.
    #
    # The detector is not wrong to fire on them -- a flat commercial roof is
    # covered in real lines: parapets, plant, membrane seams, shadow edges.
    # None is a fold. Retraining does not help, and was measured: on 5 of those
    # 7 roofs a detector retrained on 50 more marked roofs produced an identical
    # result, because the lines were never the binding constraint.
    #
    # Slope separates these cleanly from roofs that do need cutting -- the hips
    # drawn there fit at 9.6-12.5 degrees against 0.3-3.7 here.
    #
    # Only for geometry nobody has drawn: this sits after the drawn-faces return
    # above, so a flat roof that HAS been marked keeps every drawn face. #4735237 is
    # exactly that -- 1,688 m2 at 1.6 degrees with 23 drawn faces.
    _flat = False
    if imagery_ds is not None and USE_IMAGERY_CUTS:
        try:
            _in = _points_in(footprint, pts)
            if len(_in) >= MIN_POINTS:
                _pl = _fit_plane_robust(_in)
                if _pl is not None:
                    _sl, _ = _slope_aspect(_pl)
                    _flat = _sl < FLAT_ROOF_MAX_SLOPE_DEG
        except Exception:
            _flat = False

    if imagery_ds is not None and USE_IMAGERY_CUTS and not _flat:
        # NOT a bare except. A rewrite of roof_outline above once deleted
        # _line_is_real while leaving this call site, and a broad except turned
        # that into "imagery cuts silently do nothing" -- the measurements looked
        # plausible and were meaningless. Import and geometry failures are the
        # only ones worth tolerating here.
        try:
            # Via roof_line_source so a vision model can propose these
            # instead. With no model prediction on disk this is the same call
            # it always was -- see that module's header for the fusion rule.
            # every model line, not just the long ones: a 2 m dormer cliff is
            # exactly the fold that gets missed, and the LiDAR gate below is
            # what keeps a short proposal honest
            from src.roof_line_source import model_lines
            proposed = model_lines(building_id, footprint) or []
            # CAP THE PROPOSALS. Each accepted cut splits cells, and every
            # later line is then tested against every cell, so the work grows
            # multiplicatively. Uncapped this killed the airport (#4722059):
            # 30 minutes on one building and the region watchdog stopped the
            # whole build. A roof does not have hundreds of primary creases --
            # keep the longest, most confident ones, which are the ones worth
            # cutting on anyway.
            # each entry carries its own segment, so the two can never fall out
            # of step -- pairing them by index across two calls did exactly that
            proposed.sort(key=lambda t: -(t[2] * t[3]))     # length x score
            proposed = proposed[:MAX_MODEL_CUTS]
            for t in proposed:
                ang, off, _ln, _sc = t[0], t[1], t[2], t[3]
                seg = t[4] if len(t) > 4 else None
                if len(cells) >= MAX_CELLS_FROM_MODEL:
                    break        # already finely divided; stop before it runs away
                nxt = []
                for c in cells:
                    # The offset arrived measured from the FOOTPRINT's centroid;
                    # everything below re-anchors to the polygon it is given, so
                    # it has to be converted per cell or the cut drifts. See
                    # _reanchor.
                    off_c = _reanchor(ang, off, footprint, c)
                    # THE IMAGERY SAYS WHERE THE LINE IS; THE LIDAR ONLY SAYS
                    # HOW STEEP THE FACES ARE.
                    #
                    # The image is what tells you the roof lines; the LiDAR
                    # tells you slope. _line_is_real asks the point
                    # cloud whether the roof changes across a proposed line, and
                    # at 4.9 returns/m2 on a shallow roof it usually cannot tell
                    # -- so it vetoes real creases. On #4734696 three lines
                    # survived the score and length bars and it passed exactly
                    # one, which is why loosening those bars from 0.90/0.35 to
                    # 0.30/0.08 moved the lines used from 3 to 20 and left the
                    # facets identical at 5.
                    #
                    # So a confident, long imagery line now cuts on its own
                    # authority. The LiDAR still fits every resulting facet's
                    # plane, which is the half of the job it can actually do.
                    ok = (LINES_LEAD
                          or _line_is_real(c, _points_in(c, inside), ang, off_c))
                    # ...and the observation has to actually span this cell.
                    # Without this a crease seen on one bay of a roof cuts
                    # every bay, which is the fragmentation the note above the
                    # imagery-cut block has described since August.
                    if ok and seg is not None and not _covers_cell(c, seg, ang, off_c):
                        ok = False
                    parts = _cut(c, ang, off_c) if ok else []
                    nxt.extend(parts if len(parts) >= 2 else [c])
                cells = nxt
        except (ImportError, ValueError, AttributeError) as exc:
            print(f"  roof_partition: imagery cuts unavailable ({exc!r})", flush=True)
            cells = [footprint]

    faces = []
    for cell in cells:
        # ONE FACE PER CELL THE IMAGERY CUT OUT.
        #
        # The image is what tells you the roof lines; the LiDAR tells you
        # slope. Cutting on imagery lines and then running RANSAC
        # inside each cell hands the boundaries straight back to the point
        # cloud -- the cuts happen (thousands of splits on these roofs) and the
        # edges still land where RANSAC put them, which is why loosening the
        # line bars from 0.90/0.35 to 0.30/0.08 took the lines used from 3 to 20
        # and left the facets identical.
        #
        # So when the imagery has divided the roof, each cell IS a face and the
        # LiDAR only fits its plane. _partition returns (polygon, plane) tuples,
        # not dicts -- the dicts are built further down, and appending one here
        # broke _recessed_region with a KeyError.
        if LINES_LEAD and len(cells) > 1:
            _sub = _points_in(cell, inside)
            _pl = _fit_plane_robust(_sub) if len(_sub) >= MIN_POINTS_PER_FACE else None
            if _pl is not None:
                faces.append((Polygon(cell.exterior,
                                      [r for r in cell.interiors]), _pl))
                continue
        faces.extend(_partition(cell, _points_in(cell, inside)))
    if not faces:
        return []

    # Second pass: if the first one reveals a recessed section, partition the
    # section and the roof around it separately. A cut that spans the region can
    # never isolate something in the middle of it, so this cannot be done by
    # offering another candidate to _best_cut -- it has to change what is being
    # cut. Only re-run when a section is actually found, so ordinary roofs pay
    # one plane-envelope evaluation and nothing else.
    recess = _recessed_region(footprint, inside, faces)
    if recess is not None:
        rest = footprint.difference(recess)
        pieces = [recess] + [q for q in getattr(rest, "geoms", [rest])
                             if isinstance(q, Polygon) and q.area >= MIN_PIECE_M2]
        if len(pieces) >= 2:
            regrown = []
            for piece in pieces:
                if piece is recess:
                    # A middle recession is two four-sided faces joined in
                    # the middle. A budget
                    # of two allows exactly one cut -- the line where they join.
                    # Unbudgeted, the recursion split the section into four.
                    regrown.extend(_partition(piece, _points_in(piece, inside),
                                              budget=[RECESS_MAX_FACES]))
                else:
                    regrown.extend(_partition(piece, _points_in(piece, inside)))
            if regrown:
                faces = regrown

    faces = _merge_bridgeable(faces, inside)

    # Step risers on stepped houses remain an OPEN problem, deliberately.
    # 26 Panorama Terrace carries 36.8 m2 of 42-44 degree strips between its
    # near-flat bands, and every local-geometry rule tried on 29 Aug also
    # deleted a real roof somewhere else. The measurements, so this is not
    # retried blind: (1) fit cannot reject a wall -- Panorama's risers fit 89%,
    # a wall is a perfect plane. (2) slope + short downhill run also matches
    # small real gables: 4725529 is a genuine 44-degree pair with a 2.9 m run
    # and 4734699 an entire 39-degree house. (3) "every neighbour much flatter"
    # fails because the risers touch a smeared 24-degree transition face.
    # (4) requiring a candidate pair to share a ridge does not separate them:
    # Panorama's two strips SHARE a 13.4 m edge at the top of both, exactly like
    # a gable pair -- at 0.42 m point spacing a smeared step edge is
    # geometrically a small steep roof. The remaining signal is imagery: a real
    # gable shows a sunlit/shaded pair, a step shows a shadow line.

    # NO eave extension: roof beyond the LINZ footprint stays out of the
    # model. It was also placing panels on air --
    # 45 Camp St showed panels overlapping the edge 'floating with nothing
    # underneath them', because a face grown past the footprint carries its
    # panel grid with it. (_extend_to_eave, removed 24 Sep 2026, is in git history.)

    out = []
    for poly, plane in faces:
        if poly.area < MIN_FACET_M2:
            continue
        sub = _points_in(poly, inside)
        slope, aspect = _slope_aspect(plane)
        if slope > config.MAX_ROOF_SLOPE_DEG:
            continue
        if slope >= STEEP_FACE_DEG and _inlier_fraction(sub, plane) < STEEP_FACE_MIN_FIT:
            continue        # steep AND not a plane: a wall, not a roof face
        out.append({
            "building_id": building_id,
            "geometry": Polygon(poly.exterior, [r for r in poly.interiors]),
            "plane_a": plane[0], "plane_b": plane[1], "plane_c": plane[2],
            "slope_deg": slope, "aspect_deg": aspect,
            "area_m2": float(poly.area), "point_count": int(len(sub)),
        })
    return out
