#!/usr/bin/env python3
"""
Simplify 2D  (simplify_2d.py)

Simplifies small curves in 2D details in Archicad (for example, window and
curtain-wall details imported from DWG), so that complex profiles and library
parts built from them have far fewer polygons.

  - Clean fillets (up to 100°, radius up to 5 mm): sharp corner.
  - Other small curves (hooks, rounded tips, serrations): straight segments,
    simplified to within 0.2 mm of the original shape.
  - Hatches lead: lines lying on a hatch outline are redrawn from the cleaned
    hatch (one polyline per outline, by default).
  - Loose lines, arcs and splines follow the same rules.

By default the result is drawn in a new worksheet, "Simplify 2D <view name>",
and the original drawing is not changed (see SETTINGS["output"]).

Uses the Archicad JSON API + Tapir. Python 3 standard library only.
Changes nothing without --apply (and asks for confirmation).

Usage (Terminal, with Archicad open and no action in progress):
    python3 simplify_2d.py               # dry run: summary only, nothing changes
    python3 simplify_2d.py --selection   # dry run on the current selection only
    python3 simplify_2d.py --apply       # apply the changes
    python3 simplify_2d.py --help        # all options
"""

# --------------------------------------------------------------------------
# Presets offered in the Archicad dialog (edit here to change them for the
# whole office). radius and shape_tol in mm, corner_max in degrees.
# --------------------------------------------------------------------------
PRESETS = {
    "Fine":     {"radius": 3.0, "shape_tol": 0.1, "corner_max": 100},
    "Standard": {"radius": 5.0, "shape_tol": 0.2, "corner_max": 100},
    "Coarse":   {"radius": 8.0, "shape_tol": 0.5, "corner_max": 110},
}

# Office settings: used by the Archicad dialogs and as the Terminal defaults.
SETTINGS = {
    "circles": "keep",          # small full circles: "keep" or "delete"
    "contours": "polyline",     # redrawn hatch outlines: "polyline" or "lines"
    "hatches_only": False,      # True: change hatches only, leave all lines alone
    "output": "worksheet",      # "worksheet": draw the result in a new worksheet
                                #   (ID "Simplify 2D", named after the view); the original is not changed.
                                # "in place": change the drawing itself.
}

import argparse
import json
import math
import sys
import time
import urllib.request
from collections import defaultdict

# --------------------------------------------------------------------------
# Archicad connection
# --------------------------------------------------------------------------

class Archicad:
    def __init__(self, port):
        self.url = f"http://127.0.0.1:{port}"

    def _post(self, payload):
        data = json.dumps(payload).encode("utf-8")
        warned = False
        for _ in range(120):
            req = urllib.request.Request(self.url, data=data,
                                         headers={"Content-Type": "application/json"})
            with urllib.request.urlopen(req, timeout=600) as r:
                resp = json.loads(r.read().decode("utf-8"))
            err = resp.get("error") or {}
            if not resp.get("succeeded", False) and err.get("code") == 4001:
                # Archicad busy with a user action (active tool, selection in
                # progress, open dialog): wait instead of failing.
                if not warned:
                    print("  Archicad is busy. Press Esc in Archicad and don't touch "
                          "it until the script finishes…")
                    warned = True
                time.sleep(1)
                continue
            break
        if not resp.get("succeeded", False):
            raise RuntimeError(f"Archicad refused: {json.dumps(resp.get('error', resp))[:500]}")
        return resp.get("result", {})

    def api(self, command, parameters=None):
        p = {"command": command}
        if parameters is not None:
            p["parameters"] = parameters
        return self._post(p)

    def tapir(self, command, parameters=None):
        res = self.api("API.ExecuteAddOnCommand", {
            "addOnCommandId": {"commandNamespace": "TapirCommand", "commandName": command},
            "addOnCommandParameters": parameters or {},
        })
        out = res.get("addOnCommandResponse", res)
        if isinstance(out, dict) and "error" in out and len(out) == 1:
            raise RuntimeError(f"Tapir {command}: {out['error']}")
        return out

    def tapir_available(self, command):
        try:
            r = self.api("API.IsAddOnCommandAvailable", {
                "addOnCommandId": {"commandNamespace": "TapirCommand", "commandName": command}})
            return bool(r.get("available", False))
        except Exception:
            return False


def eid(guid):
    return {"elementId": {"guid": guid}}


def chunks(seq, n):
    for i in range(0, len(seq), n):
        yield seq[i:i + n]

# --------------------------------------------------------------------------
# Geometry
# --------------------------------------------------------------------------

def sub(a, b): return (a[0] - b[0], a[1] - b[1])
def add(a, b): return (a[0] + b[0], a[1] + b[1])
def mul(a, s): return (a[0] * s, a[1] * s)
def dot(a, b): return a[0] * b[0] + a[1] * b[1]
def cross(a, b): return a[0] * b[1] - a[1] * b[0]
def norm(a): return math.hypot(a[0], a[1])
def dist(a, b): return norm(sub(a, b))

def unit(a):
    n = norm(a)
    return (a[0] / n, a[1] / n) if n > 0 else (0.0, 0.0)

def rot(v, ang):
    c, s = math.cos(ang), math.sin(ang)
    return (v[0] * c - v[1] * s, v[0] * s + v[1] * c)

def pt(d): return (float(d["x"]), float(d["y"]))
def js(p): return {"x": p[0], "y": p[1]}


def corner(P, d_in, Q, d_out, spike):
    """Intersection of the line arriving at P (direction d_in) with the line
    leaving Q (direction d_out). Returns ('corner', X) or ('chord', reason)."""
    d1, d2 = unit(d_in), unit(d_out)
    den = cross(d1, d2)
    if abs(den) < 1e-6:                       # parallel: rib end, etc.
        return ("chord", "parallel")
    w = sub(Q, P)
    t1 = cross(w, d2) / den                   # X = P + t1*d1
    t2 = cross(w, d1) / den                   # X = Q + t2*d2
    if t1 < -1e-9 or t2 > 1e-9:               # corner would be on the wrong side
        return ("chord", "direction")
    X = add(P, mul(d1, t1))
    if max(dist(X, P), dist(X, Q)) > spike:   # corner too far away
        return ("chord", "spike")
    return ("corner", X)


def seg_radius(A, B, bulge):
    c = dist(A, B)
    s = math.sin(abs(bulge) / 2.0)
    return float("inf") if s < 1e-12 else c / (2.0 * s)


def seg_dir_start(A, B, bulge):
    ch = unit(sub(B, A))
    return ch if bulge == 0 else rot(ch, -bulge / 2.0)


def seg_dir_end(A, B, bulge):
    ch = unit(sub(B, A))
    return ch if bulge == 0 else rot(ch, bulge / 2.0)

# --- Polygons/polylines: list of points + arc angle per segment ------------

def from_api(coords, arcs, tol):
    """Archicad format -> (points, bulges, closed, odd_arcs)."""
    C = [pt(c) for c in coords]
    n = len(C)
    b = [0.0] * max(n - 1, 0)
    odd = 0
    for a in arcs or []:
        i, j, ang = int(a["begIndex"]), int(a["endIndex"]), float(a["arcAngle"])
        if j == i + 1 and 0 <= i < n - 1:
            b[i] = ang
        elif i == j + 1 and 0 <= j < n - 1:
            b[j] = -ang
        else:
            odd += 1
    closed = n >= 3 and dist(C[0], C[-1]) < tol
    if closed:
        V, B = C[:-1], b[:]                    # segment k: V[k] -> V[(k+1)%m]
    else:
        V, B = C[:], b[:] + [0.0]              # last point has no segment
    # drop zero-length segments
    P, Bl = [V[0]], [B[0]]
    for k in range(1, len(V)):
        if dist(V[k], P[-1]) < 1e-9:
            Bl[-1] = B[k]
        else:
            P.append(V[k]); Bl.append(B[k])
    if closed and len(P) > 1 and dist(P[-1], P[0]) < 1e-9:
        P.pop(); Bl.pop()
    return P, Bl, closed, odd


def to_api(P, Bl, closed):
    """Polyline format: closed polylines repeat the first point at the end."""
    if closed:
        coords = [js(p) for p in P] + [js(P[0])]
        nseg = len(P)
    else:
        coords = [js(p) for p in P]
        nseg = len(P) - 1
    arcs = [{"begIndex": k, "endIndex": k + 1, "arcAngle": Bl[k]}
            for k in range(nseg) if Bl[k] != 0]
    return coords, arcs


PARTIAL = []                           # hatches whose outline is only partly drawn as lines


def to_api_hatch(P, Bl):
    """Format Archicad accepts when WRITING a hatch outer outline: the first point
    is not repeated at the end; the closing segment's arc uses endIndex = n.
    (Confirmed on Archicad 29 + Tapir 1.8.)"""
    n = len(P)
    coords = [js(p) for p in P]
    arcs = [{"begIndex": k, "endIndex": k + 1, "arcAngle": Bl[k]}
            for k in range(n) if Bl[k] != 0]
    return coords, arcs


# Rules (radians/metres; set in process() from the command-line options).
CFG = {"corner_max": math.radians(100), "spike_r": 2.0, "shape_tol": 0.0002,
       "facet": math.radians(45)}


def arc_center(A, B, bulge):
    """Centre and radius of the arc A->B with angle 'bulge' (Archicad convention:
    positive = left turn)."""
    r = seg_radius(A, B, bulge)
    t0 = seg_dir_start(A, B, bulge)
    n0 = rot(t0, math.pi / 2)
    C = add(A, mul(n0, r if bulge > 0 else -r))
    return C, r


def arc_inner_points(A, B, bulge, step):
    """Intermediate points to split the arc A->B into segments of ~step rad."""
    n = max(1, int(math.ceil(abs(bulge) / step - 1e-9)))
    if n == 1:
        return []
    C, _ = arc_center(A, B, bulge)
    v = sub(A, C)
    return [add(C, rot(v, bulge * i / n)) for i in range(1, n)]


def rdp(pts, tol):
    """Douglas-Peucker: indices to keep (always the first and the last)."""
    keep = {0, len(pts) - 1}
    stack = [(0, len(pts) - 1)]
    while stack:
        a, b = stack.pop()
        if b - a < 2:
            continue
        A, B = pts[a], pts[b]
        ab = sub(B, A); L = norm(ab)
        best, bi = -1.0, None
        for i in range(a + 1, b):
            dd = abs(cross(ab, sub(pts[i], A))) / L if L > 0 else dist(pts[i], A)
            if dd > best:
                best, bi = dd, i
        if best > tol:
            keep.add(bi); stack += [(a, bi), (bi, b)]
    return sorted(keep)


def simplify_runs(P, Bl, closed, hard, tol):
    """Douglas-Peucker on the runs between hard vertices. Vertices next to
    remaining arcs are also hard."""
    m = len(P)
    def kp_(p): return (round(p[0], 9), round(p[1], 9))
    isH = []
    for i in range(m):
        prev_b = Bl[i - 1] if (closed or i > 0) else 0.0
        isH.append(kp_(P[i]) in hard or Bl[i] != 0 or prev_b != 0
                   or (not closed and i in (0, m - 1)))
    if not any(isH):
        isH[0] = True
    H = [i for i in range(m) if isH[i]]
    keep = set(H)
    runs = list(zip(H, H[1:])) + ([(H[-1], H[0] + m)] if closed else [])
    for a, b in runs:
        idx = list(range(a, b + 1))
        pts = [P[i % m] for i in idx]
        for j in rdp(pts, tol):
            keep.add(idx[j] % m)
    order = sorted(keep)
    return [P[i] for i in order], [Bl[i] for i in order]


def simplify_path(P, Bl, closed, rmax, spike, stats):
    """Removes arcs with radius <= rmax. Returns (P, Bl, changed).
    Clean fillet (one arc, or several in a row turning the same way, up to
    corner_max in total, corner within spike_r radii): sharp corner at the
    intersection of the neighbouring tangents.
    Everything else (hooks, rounded tips, grooves, serrations, non-tangent
    curves): straight segments, then Douglas-Peucker within shape_tol."""
    P, Bl = list(P), list(Bl)
    m = len(P)
    nseg = m if closed else m - 1
    small = [Bl[k] != 0 and seg_radius(P[k], P[(k + 1) % m], Bl[k]) <= rmax
             for k in range(nseg)]
    if nseg > 0 and all(Bl[k] != 0 for k in range(nseg)):
        if any(small):
            stats["ring_all_curves"] += 1     # circle/oval: left as it is
        return P, Bl, False
    changed = False
    n_small = sum(small)
    # "Hard" vertices: those that were already straight corners in the original
    # (both neighbouring segments straight) and the sharp corners created
    # between two straight lines. The final simplification never removes them.
    def kp_(p): return (round(p[0], 9), round(p[1], 9))
    hard = set()
    for i in range(m):
        prev_b = Bl[i - 1] if (closed or i > 0) else 0.0
        if Bl[i] == 0 and prev_b == 0:
            hard.add(kp_(P[i]))

    def is_small(i):
        mm = len(P)
        return Bl[i] != 0 and seg_radius(P[i], P[(i + 1) % mm], Bl[i]) <= rmax

    def facet(k, ke):
        mm = len(P)
        newP, newB = P[:k], Bl[:k]
        for i in range(k, ke + 1):
            newP.append(P[i]); newB.append(0.0)
            for q in arc_inner_points(P[i], P[(i + 1) % mm], Bl[i], CFG["facet"]):
                newP.append(q); newB.append(0.0)
        P[:] = newP + P[ke + 1:]
        Bl[:] = newB + Bl[ke + 1:]
        stats["faceted_arcs"] += ke - k + 1

    # Each pass removes at least one small arc.
    for _ in range(n_small + 5):
        m = len(P)
        nseg = m if closed else m - 1
        k = next((i for i in range(nseg) if is_small(i)), None)
        if k is None:
            break
        changed = True
        if closed:
            # go back to the start of the chain and rotate the ring so that
            # the segment before the chain is segment 0
            n_back = 0
            while n_back < m and is_small((k - 1) % m):
                k = (k - 1) % m; n_back += 1
            if n_back >= m:
                break
            r0 = (k - 1) % m
            P[:] = P[r0:] + P[:r0]; Bl[:] = Bl[r0:] + Bl[:r0]
            k = 1
        ke = k
        while ke + 1 < nseg and is_small(ke + 1):
            ke += 1

        # Only a chain that always turns the same way is a fillet split into
        # several arcs. With alternating turns (hooks, serrations, S-curves)
        # one arc is handled at a time.
        if ke > k and not (all(b > 0 for b in Bl[k:ke + 1]) or all(b < 0 for b in Bl[k:ke + 1])):
            ke = k
        total = abs(sum(Bl[k:ke + 1]))

        def try_corner(k, ke):
            """Sharp corner for the chain k..ke, if it is a clean fillet: corner
            on the right side and within CFG['spike_r'] radii of the arc ends."""
            m_ = len(P); nseg_ = m_ if closed else m_ - 1
            ns = ke + 1
            if k - 1 < 0 or ns >= nseg_ or (closed and ns % m_ == 0) or (closed and m_ < 4):
                return None
            A, E = P[k], P[ke + 1]
            d_in = seg_dir_end(P[k - 1], P[k], Bl[k - 1])
            d_out = seg_dir_start(P[ns], P[(ns + 1) % m_], Bl[ns])
            t0 = seg_dir_start(A, P[k + 1], Bl[k]); t1 = seg_dir_end(P[ke], E, Bl[ke])
            if dot(unit(d_in), t0) < 0.985 or dot(unit(d_out), t1) < 0.985:
                stats["non_tangent"] += 1       # statistics only
            r_ = max(seg_radius(P[i], P[(i + 1) % m_], Bl[i]) for i in range(k, ke + 1))
            kind, val = corner(A, d_in, E, d_out, min(spike, CFG["spike_r"] * r_))
            if kind != "corner":
                stats["no_corner_" + val] += 1
                return None
            return val, ns

        res = None
        if total <= CFG["corner_max"]:
            res = try_corner(k, ke)
        if res:
            X, ns = res
            A, E = P[k], P[ke + 1]
            prev_straight, next_straight = Bl[k - 1] == 0, Bl[ns] == 0
            # Straight neighbour: extended to X. Curved neighbour: keeps its end
            # point and is joined to X by a straight piece along its tangent.
            mid_p = ([] if prev_straight else [A]) + [X] + ([] if next_straight else [E])
            mid_b = ([] if prev_straight else [0.0]) + [0.0] + ([] if next_straight else [Bl[ns]])
            P[:] = P[:k] + mid_p + P[ns + 1:]
            Bl[:] = Bl[:k] + mid_b + Bl[ns + 1:]
            stats["arc_to_corner"] += ke - k + 1
            if prev_straight and next_straight:
                hard.add(kp_(X))              # corner between two straights: keep it
        else:
            # Not a clean fillet (hook, rounded tip, groove, non-tangent curve):
            # keep the shape, in straight segments.
            facet(k, ke)
            stats["faceted_curves"] += 1
    # Large arcs that stay but barely deviate from their chord: chord.
    tolf = CFG["shape_tol"]
    m = len(P); nseg = m if closed else m - 1
    for k in range(nseg):
        if Bl[k] != 0:
            r_ = seg_radius(P[k], P[(k + 1) % m], Bl[k])
            if r_ * (1 - math.cos(abs(Bl[k]) / 2)) <= tolf:
                Bl[k] = 0.0; changed = True; stats["nearly_straight_arc"] += 1
    if changed and tolf > 0:
        n0 = len(P)
        P, Bl = simplify_runs(P, Bl, closed, hard, tolf)
        stats["vertices_removed"] += n0 - len(P)
    m = len(P)
    nseg = m if closed else m - 1
    stats["arcs_unresolved"] += sum(
        1 for k in range(nseg)
        if Bl[k] != 0 and seg_radius(P[k], P[(k + 1) % m], Bl[k]) <= rmax)
    return P, Bl, changed

# --------------------------------------------------------------------------
# Reading
# --------------------------------------------------------------------------

# Note: in Archicad circles are of type Arc (start angle = end angle), so
# "Circle" is not listed separately, to avoid counting them twice.
TYPES = ["Line", "Arc", "PolyLine", "Hatch", "Spline"]


def list_by_type(ac, t):
    try:
        r = ac.tapir("GetElementsByType", {"elementType": t})
    except Exception:
        try:
            r = ac.api("API.GetElementsByType", {"elementType": t})
        except Exception as e:
            print(f"  warning: could not list {t} ({e}); skipped")
            return []
    return [e["elementId"]["guid"] for e in r.get("elements", [])]


def selected_guids(ac):
    try:
        r = ac.tapir("GetSelectedElements")
    except Exception:
        r = ac.api("API.GetSelectedElements")
    lst = r.get("selectedElements") or r.get("elements") or []
    return {e["elementId"]["guid"] for e in lst}


def get_details(ac, guids):
    out = {}
    for ch in chunks(guids, 400):
        params = {"elements": [eid(g) for g in ch],
                  "fields": ["type", "floorIndex", "layerIndex", "details"]}
        try:
            r = ac.tapir("GetDetailsOfElements", params)
        except Exception:
            params.pop("fields")
            r = ac.tapir("GetDetailsOfElements", params)
        for g, d in zip(ch, r.get("detailsOfElements", [])):
            if "error" not in d:
                out[g] = d
    return out

# --------------------------------------------------------------------------
# Processing
# --------------------------------------------------------------------------

def process(ac, args):
    rmax = args.radius / 1000.0
    CFG["corner_max"] = math.radians(args.corner_max)
    CFG["spike_r"] = args.spike_r
    CFG["shape_tol"] = args.shape_tol / 1000.0
    CFG["facet"] = math.radians(args.facet)
    spike = args.spike / 1000.0
    tol = args.tol / 1000.0
    stats = defaultdict(int)
    skipped = []                       # (guid, reason)

    ids = {t: list_by_type(ac, t) for t in TYPES}
    if args.selection:
        sel = selected_guids(ac)
        if not sel:
            sys.exit("Nothing is selected in Archicad.")
        ids = {t: [g for g in v if g in sel] for t, v in ids.items()}
    for t in TYPES:
        stats[f"n_{t}"] = len(ids[t])
    all_ids = [g for t in TYPES for g in ids[t]]

    det = get_details(ac, ids["Line"] + ids["Arc"] + ids["Spline"]
                      + ids["PolyLine"] + ids["Hatch"])

    # ---------- 1. Hatches: arcs in the outlines ----------
    poly_updates, hatch_updates = [], []
    poly_final = {}                    # guid -> [pts, bulges, closed, changed]
    hatch_rings = []                   # hatch rings that changed
    if args.hatches_only:
        for t in ("Line", "Arc", "PolyLine", "Spline"):
            ids[t] = []
    for g in ids["Hatch"]:
        d = det.get(g)
        if not d:
            continue
        dd = d["details"]
        rings = [(dd["coordinates"], dd.get("arcs"))]
        for h in dd.get("holes") or []:
            rings.append((h.get("polygonOutline") or h.get("polygonCoordinates") or [],
                          h.get("polygonArcs") or h.get("arcs")))
        new, any_ch, bad = [], False, None
        ring_rec = []
        for coords, arcs in rings:
            P, Bl, closed, odd = from_api(coords, arcs, tol)
            if odd or not closed:
                bad = "irregular hatch outline"; break
            P2, B2, ch = simplify_path(P, Bl, True, rmax, spike, stats)
            ring_rec.append((P, Bl, P2, B2, ch))
            if not ch:                         # untouched ring: same geometry
                new.append(to_api_hatch(P, Bl))
                continue
            if len(P2) < 3:
                bad = "degenerate hatch"; break
            any_ch = True
            new.append(to_api_hatch(P2, B2))
        if bad:
            skipped.append((g, bad)); continue
        for (P, Bl, P2, B2, ch) in ring_rec:
            if ch:
                hatch_rings.append({"hatch": g, "orig": (P, Bl), "new": (P2, B2)})
        if any_ch:
            spec = {"coordinates": new[0][0], "arcs": new[0][1],
                    # Holes, unlike the outer outline, must repeat the first point
                    # at the end; without it Archicad drops the hole's last vertex
                    # (confirmed on Archicad 29 + Tapir 1.8).
                    "holes": [{"polygonOutline": c + [c[0]], "polygonArcs": a} for c, a in new[1:]]}
            hatch_updates.append({"elementId": {"guid": g},
                                  "details": {"typeSpecificDetails": spec}})

    # ---------- 1b. Lines on hatch outlines ----------
    # Lines, arcs, splines and polylines lying on the ORIGINAL outline of a
    # hatch that changed are removed and the outline is redrawn from the
    # cleaned hatch, so lines and hatches match exactly.
    contour_delete, contour_lines, contour_arcs = [], [], []
    contour_poly_updates, contour_new_polys = [], []
    if hatch_rings and not args.hatches_only and not args.no_contours:
        tolc = args.contour_tol / 1000.0
        cellc = 0.002
        grid = defaultdict(list)       # cell -> [(ring, a, b)]
        perim = []

        def ring_chords(P, Bl, closed=True):
            m = len(P); out = []
            for k in range(m if closed else m - 1):
                A, B = P[k], P[(k + 1) % m]
                if Bl[k] == 0:
                    out.append((A, B)); continue
                pts = [A] + arc_inner_points(A, B, Bl[k], math.radians(2)) + [B]
                out += list(zip(pts[:-1], pts[1:]))
            return out

        for ri, rr in enumerate(hatch_rings):
            ch_ = ring_chords(*rr["orig"])
            perim.append(sum(dist(a, b) for a, b in ch_))
            for a, b in ch_:
                x0 = int(math.floor((min(a[0], b[0]) - tolc) / cellc))
                x1 = int(math.floor((max(a[0], b[0]) + tolc) / cellc))
                y0 = int(math.floor((min(a[1], b[1]) - tolc) / cellc))
                y1 = int(math.floor((max(a[1], b[1]) + tolc) / cellc))
                for cx in range(x0, x1 + 1):
                    for cy in range(y0, y1 + 1):
                        grid[(cx, cy)].append((ri, a, b))

        def seg_dist(p, a, b):
            ab = sub(b, a); L2 = dot(ab, ab)
            t = 0.0 if L2 == 0 else max(0.0, min(1.0, dot(sub(p, a), ab) / L2))
            return dist(p, add(a, mul(ab, t)))

        def rings_near(p):
            c = (int(math.floor(p[0] / cellc)), int(math.floor(p[1] / cellc)))
            return {ri for (ri, a, b) in grid.get(c, []) if seg_dist(p, a, b) <= tolc}

        def samples(g):
            d = det.get(g)
            if not d:
                return None, 0.0
            t = d["type"]; dd = d["details"]
            if t == "Line":
                a, b = pt(dd["begCoordinate"]), pt(dd["endCoordinate"])
                return [a, mul(add(a, b), 0.5), b], dist(a, b)
            if t == "Arc":
                if abs(float(dd.get("ratio", 1) or 1) - 1) > 1e-6:
                    return None, 0.0
                O, r = pt(dd["origin"]), float(dd["radius"])
                b0, e0 = float(dd["begAngle"]), float(dd["endAngle"])
                rot0 = float(dd.get("angle", 0))
                sw = (e0 - b0) % (2 * math.pi) or 2 * math.pi
                ang = [b0 + rot0 + sw * i / 6 for i in range(7)]
                return [add(O, (r * math.cos(x), r * math.sin(x))) for x in ang], r * sw
            if t == "Spline":
                q = [pt(c) for c in dd.get("coordinates", [])]
                return q, sum(dist(a, b) for a, b in zip(q[:-1], q[1:]))
            if t == "PolyLine":
                P_, B_, cl, odd = from_api(dd["coordinates"], dd.get("arcs"), tol)
                if odd:
                    return None, 0.0
                ch_ = ring_chords(P_, B_, cl)
                q = [a for a, b in ch_] + ([ch_[-1][1]] if ch_ else [])
                return q, sum(dist(a, b) for a, b in ch_)
            return None, 0.0

        on_ring = {}                   # guid -> set of rings
        elem_len = {}
        cover = defaultdict(float)
        for t in ("Line", "Arc", "Spline", "PolyLine"):
            for g in ids[t]:
                q, L = samples(g)
                if not q:
                    continue
                common = None
                for p_ in q:
                    rs = rings_near(p_)
                    common = rs if common is None else (common & rs)
                    if not common:
                        break
                if common:
                    on_ring[g] = common
                    elem_len[g] = L
                    for ri in common:
                        cover[ri] += L

        redraw = {ri for ri in range(len(hatch_rings))
                  if perim[ri] > 0 and cover[ri] / perim[ri] >= args.coverage}
        stats["contours_redrawn"] = len(redraw)
        partial = [ri for ri in range(len(hatch_rings)) if ri not in redraw and cover[ri] > 0]
        stats["contours_partial"] = len(partial)
        PARTIAL[:] = sorted({hatch_rings[ri]["hatch"] for ri in partial})
        attrs_by_ring = defaultdict(lambda: defaultdict(int))
        gone = set()
        for g, rs in on_ring.items():
            hit = rs & redraw
            if not hit:
                continue
            gone.add(g)
            d = det[g]; a_ = d["details"]
            key = (d.get("floorIndex"), d.get("layerIndex"), a_.get("linePenIndex"),
                   json.dumps(a_.get("lineTypeId"), sort_keys=True))
            for ri in hit:
                attrs_by_ring[ri][key] += 1
        for t in ("Line", "Arc", "Spline", "PolyLine"):
            ids[t] = [g for g in ids[t] if g not in gone]

        segs = []                      # (attributes, a, b)
        if args.contours == "polyline":
            # One closed polyline per outline. If the outline was already a
            # polyline, that polyline is changed in place (keeps its group,
            # layer and other attributes); otherwise a new one is created.
            used = set()
            for ri in sorted(redraw):
                if not attrs_by_ring[ri]:
                    continue
                key = max(attrs_by_ring[ri].items(), key=lambda kv: kv[1])[0]
                P2, B2 = hatch_rings[ri]["new"]
                c_, a_ = to_api(P2, B2, True)
                cands = [g for g in gone if ri in on_ring[g] and g not in used
                         and det[g]["type"] == "PolyLine"]
                if cands:
                    g = max(cands, key=lambda x: elem_len.get(x, 0))
                    used.add(g)
                    contour_poly_updates.append({"elementId": {"guid": g}, "details": {
                        "typeSpecificDetails": {"coordinates": c_, "arcs": a_}}})
                else:
                    contour_new_polys.append((key, c_, a_))
            gone -= used
            stats["contour_polylines_changed"] = len(contour_poly_updates)
            stats["contour_polylines_new"] = len(contour_new_polys)
        contour_delete = sorted(gone)
        stats["contour_elements_deleted"] = len(contour_delete)

        for ri in (sorted(redraw) if args.contours == "lines" else []):
            if not attrs_by_ring[ri]:
                continue
            key = max(attrs_by_ring[ri].items(), key=lambda kv: kv[1])[0]
            P2, B2 = hatch_rings[ri]["new"]
            m = len(P2)
            for k in range(m):
                A, B = P2[k], P2[(k + 1) % m]
                if dist(A, B) < 1e-9:
                    continue
                if B2[k] == 0:
                    segs.append((key, A, B))
                else:                  # large curve that stays: redrawn as an arc
                    C, r = arc_center(A, B, B2[k])
                    a0 = math.atan2(A[1] - C[1], A[0] - C[0])
                    a1 = math.atan2(B[1] - C[1], B[0] - C[0])
                    if B2[k] < 0:
                        a0, a1 = a1, a0
                    contour_arcs.append((key, C, r, a0, a1))

        # merge overlapping or touching collinear pieces (also between adjacent hatches)
        groups = defaultdict(list)
        for key, A, B in segs:
            u = unit(sub(B, A))
            if u[0] < -1e-12 or (abs(u[0]) <= 1e-12 and u[1] < 0):
                u = (-u[0], -u[1]); A, B = B, A
            off = cross(u, A)
            gk = (key, round(math.atan2(u[1], u[0]), 6), round(off, 7))
            groups[gk].append((dot(u, A), dot(u, B), u, off))
        for gk, lst in groups.items():
            lst.sort()
            cur = None
            for t0, t1, u, off in lst:
                if cur and t0 <= cur[1] + 1e-8:
                    cur[1] = max(cur[1], t1)
                else:
                    if cur:
                        contour_lines.append((gk[0], cur))
                    cur = [t0, t1, u, off]
            if cur:
                contour_lines.append((gk[0], cur))
        stats["contour_lines_new"] = len(contour_lines)
        stats["contour_arcs_new"] = len(contour_arcs)

    # ---------- 1c. Other polylines: arcs inside them ----------
    for g in ids["PolyLine"]:
        d = det.get(g)
        if not d:
            continue
        dd = d["details"]
        P, Bl, closed, odd = from_api(dd["coordinates"], dd.get("arcs"), tol)
        if odd:
            skipped.append((g, "polyline with non-consecutive arcs")); continue
        P2, B2, ch = simplify_path(P, Bl, closed, rmax, spike, stats)
        if ch and len(P2) < (3 if closed else 2):
            skipped.append((g, "degenerate polyline")); continue
        poly_final[g] = [P2, B2, closed, ch]

    # ---------- 2. Loose arcs and splines between lines ----------
    # Endpoint index of real Lines and of "virtual lines" (nearly straight
    # splines, which are replaced by Lines).
    ends = defaultdict(list)           # cell -> [(id, which, P, direction_into_P)]
    cell = max(tol * 4, 1e-6)
    seg = {}                           # id -> [beg, end, attributes or None]

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

    def put(g, which, p, d):
        ends[key(p)].append((g, which, p, d))

    def attrs(d):
        a = d["details"]
        return {"floorInd": d.get("floorIndex"), "layerIndex": d.get("layerIndex"),
                "linePenIndex": a.get("linePenIndex"), "lineTypeId": a.get("lineTypeId")}

    for g in ids["Line"]:
        d = det.get(g)
        if not d:
            continue
        a, b = pt(d["details"]["begCoordinate"]), pt(d["details"]["endCoordinate"])
        if dist(a, b) < 1e-9:
            continue
        seg[g] = [a, b, None]
        put(g, "beg", a, sub(a, b))
        put(g, "end", b, sub(b, a))

    for g, (P2, B2, closed, ch) in poly_final.items():
        if closed or len(P2) < 2:
            continue
        if B2[0] == 0 and dist(P2[0], P2[1]) > 1e-9:
            put("P:" + g, "beg", P2[0], sub(P2[0], P2[1]))
        if B2[len(P2) - 2] == 0 and dist(P2[-1], P2[-2]) > 1e-9:
            put("P:" + g, "end", P2[-1], sub(P2[-1], P2[-2]))

    straight = args.straight / 1000.0
    small_splines = []                 # (guid, pts, details, radius)
    to_delete = []
    for g in ids["Spline"]:
        d = det.get(g)
        if not d:
            continue
        dd = d["details"]
        pts = [pt(c) for c in dd.get("coordinates", [])]
        if dd.get("closed") or len(pts) < 2:
            stats["spline_kept"] += 1; continue
        a, b = pts[0], pts[-1]
        ch = dist(a, b)
        if ch < 1e-9:
            stats["spline_kept"] += 1; continue
        u = unit(sub(b, a))
        sag = max(abs(cross(u, sub(q, a))) for q in pts)
        if sag <= straight:
            vid = "S:" + g
            seg[vid] = [a, b, attrs(d)]
            put(vid, "beg", a, sub(a, b))
            put(vid, "end", b, sub(b, a))
            to_delete.append(g)
            stats["spline_straight"] += 1
            continue
        mpt = pts[len(pts) // 2]
        den = 2 * cross(sub(mpt, a), sub(b, a))
        if abs(den) < 1e-18:
            stats["spline_kept"] += 1; continue
        # radius of the circle through both ends and the middle point
        rr = dist(a, mpt) * dist(mpt, b) * dist(a, b) / abs(den)
        if rr <= rmax:
            small_splines.append((g, pts, d, rr))
        else:
            stats["spline_kept"] += 1

    def near(p):
        k = key(p); res = []
        for dx in (-1, 0, 1):
            for dy in (-1, 0, 1):
                for e in ends.get((k[0] + dx, k[1] + dy), []):
                    if dist(e[2], p) <= tol:
                        res.append(e)
        return res

    line_moves = {}                    # id -> {"beg": X, "end": X}
    new_lines = []
    circles = []

    def fillet(g, Pb, Pe, nb, ne, d, tag, r_=None, sweep=None):
        """Replaces the curve g between Pb and Pe. nb/ne: tangent neighbours."""
        if not nb or not ne:
            stats[tag + "_no_neighbours"] += 1
            skipped.append((g, "curve without tangent lines at both ends"))
            return False
        if sweep is not None and sweep > CFG["corner_max"]:
            stats[tag + "_large_kept"] += 1
            skipped.append((g, "loose curve over corner-max: kept"))
            return False
        lim = spike if r_ is None else min(spike, CFG["spike_r"] * r_)
        kind, val = corner(Pb, nb[0][3], Pe, mul(ne[0][3], -1), lim)
        if kind == "corner":
            if any(which in line_moves.get(lg, {}) for (lg, which, _, _) in nb + ne):
                skipped.append((g, "neighbouring line already moved by another curve"))
                return False
            for (lg, which, _, _) in nb + ne:
                line_moves.setdefault(lg, {})[which] = val
            stats[tag + "_corner"] += 1
        else:
            new_lines.append(dict(attrs(d), begCoordinate=js(Pb), endCoordinate=js(Pe)))
            stats[tag + "_chord"] += 1
        to_delete.append(g)
        return True

    for g in ids["Arc"]:
        d = det.get(g)
        if not d:
            continue
        a = d["details"]
        r = float(a["radius"])
        ratio = float(a.get("ratio", 1) or 1)
        if r > rmax:
            continue
        b0, e0 = float(a["begAngle"]), float(a["endAngle"])
        sweep = (e0 - b0) % (2 * math.pi)
        if sweep < 1e-9 or abs(sweep - 2 * math.pi) < 1e-9:
            circles.append(g); continue
        O, rot0 = pt(a["origin"]), float(a.get("angle", 0))
        if abs(ratio - 1) > 1e-6:
            stats["arc_elliptic"] += 1

        def tang_arc(p, t):
            return [e for e in near(p) if abs(cross(unit(e[3]), t)) < 0.2]

        # A circle has a single reading. For an ellipse the angle may be
        # parametric or polar, and the ellipse may be mirrored: each reading is
        # tried until both ends find tangent lines.
        variants = [("param", 1)]
        if abs(ratio - 1) > 1e-6:
            variants = [("param", 1), ("polar", 1), ("param", -1), ("polar", -1)]
        best = None
        for conv, sy in variants:
            def tpar(ang):
                return ang if conv == "param" else math.atan2(math.sin(ang), ratio * math.cos(ang))

            def on(ang):
                t = tpar(ang)
                return add(O, rot((r * math.cos(t), sy * r * ratio * math.sin(t)), rot0))

            def tg(ang):
                t = tpar(ang)
                return unit(rot((-r * math.sin(t), sy * r * ratio * math.cos(t)), rot0))

            Pb, Pe = on(b0), on(e0)
            nb, ne = tang_arc(Pb, tg(b0)), tang_arc(Pe, tg(e0))
            if best is None:
                best = (Pb, Pe, nb, ne)
            if nb and ne:
                best = (Pb, Pe, nb, ne)
                if abs(ratio - 1) > 1e-6:
                    stats[f"ellipse_{conv}{'' if sy > 0 else '_mirrored'}"] += 1
                break
        Pb, Pe, nb, ne = best
        fillet(g, Pb, Pe, nb, ne, d, "arc", r_=r, sweep=sweep)

    for g, pts, d, rr in small_splines:
        Pb, Pe = pts[0], pts[-1]
        tb = unit(sub(pts[1], pts[0]))          # spline direction leaving Pb
        te = unit(sub(pts[-1], pts[-2]))        # spline direction arriving at Pe

        def tang_spl(p, t):
            return [e for e in near(p) if abs(dot(unit(e[3]), t)) > 0.9]

        turn = math.acos(max(-1.0, min(1.0, dot(tb, te))))
        fillet(g, Pb, Pe, tang_spl(Pb, tb), tang_spl(Pe, te), d, "spline", r_=rr, sweep=turn)

    line_updates = []
    for g, (P2, B2, closed, ch) in poly_final.items():
        mv = line_moves.get("P:" + g, {})
        if mv:
            P2 = list(P2)
            if "beg" in mv: P2[0] = mv["beg"]
            if "end" in mv: P2[-1] = mv["end"]
            ch = True
        if ch:
            c, a = to_api(P2, B2, closed)
            poly_updates.append({"elementId": {"guid": g}, "details": {
                "typeSpecificDetails": {"coordinates": c, "arcs": a}}})

    for vid, (a0, b0_, at) in seg.items():
        mv = line_moves.get(vid, {})
        a = mv.get("beg", a0)
        b = mv.get("end", b0_)
        if at is not None:                      # straight spline -> new Line
            if dist(a, b) < 1e-7:
                continue
            new_lines.append(dict(at, begCoordinate=js(a), endCoordinate=js(b)))
            continue
        if not mv:
            continue
        if dist(a, b) < 1e-7:
            skipped.append((vid, "line would have zero length")); continue
        line_updates.append({"elementId": {"guid": vid}, "details": {
            "typeSpecificDetails": {"begCoordinate": js(a), "endCoordinate": js(b)}}})

    def key_attrs(key):
        fl, la, pen, lt = key
        return {"floorInd": fl, "layerIndex": la, "linePenIndex": pen,
                "lineTypeId": json.loads(lt)}

    for key, (t0, t1, u, off) in contour_lines:
        n_ = (-u[1], u[0])             # point on the line: 'off' along the normal
        base = mul(n_, off)
        a = add(base, mul(u, t0)); b = add(base, mul(u, t1))
        new_lines.append(dict(key_attrs(key), begCoordinate=js(a), endCoordinate=js(b)))
    new_arcs = [dict(key_attrs(key), origin=js(C), radius=r, begAngle=a0, endAngle=a1)
                for key, C, r, a0, a1 in contour_arcs]
    to_delete += contour_delete
    poly_updates += contour_poly_updates
    new_polys = [dict(key_attrs(key), coordinates=c_, arcs=a_)
                 for key, c_, a_ in contour_new_polys]

    if args.circles == "delete":
        to_delete += circles
    stats["small_circles"] = len(circles)

    # ---------- Summary ----------
    print("\nInventory:")
    for t in TYPES:
        print(f"  {t:9s} {stats['n_' + t]}")
    print(f"\nMax radius {args.radius} mm | shape tolerance {args.shape_tol} mm | "
          f"endpoint tolerance {args.tol} mm")
    print("\nPlanned changes:")
    print(f"  Polylines changed .................. {len(poly_updates)}")
    print(f"  Hatches changed .................... {len(hatch_updates)}")
    print(f"    arcs -> sharp corner ............. {stats['arc_to_corner']}")
    print(f"    arcs -> straight segments ........ {stats['faceted_arcs']}  "
          f"(in {stats['faceted_curves']} curves that are not clean fillets: "
          f"{stats['no_corner_spike']} with a distant corner, "
          f"{stats['no_corner_parallel']} between parallels; the rest are hooks and tips)")
    print(f"      vertices removed by simplification: {stats['vertices_removed']}; "
          f"nearly straight large arcs -> straight: {stats['nearly_straight_arc']}")
    el = {k[8:]: v for k, v in stats.items() if k.startswith("ellipse_")}
    if el:
        print(f"      ellipses resolved by reading: {el}")
    print(f"  Loose arcs -> corner ............... {stats['arc_corner']}"
          f"  (elliptic arcs found: {stats['arc_elliptic']})")
    print(f"  Loose arcs -> chord (new line) ..... {stats['arc_chord']}")
    print(f"  Straight splines -> Line ........... {stats['spline_straight']}")
    print(f"  Small splines -> corner ............ {stats['spline_corner']}")
    print(f"  Small splines -> chord ............. {stats['spline_chord']}")
    print(f"  Lines extended ..................... {len(line_updates)}")
    print(f"  Hatch outlines redrawn ............. {stats['contours_redrawn']}  "
          f"(as {args.contours})")
    if args.contours == "polyline":
        print(f"      polylines changed in place {stats['contour_polylines_changed']}, "
              f"new polylines {stats['contour_polylines_new']}, "
              f"old elements deleted {stats['contour_elements_deleted']}")
    else:
        print(f"      new lines {stats['contour_lines_new']}, new arcs "
              f"{stats['contour_arcs_new']}, old elements deleted "
              f"{stats['contour_elements_deleted']}")
    print(f"  Outlines only partly drawn as lines (not redrawn): "
          f"{stats['contours_partial']}")
    print(f"  New lines (total) .................. {len(new_lines)}")
    print(f"  Circles <= radius .................. {len(circles)}  "
          f"({'delete' if args.circles == 'delete' else 'keep'})")
    print(f"  Elements to delete ................. {len(to_delete)}")
    print("\nNot handled (check by hand):")
    print(f"  Rings made only of curves (round holes) {stats['ring_all_curves']}")
    print(f"  Arcs left unresolved ............... {stats['arcs_unresolved']}")
    print(f"  Curved splines kept ................ {stats['spline_kept']}")
    print(f"  Curves without tangent lines ....... "
          f"{stats['arc_no_neighbours'] + stats['spline_no_neighbours']}")
    print(f"  Other skipped ...................... {len(skipped)}")
    reasons = defaultdict(int)
    for _, rsn in skipped:
        reasons[rsn] += 1
    for rsn, n in sorted(reasons.items(), key=lambda x: -x[1]):
        print(f"      {n:5d}  {rsn}")

    if args.report:
        with open(args.report, "w", encoding="utf-8") as f:
            json.dump({"stats": stats, "skipped": skipped}, f, ensure_ascii=False, indent=1)
        print(f"\nReport: {args.report}")

    summary = {
        "hatches": len(hatch_updates),
        "polylines": len(poly_updates),
        "corners": stats["arc_to_corner"] + stats["arc_corner"] + stats["spline_corner"],
        "faceted": stats["faceted_curves"],
        "lines_extended": len(line_updates),
        "new_lines": len(new_lines),
        "deleted": len(to_delete),
        "outlines": stats["contours_redrawn"],
        "partial": stats["contours_partial"],
        "skipped": len(skipped),
        "failures": 0,
    }
    if not args.apply:
        if args.show_partial:
            ac.tapir("ChangeSelectionOfElements",
                     {"addElementsToSelection": [eid(g) for g in PARTIAL]})
            print(f"{len(PARTIAL)} hatches whose outline is only partly drawn "
                  "are now selected in Archicad.")
        if skipped and args.select_skipped:
            ac.tapir("ChangeSelectionOfElements",
                     {"addElementsToSelection": [eid(g) for g, _ in skipped]})
            print("Skipped elements are now selected in Archicad.")
        print("\nDry run only. Nothing was changed. Use --apply to apply.")
        return summary

    # ---------- Apply ----------
    if args.output == "worksheet":
        print("\nDrawing in a new worksheet… Don't touch Archicad until you see 'Done'.")
        res = apply_to_worksheet(ac, all_ids, det, poly_updates + hatch_updates + line_updates,
                                 to_delete, new_lines, new_polys, new_arcs, tol)
        summary.update(res)
        if res.get("cancelled"):
            print("Cancelled. Nothing was changed.")
            return summary
        print(f"Done: worksheet '{res['worksheet']}', {res['created']} elements"
              + (f", {res['failures']} refused." if res["failures"] else "."))
        return summary
    print("\nApplying… Don't touch Archicad until you see 'Done'.")
    # Elements inside groups can only be changed with groups suspended.
    try:
        prev_susp = bool(ac.tapir("GetSuspendGroupsMode").get("suspendGroups"))
    except Exception:
        prev_susp = None
    if prev_susp is False:
        ac.tapir("SetSuspendGroupsMode", {"suspendGroups": True})
    failures = 0
    try:
        updates = poly_updates + hatch_updates + line_updates
        for batch in chunks(updates, 200):
            r = ac.tapir("SetDetailsOfElements", {"elementsWithDetails": batch})
            for item, res in zip(batch, r.get("executionResults", [])):
                if not res.get("success", True):
                    failures += 1
                    if failures <= 5:
                        print("  failed:", item["elementId"]["guid"],
                              res.get("error", {}).get("message"))
        if failures:
            print(f"  {failures} of {len(updates)} changes refused by Archicad.")
        if failures > len(updates) // 10:
            print("Too many refusals: stopped before deleting or creating elements. "
                  "Undo (Cmd+Z / Ctrl+Z) or close without saving.")
            summary["failures"] = failures
            summary["stopped"] = True
            return summary
        for batch in chunks(new_lines, 200):
            ac.tapir("CreateLineElements", {"linesData": [
                {k: v for k, v in L.items() if v is not None} for L in batch]})
        for batch in chunks(new_polys, 200):
            # CreatePolylines only takes the line type by index: create without
            # it, then set it by its identifier.
            r = ac.tapir("CreatePolylines", {"polylinesData": [
                {k: v for k, v in L.items() if v is not None and k != "lineTypeId"}
                for L in batch]})
            fix = [{"elementId": e["elementId"], "details": {"typeSpecificDetails": {
                       "lineTypeId": L["lineTypeId"]}}}
                   for e, L in zip(r.get("elements", []), batch)
                   if "elementId" in e and L.get("lineTypeId")]
            if fix:
                ac.tapir("SetDetailsOfElements", {"elementsWithDetails": fix})
        for batch in chunks(new_arcs, 200):
            ac.tapir("CreateArcs", {"arcsData": [
                {k: v for k, v in L.items() if v is not None} for L in batch]})
        for batch in chunks(to_delete, 400):
            ac.tapir("DeleteElements", {"elements": [eid(g) for g in batch]})
    finally:
        if prev_susp is False:
            try:
                ac.tapir("SetSuspendGroupsMode", {"suspendGroups": False})
            except Exception:
                print("WARNING: could not restore groups. Turn 'Suspend Groups' "
                      "off by hand in Archicad.")
    print("Done. Optional next step in Archicad: Edit > Reshape > Consolidate Lines.")
    summary["failures"] = failures
    return summary



# --------------------------------------------------------------------------
# Output to a new worksheet
# --------------------------------------------------------------------------

def view_name(ac, guid):
    """Name of the view that contains the element: the worksheet, detail or
    section name; for the floor plan, the story name, else the project name."""
    try:
        db = ac.tapir("GetContainingDatabases", {"elements": [eid(guid)]})["databases"][0]
    except Exception:
        db = {}
    name = (db.get("name") or "").strip()
    if name:
        return name
    if db.get("windowType") == "FloorPlan":
        try:
            d = ac.tapir("GetDetailsOfElements", {"elements": [eid(guid)],
                                                  "fields": ["floorIndex"]})["detailsOfElements"][0]
            for st in ac.tapir("GetStories").get("stories", []):
                if st.get("index") == d.get("floorIndex") and (st.get("name") or "").strip():
                    return st["name"].strip()
        except Exception:
            pass
    try:
        return ac.tapir("GetProjectInfo").get("projectName") or "Untitled"
    except Exception:
        return "Untitled"


OWN_TYPES = ["Hatch", "Line", "Arc", "PolyLine", "Spline"]   # what the scripts draw


def list_worksheets(ac):
    try:
        return ac.tapir("GetDatabases", {"types": ["Worksheet"]}).get("databases") or []
    except Exception:
        return []


def find_worksheet(ac, name, ref_id):
    for d in list_worksheets(ac):
        if (d.get("name") or "") == name and (d.get("referenceId") or "") == ref_id:
            return d.get("databaseId")
    return None


def free_ref(ac, ref_id):
    used = {d.get("referenceId") for d in list_worksheets(ac)}
    if ref_id not in used:
        return ref_id
    for i in range(2, 1000):
        if f"{ref_id} {i}" not in used:
            return f"{ref_id} {i}"
    return ref_id


def clear_worksheet(ac, db):
    """Opens the worksheet and deletes its hatches, lines, arcs, polylines and
    splines. Anything else in it (texts, dimensions...) is kept. Each element is
    checked to belong to this worksheet before it is deleted."""
    ac.tapir("ChangeWindow", {"databaseId": db})
    cand = []
    for t in OWN_TYPES:
        try:
            r = ac.tapir("GetElementsByType", {"elementType": t})
        except Exception:
            continue
        cand += [e["elementId"]["guid"] for e in r.get("elements", [])]
    mine = []
    for ch in chunks(cand, 300):
        r = ac.tapir("GetContainingDatabases", {"elements": [eid(g) for g in ch]})
        for g, d in zip(ch, r.get("databases", [])):
            if ((d or {}).get("databaseId") or {}).get("guid") == db.get("guid"):
                mine.append(g)
    for ch in chunks(mine, 400):
        ac.tapir("DeleteElements", {"elements": [eid(g) for g in ch]})
    return len(mine)


def open_worksheet(ac, name, ref_id, mode="new"):
    """Makes the worksheet '<ref_id> <name>' the current window, so that the
    elements created next are drawn in it. mode 'replace': an existing one with
    this ID and name is reused and cleared; otherwise a new one is created (with
    a numbered ID if the ID is taken)."""
    if mode == "replace":
        db = find_worksheet(ac, name, ref_id)
        if db:
            clear_worksheet(ac, db)
            return db
    first = free_ref(ac, ref_id)
    last = None
    for ref in [first] + [f"{ref_id} {i}" for i in range(2, 100)]:
        try:
            r = ac.tapir("CreateWorksheets", {"worksheetsData": [
                {"name": name, "referenceId": ref}]})
        except Exception as e:
            last = e
            continue
        dbs = r.get("databases") or []
        if dbs and (dbs[0] or {}).get("databaseId"):
            ac.tapir("ChangeWindow", {"databaseId": dbs[0]["databaseId"]})
            return dbs[0]["databaseId"]
        last = r
    raise RuntimeError(f"Could not create the worksheet '{name}': {str(last)[:200]}")


def ask_terminal_existing(names):
    print("\nThese worksheets already exist:")
    for n in names:
        print("  " + n)
    a = input("[R]eplace their contents, create [N]ew ones, or [C]ancel? ").strip().lower()
    return {"r": "replace", "n": "new"}.get(a[:1], "cancel")


# Set to a dialog version when run from the Tapir palette.
CHOOSE_EXISTING = ask_terminal_existing


def zoom_to_fit(ac):
    try:
        ac.tapir("FitInWindow", {})
    except Exception:
        pass


def _clean(d):
    return {k: v for k, v in d.items() if v is not None}


def _created(r, n):
    out = [((e or {}).get("elementId") or {}).get("guid") for e in r.get("elements", [])]
    return out + [None] * (n - len(out))


def apply_to_worksheet(ac, all_ids, det, updates, to_delete, new_lines, new_polys,
                       new_arcs, tol):
    """Draws the final state of every processed element in a new worksheet:
    unchanged elements are copied, changed ones are drawn changed, deleted ones
    are left out and new ones are added. The original drawing is not touched."""
    upd = {u["elementId"]["guid"]: u["details"]["typeSpecificDetails"] for u in updates}
    gone = set(to_delete)
    keep = [g for g in all_ids if g not in gone and g in det]
    view = view_name(ac, all_ids[0]) if all_ids else "Untitled"
    name = f"Simplify 2D {view}"
    mode = "new"
    if find_worksheet(ac, view, "Simplify 2D"):
        mode = CHOOSE_EXISTING([name])
        if mode == "cancel":
            return {"worksheet": None, "created": 0, "failures": 0, "cancelled": True}
    open_worksheet(ac, view, "Simplify 2D", mode)

    lines, arcs, polys, splines, hatches = [], [], [], [], []
    for g in keep:
        d = det[g]; t = d["type"]; dd = dict(d["details"]); dd.update(upd.get(g, {}))
        base = {"layerIndex": d.get("layerIndex")}
        if t == "Line":
            lines.append(_clean(dict(base, begCoordinate=dd["begCoordinate"],
                                     endCoordinate=dd["endCoordinate"],
                                     linePenIndex=dd.get("linePenIndex"),
                                     lineTypeId=dd.get("lineTypeId"))))
        elif t == "Arc":
            arcs.append((_clean(dict(base, origin=dd["origin"], radius=dd["radius"],
                                     begAngle=dd["begAngle"], endAngle=dd["endAngle"],
                                     linePenIndex=dd.get("linePenIndex"),
                                     lineTypeId=dd.get("lineTypeId"))),
                         {k: dd[k] for k in ("angle", "ratio", "reflected") if k in dd}))
        elif t == "PolyLine":
            polys.append(_clean(dict(base, coordinates=dd["coordinates"], arcs=dd.get("arcs") or [],
                                     linePenIndex=dd.get("linePenIndex"),
                                     lineTypeId=dd.get("lineTypeId"))))
        elif t == "Spline":
            c = dd.get("coordinates") or []
            closed = bool(dd.get("closed"))
            if closed and len(c) > 1 and c[0] == c[-1]:
                c = c[:-1]
            if len(c) >= 3:
                splines.append(_clean(dict(base, coordinates=c, closed=closed,
                                           linePenIndex=dd.get("linePenIndex"),
                                           lineTypeId=dd.get("lineTypeId"))))
            elif len(c) == 2:
                lines.append(_clean(dict(base, begCoordinate=c[0], endCoordinate=c[1],
                                         linePenIndex=dd.get("linePenIndex"),
                                         lineTypeId=dd.get("lineTypeId"))))
        elif t == "Hatch":
            if g in upd:                       # already in write format
                outer = (dd["coordinates"], dd.get("arcs") or [])
                holes = dd.get("holes") or []
            else:                              # read format -> write format
                P, Bl, closed, odd = from_api(dd["coordinates"], dd.get("arcs"), tol)
                outer = to_api_hatch(P, Bl)
                holes = [{"polygonOutline": h.get("polygonOutline") or h.get("polygonCoordinates") or [],
                          "polygonArcs": h.get("polygonArcs") or h.get("arcs") or []}
                         for h in dd.get("holes") or []]
            attrs = {k: dd.get(k) for k in ("contourPenIndex", "fillPenIndex",
                                            "fillBackgroundPenIndex", "fillId",
                                            "roomSpecial", "showArea")}
            bm = (dd.get("buildingMaterialId") or {}).get("guid")
            if bm and bm != "00000000-0000-0000-0000-000000000000":
                attrs["buildingMaterialId"] = {"guid": bm}
            hatches.append((_clean(dict(base, coordinates=outer[0], arcs=outer[1], **attrs)),
                            holes))

    for L in new_lines:
        lines.append(_clean({k: v for k, v in L.items() if k != "floorInd"}))
    for A in new_arcs:
        arcs.append((_clean({k: v for k, v in A.items() if k != "floorInd"}), {}))
    for P_ in new_polys:
        polys.append(_clean({k: v for k, v in P_.items() if k != "floorInd"}))

    created, failures, fix = 0, 0, []

    def count(ids_):
        nonlocal created, failures
        ok = [g for g in ids_ if g]
        created += len(ok); failures += len(ids_) - len(ok)
        return ids_

    for batch in chunks(lines, 200):
        count(_created(ac.tapir("CreateLineElements", {"linesData": batch}), len(batch)))
    for batch in chunks(arcs, 200):
        ids_ = count(_created(ac.tapir("CreateArcs", {"arcsData": [a for a, _ in batch]}), len(batch)))
        for g, (a, extra) in zip(ids_, batch):
            if g and (abs(float(extra.get("angle", 0) or 0)) > 1e-12
                      or abs(float(extra.get("ratio", 1) or 1) - 1) > 1e-12
                      or extra.get("reflected")):
                fix.append({"elementId": {"guid": g}, "details": {"typeSpecificDetails": dict(
                    origin=a["origin"], radius=a["radius"], begAngle=a["begAngle"],
                    endAngle=a["endAngle"], **extra)}})
    for batch in chunks(polys, 200):
        # CreatePolylines takes the line type only by index: set it afterwards.
        ids_ = count(_created(ac.tapir("CreatePolylines", {"polylinesData": [
            {k: v for k, v in p.items() if k != "lineTypeId"} for p in batch]}), len(batch)))
        fix += [{"elementId": {"guid": g}, "details": {"typeSpecificDetails": {
                    "lineTypeId": p["lineTypeId"]}}}
                for g, p in zip(ids_, batch) if g and p.get("lineTypeId")]
    for batch in chunks(splines, 200):
        count(_created(ac.tapir("CreateSplines", {"splinesData": batch}), len(batch)))
    for batch in chunks(hatches, 200):
        # CreateHatches takes a single contour. Holes are added afterwards,
        # together with the outline (Archicad ignores holes sent on their own);
        # holes repeat their first point at the end.
        ids_ = count(_created(ac.tapir("CreateHatches", {"hatchesData": [h for h, _ in batch]}),
                              len(batch)))
        for g, (h, holes) in zip(ids_, batch):
            if g and holes:
                fix.append({"elementId": {"guid": g}, "details": {"typeSpecificDetails": {
                    "coordinates": h["coordinates"], "arcs": h.get("arcs", []), "holes": [
                        {"polygonOutline": (hh["polygonOutline"] if hh["polygonOutline"][:1] ==
                                            hh["polygonOutline"][-1:] else
                                            hh["polygonOutline"] + hh["polygonOutline"][:1]),
                         "polygonArcs": hh.get("polygonArcs") or []} for hh in holes]}}})
    for batch in chunks(fix, 200):
        r = ac.tapir("SetDetailsOfElements", {"elementsWithDetails": batch})
        failures += sum(1 for x in r.get("executionResults", []) if not x.get("success", True))
    zoom_to_fit(ac)
    return {"worksheet": name, "created": created, "failures": failures}

# --------------------------------------------------------------------------
# Dialog mode (no Terminal): runs from the Tapir palette in Archicad
# --------------------------------------------------------------------------

def _first_int(obj):
    if isinstance(obj, bool):
        return None
    if isinstance(obj, int):
        return obj
    if isinstance(obj, dict):
        for k in ("clickedButton", "pressedButton", "button", "buttonIndex", "result"):
            if k in obj:
                v = _first_int(obj[k])
                if v is not None:
                    return v
        for v in obj.values():
            r = _first_int(v)
            if r is not None:
                return r
    if isinstance(obj, (list, tuple)):
        for v in obj:
            r = _first_int(v)
            if r is not None:
                return r
    return None


def ask(ac, message, sub=None, buttons=("OK",), kind="information"):
    """Archicad alert with up to three buttons. Returns 1, 2 or 3."""
    params = {"alertType": kind, "title": "Simplify 2D", "message": message,
              "button1": buttons[0]}
    if sub:
        params["subMessage"] = sub
    if len(buttons) > 1:
        params["button2"] = buttons[1]
    if len(buttons) > 2:
        params["button3"] = buttons[2]
    r = ac.tapir("ShowAlert", params)
    v = _first_int(r)
    return v if v in (1, 2, 3) else 1


def run_dialogs(ac, args, name):
    global CHOOSE_EXISTING

    def choose(names):
        b = ask(ac, "This worksheet already exists.", "\n".join(names) +
                "\n\nReplace: delete its hatches, lines, arcs, polylines and splines and "
                "draw the new result there.\nNew: create another worksheet.",
                ("Replace", "New", "Cancel"), "warning")
        return {1: "replace", 2: "new"}.get(b, "cancel")
    CHOOSE_EXISTING = choose
    choice = ask(ac, "What should Simplify 2D process?",
                 f"File: {name}\n\nSelection: only the elements selected now.\n"
                 "Whole file: every hatch, line, arc, polyline and spline.",
                 ("Selection", "Whole file", "Cancel"))
    if choice == 3:
        return
    args.selection = (choice == 1)
    names = list(PRESETS)
    desc = "\n".join(f"{n}: curves up to {v['radius']:g} mm become corners or "
                     f"straight segments; shape kept within {v['shape_tol']:g} mm."
                     for n, v in PRESETS.items())
    level = ask(ac, "How much should it simplify?", desc, tuple(names[:3]))
    preset = names[level - 1]
    for k, v in PRESETS[preset].items():
        setattr(args, k, v)
    if args.selection and not selected_guids(ac):
        ask(ac, "Nothing is selected.", "Select the detail first, then run Simplify 2D again.",
            ("OK",), "warning")
        return
    args.apply = False
    plan = process(ac, args)
    if not (plan["hatches"] or plan["polylines"] or plan["lines_extended"]
            or plan["new_lines"] or plan["deleted"]):
        ask(ac, "Nothing to simplify.", "No curves within the limits were found.", ("OK",))
        return
    text = (f"Level: {preset}. Circles: {args.circles}. Outlines: "
            f"{'not changed (hatches only)' if args.hatches_only else 'as ' + args.contours}.\n"
            f"{plan['hatches']} hatches and {plan['polylines']} polylines will change.\n"
            f"{plan['corners']} fillets become sharp corners; {plan['faceted']} other "
            f"curves become straight segments.\n"
            f"{plan['outlines']} hatch outlines are redrawn; {plan['deleted']} old "
            f"elements are deleted.")
    if plan["partial"]:
        text += (f"\n\n{plan['partial']} hatch outlines are only partly drawn as lines: "
                 "their lines will not be redrawn.")
    if args.output == "worksheet":
        text += ("\n\nThe result is drawn in a new worksheet, 'Simplify 2D <view>'. "
                 "The original is not changed.")
    else:
        text += "\n\nThis changes the drawing itself. Keep a copy of the file."
    text += " Don't touch Archicad until the end."
    if ask(ac, "Apply these changes?", text, ("Apply", "Cancel"), "warning") != 1:
        return
    args.apply = True
    res = process(ac, args)
    if res.get("stopped"):
        ask(ac, "Stopped: Archicad refused too many changes.",
            f"{res['failures']} changes were refused. Nothing was deleted or created. "
            "Undo or close without saving.", ("OK",), "error")
    elif res.get("failures"):
        ask(ac, "Done, with some refusals.",
            f"{res['failures']} changes were refused by Archicad. Check the result.",
            ("OK",), "warning")
    elif res.get("cancelled"):
        return
    elif args.output == "worksheet":
        ask(ac, "Done.", f"Worksheet '{res.get('worksheet')}' created with "
            f"{res.get('created', 0)} elements. The original was not changed.", ("OK",))
    else:
        ask(ac, "Done.", "Check the result before saving.", ("OK",))


def main():
    ap = argparse.ArgumentParser(
        prog="simplify_2d.py",
        description="Simplify 2D: simplifies small curves in Archicad 2D details "
                    "(hatches, lines, arcs, polylines, splines).")
    ap.add_argument("--port", type=int, default=0,
                    help="Archicad instance port (default: search 19723–19743)")
    ap.add_argument("--radius", type=float, default=5.0,
                    help="max radius, in mm, of the curves to simplify (5)")
    ap.add_argument("--spike", type=float, default=10.0,
                    help="absolute max distance, in mm, from a new corner to the arc ends (10)")
    ap.add_argument("--tol", type=float, default=0.02,
                    help="tolerance, in mm, for matching endpoints (0.02)")
    ap.add_argument("--straight", type=float, default=0.05,
                    help="max deviation, in mm, for a spline to count as straight (0.05)")
    ap.add_argument("--contour-tol", type=float, default=0.05,
                    help="max distance, in mm, from a line to a hatch outline (0.05)")
    ap.add_argument("--coverage", type=float, default=0.9,
                    help="share of a hatch outline that must be drawn as lines "
                         "for it to be redrawn (0.9)")
    ap.add_argument("--contours", choices=["polyline", "lines"], default=SETTINGS["contours"],
                    help="how to redraw hatch outlines: one polyline per outline "
                         "(fewer elements) or loose lines (polyline)")
    ap.add_argument("--no-contours", action="store_true",
                    help="don't redraw outline lines from the hatches")
    ap.add_argument("--corner-max", type=float, default=100,
                    help="max turn, in degrees, of a fillet to become a sharp corner (100)")
    ap.add_argument("--spike-r", type=float, default=2.0,
                    help="max distance from a new corner to the arc ends, "
                         "in multiples of the radius (2)")
    ap.add_argument("--facet", type=float, default=15,
                    help="segment angle, in degrees, before simplification (15)")
    ap.add_argument("--shape-tol", type=float, default=0.2,
                    help="max deviation, in mm, when simplifying curves that are not "
                         "fillets, and nearly straight arcs (0.2)")
    ap.add_argument("--circles", choices=["keep", "delete"], default=SETTINGS["circles"],
                    help="what to do with full circles up to --radius (keep)")
    ap.add_argument("--selection", action="store_true",
                    help="only the elements selected in Archicad")
    ap.add_argument("--hatches-only", action="store_true", default=SETTINGS["hatches_only"],
                    help="only change hatches; don't touch lines, arcs, polylines or splines")
    ap.add_argument("--select-skipped", action="store_true",
                    help="in a dry run, select the skipped elements in Archicad")
    ap.add_argument("--show-partial", action="store_true",
                    help="in a dry run, select the hatches whose outline is only partly "
                         "drawn as lines")
    ap.add_argument("--output", choices=["worksheet", "in place"], default=SETTINGS["output"],
                    help="draw the result in a new worksheet, or change the drawing "
                         f"itself ({SETTINGS['output']})")
    ap.add_argument("--apply", action="store_true", help="apply the changes")
    ap.add_argument("--dialogs", action="store_true",
                    help="use Archicad dialogs instead of the Terminal (automatic when "
                         "run without a Terminal, e.g. from the Tapir palette)")
    ap.add_argument("--report", nargs="?", const="simplify_2d_report.json",
                    default=None,
                    help="write a JSON report (off by default; without a name uses "
                         "simplify_2d_report.json)")
    args = ap.parse_args()

    ports = [args.port] if args.port else range(19723, 19744)
    ac = None
    for p in ports:
        try:
            c = Archicad(p)
            info = c.api("API.GetProductInfo")
            ac = c
            print(f"Simplify 2D | Archicad {info.get('version')} on port {p}")
            break
        except Exception:
            continue
    if not ac:
        sys.exit("No Archicad responding. Is Archicad open with Tapir installed?")
    if not args.port:
        print("(With several Archicad instances open, use --port.)")

    for cmd in ("GetDetailsOfElements", "SetDetailsOfElements",
                "DeleteElements", "CreateLineElements", "CreateArcs", "CreatePolylines"):
        if not ac.tapir_available(cmd):
            sys.exit(f"Missing Tapir command: {cmd}. Update Tapir.")
    if args.output == "worksheet":
        for cmd in ("CreateWorksheets", "ChangeWindow", "GetContainingDatabases",
                    "CreateHatches", "CreateSplines", "GetDatabases"):
            if not ac.tapir_available(cmd):
                sys.exit(f"Missing Tapir command: {cmd}. Update Tapir, or set "
                         "SETTINGS['output'] to 'in place'.")

    try:
        name = ac.tapir("GetProjectInfo").get("projectName", "?")
        print(f"Open file: {name}")
    except Exception:
        name = "?"
    if args.dialogs or not sys.stdin or not sys.stdin.isatty():
        try:
            run_dialogs(ac, args, name)
        except Exception as e:
            try:
                ask(ac, "Simplify 2D stopped with an error.", str(e)[:400], ("OK",), "error")
            except Exception:
                pass
            raise
        return
    if args.apply and args.output == "worksheet":
        resp = input(f"\nThis will add a worksheet to '{name}'. Type YES to continue: ")
        if resp.strip().upper() != "YES":
            sys.exit("Cancelled. Nothing was changed.")
    elif args.apply:
        resp = input(f"\nThis will change the file '{name}'. Type YES to continue: ")
        if resp.strip().upper() != "YES":
            sys.exit("Cancelled. Nothing was changed.")
        print("Keep a copy of the file. The changes are several separate steps in "
              "the undo history.")
    process(ac, args)


if __name__ == "__main__":
    main()
