/**
 * S-25 · S2「边界与连接带」纯函数单测（Node，无 WebGL / 无 three）。
 * -----------------------------------------------------------------------------
 * 覆盖任务书 e/f/g 与 Lead 在 island-shape.ts 里落盘的 connect 段契约：
 *   e. 相邻已拥有地块合并：同簇相邻**不建侧壁**（wallMaskFor 边界位 false），簇外缘建墙。
 *   f. 扩岛连接带：岩桥跨骑在公共边上（左右各半宽），不越两侧 footprint（R4 A32）。
 *   g. 高差衔接：|dh| ≤ 0.5 生成粗糙斜面/台阶面；dh=0 或超限返回空。
 *
 * 关键几何事实（自洽校验，见 E 段）：
 *   · HEX_S=2、HEX_INRADIUS=√3≈1.73205；顶面内缩 TOP_INSET=0.025 ⇒ 顶面六边形 r=1.975。
 *   · 相邻两块地的**真 footprint 在公共边上正好相切**（公共边线距各自中心 1.73205），
 *     公共边线落在两块 footprint 的**并集内部** ⇒ 岩桥可以对称跨骑而不违反 A32。
 *   · 两块地顶面之间那道缝宽 = 2·0.025·cos30° = **0.0433013**。
 */
import { writeFileSync } from 'node:fs';
import { HEX_S, HEX_INRADIUS, dirUnit, axialToWorld } from '../src/render/hex';
import {
  wallMaskFor, seamTris, bridgeTris, rampTris, bridgeWidth,
  neighborOf, edgeForDirection, Band, TOP_INSET,
  type OwnedTest, type Tri, type V3
} from '../src/render/island-shape';

/* ------------------------------------------------------------------ 断言框架 */

let checks = 0;
const fails: string[] = [];
const ok = (cond: boolean, msg: string): void => { checks++; if (!cond) { fails.push(msg); } };
const near = (a: number, b: number, tol = 1e-9): boolean => Math.abs(a - b) <= tol;

/* ------------------------------------------------------------------ 小工具 */

/** 叉积。 */
function cross(u: V3, v: V3): V3 { return { x: u.y * v.z - u.z * v.y, y: u.z * v.x - u.x * v.z, z: u.x * v.y - u.y * v.x }; }
/** 三角形法线（未归一）。 */
function triNormal(t: Tri): V3 { return cross(sub(t.b, t.a), sub(t.c, t.a)); }
function sub(a: V3, b: V3): V3 { return { x: a.x - b.x, y: a.y - b.y, z: a.z - b.z }; }
/** 三角形面积。 */
function triArea(t: Tri): number { const c = triNormal(t); return Math.hypot(c.x, c.y, c.z) * 0.5; }
/** 三角形三个顶点。 */
function triVerts(t: Tri): V3[] { return [t.a, t.b, t.c]; }
/** 三角形集合去重后的顶点（按 xz + y，容差 1e-9）。 */
function uniqVerts(tris: ReadonlyArray<Tri>): V3[] {
  const out: V3[] = [];
  for (const t of tris) for (const p of triVerts(t)) {
    if (!out.some(o => near(o.x, p.x, 1e-9) && near(o.y, p.y, 1e-9) && near(o.z, p.z, 1e-9))) out.push(p);
  }
  return out;
}
const key = (p: V3): string => `${p.x.toFixed(9)}|${p.y.toFixed(9)}|${p.z.toFixed(9)}`;
/** 两个三角形集合逐分量相等（坐标 + band）。 */
function sameTris(a: ReadonlyArray<Tri>, b: ReadonlyArray<Tri>): boolean {
  if (a.length !== b.length) { return false; }
  for (let i = 0; i < a.length; i++) {
    if (a[i].band !== b[i].band) { return false; }
    for (const k of ['a', 'b', 'c'] as const) {
      const p = a[i][k], q = b[i][k];
      if (!near(p.x, q.x, 0) || !near(p.y, q.y, 0) || !near(p.z, q.z, 0)) { return false; }
    }
    if (!near(a[i].jit, b[i].jit, 0)) { return false; }
  }
  return true;
}
/** 点相对某地块中心的「六边形内缩余量」：min_j (HEX_INRADIUS − 投影)；>0 在六边形内。 */
function hexMargin(p: V3, cx: number, cz: number): number {
  let m = Infinity;
  for (let j = 0; j < 6; j++) { const u = dirUnit(j); m = Math.min(m, HEX_INRADIUS - ((p.x - cx) * u.x + (p.z - cz) * u.z)); }
  return m;
}
/** 「在六边形内」判定：6 个法向投影都 ≤ lim。 */
function inHex(p: V3, cx: number, cz: number, lim = HEX_INRADIUS): boolean {
  for (let j = 0; j < 6; j++) { const u = dirUnit(j); if ((p.x - cx) * u.x + (p.z - cz) * u.z > lim + 1e-9) { return false; } }
  return true;
}

/** 公共边线：方向 j 的公共边是两块地 footprint 的公共边；其中点 = 两中心的连线中点；法向 = dirUnit(j)。 */
function seamFrame(q: number, r: number, j: number): {
  cA: { x: number; z: number }; cB: { x: number; z: number };
  mid: { x: number; z: number }; n: { x: number; z: number }; t: { x: number; z: number };
} {
  const nb = neighborOf(q, r, j);
  const cA = axialToWorld(q, r), cB = axialToWorld(nb[0], nb[1]);
  const n = dirUnit(j);                       // 从 A 指向 B 的法向
  const t = { x: -n.z, z: n.x };              // 接缝方向（切向）
  return { cA, cB, mid: { x: (cA.x + cB.x) / 2, z: (cA.z + cB.z) / 2 }, n, t };
}
/** 点相对公共边线的有向距离（正 = B 侧）。 */
const signedToSeam = (p: V3, f: ReturnType<typeof seamFrame>): number => (p.x - f.mid.x) * f.n.x + (p.z - f.mid.z) * f.n.z;
/** 点相对公共边中点的切向坐标。 */
const alongSeam = (p: V3, f: ReturnType<typeof seamFrame>): number => (p.x - f.mid.x) * f.t.x + (p.z - f.mid.z) * f.t.z;

/* ------------------------------------------------------------------ 测试数据 */

/** 初始 7 块（任务书给定集合）。 */
const INITIAL7: ReadonlyArray<readonly [number, number]> = [[0, 0], [1, 0], [0, 1], [-1, 1], [-1, 0], [0, -1], [1, -1]];
const initialSet = new Set(INITIAL7.map(([q, r]) => q + ',' + r));
const ownedInitial: OwnedTest = (q, r) => initialSet.has(q + ',' + r);
/** 相邻两块（(0,0) 与 (1,0)）。 */
const ownedTwo: OwnedTest = (q, r) => (q === 0 && r === 0) || (q === 1 && r === 0);
/** 一组用于几何遍历的地块。 */
const TILES: ReadonlyArray<readonly [number, number]> = [[0, 0], [1, 0], [0, 1], [-1, 1], [-1, 0], [0, -1], [1, -1], [2, -1], [3, 2], [4, -3]];

/** 缝宽标称值：2·TOP_INSET·cos30°。 */
const GAP_NOMINAL = 2 * TOP_INSET * Math.cos(Math.PI / 6);
const TOP_R = HEX_S - TOP_INSET;          // 1.975：顶面六边形半径（= 边长）
const A32_LIM = HEX_INRADIUS - 0.004;     // footprint 安全余量后的投影上限

/* ================================================================== A · 边界边判定 */

/* A1 · 孤立地块：6 条边全部建墙。 */
{
  const m = wallMaskFor(() => false, 5, 5);
  ok(m.length === 6, 'wallMaskFor 返回长度 6 ' + m.length);
  ok(m.every(v => v === true), '孤立地块 6 条边全建墙 ' + JSON.stringify(m));
}

/* A2 · 两个相邻已拥有地块：公共边不建墙，其余 5 条边建墙（双向都验）。 */
{
  const mA = wallMaskFor(ownedTwo, 0, 0);
  const mB = wallMaskFor(ownedTwo, 1, 0);
  const eA = edgeForDirection(0);   // (0,0) 的方向 0（东）邻居 = (1,0)
  const eB = edgeForDirection(3);   // (1,0) 的方向 3（西）邻居 = (0,0)
  ok(mA[eA] === false, 'A 侧公共边不建墙 mask[' + eA + ']=' + mA[eA]);
  ok(mB[eB] === false, 'B 侧公共边不建墙 mask[' + eB + ']=' + mB[eB]);
  ok([0, 1, 2, 3, 4, 5].filter(e => e !== eA).every(e => mA[e] === true), 'A 侧其余 5 条边建墙 ' + JSON.stringify(mA));
  ok([0, 1, 2, 3, 4, 5].filter(e => e !== eB).every(e => mB[e] === true), 'B 侧其余 5 条边建墙 ' + JSON.stringify(mB));
  ok(mA.filter(v => v === false).length === 1 && mB.filter(v => v === false).length === 1, '每块地恰好 1 条内部边');
}

/* A3 · 初始 7 块簇：内部边全 false，簇外缘全 true。 */
{
  for (const [q, r] of INITIAL7) {
    const m = wallMaskFor(ownedInitial, q, r);
    ok(m.length === 6, `(${q},${r}) mask 长度 6`);
    let inner = 0, outer = 0;
    for (let j = 0; j < 6; j++) {
      const nb = neighborOf(q, r, j);
      const e = edgeForDirection(j);
      const isOwned = ownedInitial(nb[0], nb[1]);
      if (m[e] !== !isOwned) { ok(false, `(${q},${r}) 方向 ${j} → 边 ${e} 映射错：mask=${m[e]} 邻居已拥有=${isOwned}`); }
      if (isOwned) { inner++; if (m[e] !== false) { ok(false, `(${q},${r}) 内部边 ${e} 应不建墙`); } }
      else { outer++; if (m[e] !== true) { ok(false, `(${q},${r}) 外缘边 ${e} 应建墙`); } }
    }
    ok(inner >= 1, `(${q},${r}) 至少 1 条内部边 inner=${inner} outer=${outer}`);
    ok(m.filter(v => v === false).length === inner, `(${q},${r}) 内部边数一致`);
    ok(m.filter(v => v === false).length + m.filter(v => v === true).length === 6, `(${q},${r}) 6 条边全覆盖`);
  }
  // 中心块 (0,0) 被 6 块围住 ⇒ 全部 6 条边都不建墙
  const mc = wallMaskFor(ownedInitial, 0, 0);
  ok(mc.every(v => v === false), '中心块 (0,0) 四周皆已拥有 ⇒ 6 条边都不建墙 ' + JSON.stringify(mc));
  // 外围块各有 3 条内部边、3 条外缘边
  for (const [q, r] of [[1, 0], [0, 1], [-1, 1], [-1, 0], [0, -1], [1, -1]]) {
    const m = wallMaskFor(ownedInitial, q, r);
    ok(m.filter(v => v === false).length === 3, `(${q},${r}) 3 条内部边 ` + JSON.stringify(m));
    ok(m.filter(v => v === true).length === 3, `(${q},${r}) 3 条外缘边 ` + JSON.stringify(m));
  }
}

/* A4 · 边↔方向映射：edgeForDirection 是 6 个互异下标（一一对应），且 mask 语义按方向解释。 */
{
  const es = [0, 1, 2, 3, 4, 5].map(j => edgeForDirection(j));
  ok(new Set(es).size === 6, 'edgeForDirection 是 6↔6 双射 ' + JSON.stringify(es));
  ok(es.every((e, i) => e === ((i + 5) % 6 + 6) % 6), 'edgeForDirection(j) = (j+5)%6 ' + JSON.stringify(es));
  // 随机 owned 集合下逐方向交叉验证
  const set = new Set(['0,0', '1,0', '0,1', '-1,1', '-1,0', '2,0', '3,-1']);
  const own: OwnedTest = (q, r) => set.has(q + ',' + r);
  for (const [q, r] of TILES) {
    const m = wallMaskFor(own, q, r);
    for (let j = 0; j < 6; j++) {
      const nb = neighborOf(q, r, j);
      const e = edgeForDirection(j);
      ok(m[e] === !own(nb[0], nb[1]), `(${q},${r}) 方向 ${j} → 边 ${e} 语义一致`);
    }
  }
}

/* A5 · 方向 j 的邻居方向就是 dirUnit(j)（几何自洽：边法线与邻居一致 ⇒ 墙贴着邻居那一侧）。 */
{
  for (let j = 0; j < 6; j++) {
    const nb = neighborOf(3, -2, j);
    const cA = axialToWorld(3, -2), cB = axialToWorld(nb[0], nb[1]);
    const dx = cB.x - cA.x, dz = cB.z - cA.z;
    const len = Math.hypot(dx, dz);
    const u = dirUnit(j);
    ok(near(len, 2 * HEX_INRADIUS, 1e-9), '方向 ' + j + ' 邻居中心距 = 2·HEX_INRADIUS ' + len);
    ok(near(dx / len, u.x, 1e-12) && near(dz / len, u.z, 1e-12), '方向 ' + j + ' 邻居方位 = dirUnit(j)');
  }
}

/* ================================================================== B · 接缝几何 */

/* B1~B6 · 接缝 quad 正好填满 0.0433 的缝、无黑洞、顶点各归各地块。 */
{
  for (const [q, r] of TILES) {
    for (let j = 0; j < 6; j++) {
      const tris = seamTris(q, r, j);
      const tag = `(${q},${r}) j=${j}`;
      ok(tris.length === 2, `${tag} 接缝 2 个三角形 ` + tris.length);
      ok(tris.every(t => t.band === Band.Seam), `${tag} band = Band.Seam`);
      const vs = uniqVerts(tris);
      ok(vs.length === 4, `${tag} 接缝 4 个顶点 ` + vs.length);
      ok(vs.every(p => near(p.y, -0.002, 1e-12)), `${tag} 接缝顶面 y = −0.002（防 z-fighting）`);
      // 缝宽：顶点相对公共边线的法向偏移
      const f = seamFrame(q, r, j);
      const ds = vs.map(p => signedToSeam(p, f));
      const lo = Math.min(...ds), hi = Math.max(...ds);
      ok(lo < 0 && hi > 0, `${tag} 接缝跨在公共边两侧 lo=${lo} hi=${hi}`);
      ok(near(lo, -hi, 1e-9), `${tag} 接缝关于公共边线对称 lo=${lo} hi=${hi}`);
      const gap = hi - lo;
      ok(near(gap, GAP_NOMINAL, 0.005), `${tag} 缝宽 = ${gap.toFixed(6)}（标称 ${GAP_NOMINAL.toFixed(6)}）`);
      ok(near(Math.abs(lo), TOP_INSET * Math.cos(Math.PI / 6), 1e-9), `${tag} 单侧半缝 = ${Math.abs(lo).toFixed(6)}`);
      // 顶点各归各地块（不越 footprint）
      for (const p of vs) {
        const d = signedToSeam(p, f);
        const c = d < 0 ? f.cA : f.cB;
        ok(inHex(p, c.x, c.z, A32_LIM), `${tag} 接缝顶点在其所属地块六边形内 margin=${hexMargin(p, c.x, c.z).toFixed(6)}`);
      }
      // 面积 > 0、法线朝上、两三角形合起来正好填满四边形
      const areas = tris.map(triArea);
      ok(areas.every(a => a > 0), `${tag} 接缝三角形面积 > 0`);
      ok(tris.every(t => triNormal(t).y > 0), `${tag} 接缝三角形法线朝上（+y）`);
      const total = areas.reduce((a, b) => a + b, 0);
      ok(near(total, TOP_R * GAP_NOMINAL, 1e-6), `${tag} 接缝面积 = ${total.toFixed(6)}（标称 ${(TOP_R * GAP_NOMINAL).toFixed(6)}）`);
    }
  }
  // 不同方向的接缝不重叠
  const s0 = seamTris(0, 0, 0).map(t => triVerts(t).map(key).join(';'));
  const s1 = seamTris(0, 0, 1).map(t => triVerts(t).map(key).join(';'));
  ok(JSON.stringify(s0) !== JSON.stringify(s1), '不同方向的接缝几何不同');
}

/* ================================================================== C · 岩桥 / 连接带 */

/* C1 · 宽度：总宽 ∈ [0.30,0.45]×HEX_S，半宽 ∈ [0.30,0.45]。 */
{
  for (const [q, r] of TILES) {
    for (let j = 0; j < 6; j++) {
      const w = bridgeWidth(q, r, j);
      const tag = `(${q},${r}) j=${j}`;
      ok(w >= 0.30 * HEX_S - 1e-12 && w <= 0.45 * HEX_S + 1e-12, `${tag} 总宽 ${w.toFixed(4)} ∈ [0.30,0.45]×HEX_S`);
      ok(w / 2 >= 0.30 - 1e-12 && w / 2 <= 0.45 + 1e-12, `${tag} 半宽 ${(w / 2).toFixed(4)} ∈ [0.30,0.45]`);
      ok(w >= 0.60 - 1e-12 && w <= 0.90 + 1e-12, `${tag} 总宽 ${w.toFixed(4)} ∈ [0.60,0.90]`);
      // 确定性（宽度也必须稳定）
      ok(bridgeWidth(q, r, j) === w, `${tag} 宽度确定性`);
    }
    // 宽度由 hash 决定（粗糙岩带 ⇒ 不是每条缝都一样的宽度）
    const ws = [0, 1, 2, 3, 4, 5].map(j => bridgeWidth(q, r, j));
    ok(new Set(ws.map(v => v.toFixed(9))).size >= 4, `(${q},${r}) 6 个方向桥宽不全相同 ` + ws.map(v => v.toFixed(4)).join(' '));
  }
}

/* C2~C7 · 桥体：不越界、跨骑、横截面、覆盖比、高度、确定性。 */
{
  let globalMaxTopW = -Infinity, globalMinTopW = Infinity;
  for (const [q, r] of TILES) {
    for (let j = 0; j < 6; j++) {
      const tris = bridgeTris(q, r, j);
      const w = bridgeWidth(q, r, j);
      const f = seamFrame(q, r, j);
      const tag = `(${q},${r}) j=${j}`;
      ok(tris.length > 0 && tris.length <= 48, `${tag} 三角形数 ${tris.length} ∈ (0,48]`);
      ok(tris.every(t => t.band === Band.Bridge), `${tag} band = Band.Bridge`);
      const vs = uniqVerts(tris);
      ok(vs.every(p => Number.isFinite(p.x) && Number.isFinite(p.y) && Number.isFinite(p.z)), `${tag} 无 NaN`);
      // C3 · 不得越过接缝：每个顶点相对公共边线的偏移 ≤ 半宽
      for (const p of vs) {
        const d = Math.abs(signedToSeam(p, f));
        ok(d <= w / 2 + 1e-6, `${tag} 顶点偏移 ${d.toFixed(5)} ≤ 半宽 ${(w / 2).toFixed(5)}`);
      }
      // C4 · R4 A32：每个顶点都在其所属那一侧地块的六边形内
      for (const p of vs) {
        const d = signedToSeam(p, f);
        const c = d < 0 ? f.cA : f.cB;
        ok(inHex(p, c.x, c.z, A32_LIM), `${tag} 顶点在本侧地块六边形内 margin=${hexMargin(p, c.x, c.z).toFixed(6)}`);
      }
      // 桥确实跨骑：A 侧与 B 侧都有顶点
      const hasA = vs.some(p => signedToSeam(p, f) < 0);
      const hasB = vs.some(p => signedToSeam(p, f) > 0);
      ok(hasA && hasB, `${tag} 桥跨骑公共边（A 侧 ${hasA} / B 侧 ${hasB}）`);
      // C5 · 横截面宽度：最大横截面 = 总宽；顶面宽度 ≤ 总宽
      let maxCross = 0;
      const byAlong = new Map<string, number[]>();
      for (const p of vs) {
        const k = alongSeam(p, f).toFixed(4);
        if (!byAlong.has(k)) { byAlong.set(k, []); }
        byAlong.get(k)!.push(signedToSeam(p, f));
      }
      let minTopW = Infinity, maxTopW = -Infinity;
      for (const [, ds] of byAlong) {
        maxCross = Math.max(maxCross, Math.max(...ds) - Math.min(...ds));
      }
      // 顶面（y > −0.3）的横向宽度
      const topPts = vs.filter(p => p.y > -0.3);
      const topByAlong = new Map<string, number[]>();
      for (const p of topPts) {
        const k = alongSeam(p, f).toFixed(4);
        if (!topByAlong.has(k)) { topByAlong.set(k, []); }
        topByAlong.get(k)!.push(signedToSeam(p, f));
      }
      for (const [, ds] of topByAlong) {
        const tw = Math.max(...ds) - Math.min(...ds);
        minTopW = Math.min(minTopW, tw); maxTopW = Math.max(maxTopW, tw);
      }
      ok(near(maxCross, w, 1e-6), `${tag} 最大横截面 ${maxCross.toFixed(5)} = 总宽 ${w.toFixed(5)}`);
      ok(maxTopW <= w + 1e-9, `${tag} 顶面宽度 ${maxTopW.toFixed(5)} ≤ 总宽 ${w.toFixed(5)}`);
      ok(minTopW >= 0.30 - 1e-9, `${tag} 最小顶面宽度 ${minTopW.toFixed(5)} ≥ 0.30（不塌成一条线）`);
      globalMinTopW = Math.min(globalMinTopW, minTopW); globalMaxTopW = Math.max(globalMaxTopW, maxTopW);
      // C6 · 沿接缝覆盖 40%~70%
      const svals = vs.map(p => alongSeam(p, f));
      const span = Math.max(...svals) - Math.min(...svals);
      ok(span >= 0.40 * TOP_R - 1e-6 && span <= 0.70 * TOP_R + 1e-6, `${tag} 覆盖 ${(span / TOP_R).toFixed(4)} ∈ [0.40,0.70]`);
      // C7 · 高度：桥顶 ≈ 草顶上方一点点，桥底 = −0.55（埋进土层壁）
      const ys = vs.map(p => p.y);
      ok(near(Math.min(...ys), -0.55, 1e-9), `${tag} 桥底 y = −0.55（埋进土层壁）`);
      ok(Math.max(...ys) >= 0.005 - 1e-9 && Math.max(...ys) <= 0.08, `${tag} 桥顶最高点 ${Math.max(...ys).toFixed(5)} ∈ [0.005,0.08]`);
      ok(vs.some(p => near(p.y, 0.005, 1e-9)), `${tag} 两端沉到草面 y=0.005`);
    }
  }
  ok(globalMinTopW > 0, `顶面宽度实测区间 [${globalMinTopW.toFixed(4)}, ${globalMaxTopW.toFixed(4)}]`);
}

/* C8 · 确定性：同 (q,r,j) 两次调用逐分量相等。 */
{
  for (const [q, r] of TILES) {
    for (let j = 0; j < 6; j++) {
      ok(sameTris(bridgeTris(q, r, j), bridgeTris(q, r, j)), `(${q},${r}) j=${j} 岩桥确定性`);
      ok(sameTris(seamTris(q, r, j), seamTris(q, r, j)), `(${q},${r}) j=${j} 接缝确定性`);
      ok(sameTris(rampTris(q, r, j, 0.25), rampTris(q, r, j, 0.25)), `(${q},${r}) j=${j} 斜面确定性`);
    }
  }
}

/* C9 · 不同方向的桥位置不同（沿缝相对滑移由 hash 决定，不是固定位置）。 */
{
  for (const [q, r] of [[0, 0], [3, 4], [2, -1]] as ReadonlyArray<readonly [number, number]>) {
    const slides: number[] = [];
    for (let j = 0; j < 6; j++) {
      const f = seamFrame(q, r, j);
      const vs = uniqVerts(bridgeTris(q, r, j));
      let sum = 0;
      for (const p of vs) { sum += alongSeam(p, f); }
      slides.push(sum / vs.length);
    }
    const distinct = new Set(slides.map(v => v.toFixed(4))).size;
    ok(distinct >= 2, `(${q},${r}) 6 个方向的桥滑移各不相同 distinct=${distinct}`);
    ok(new Set(slides.map(v => v.toFixed(4))).size === 6, `(${q},${r}) 6 个方向滑移互异 ${slides.map(v => v.toFixed(3)).join(' ')}`);
  }
}

/* ================================================================== D · 高差衔接（斜面） */

/* D1~D6 · dh=0 / |dh|>0.5 → 空；否则 6 个三角形、两端分别贴住两块地顶面。 */
{
  for (const [q, r] of TILES) {
    for (let j = 0; j < 6; j++) {
      const tag = `(${q},${r}) j=${j}`;
      ok(rampTris(q, r, j, 0).length === 0, `${tag} dh=0 → 空数组`);
      ok(rampTris(q, r, j, 0.6).length === 0, `${tag} dh=0.6 → 空数组（超 0.5 无解）`);
      ok(rampTris(q, r, j, -0.6).length === 0, `${tag} dh=−0.6 → 空数组`);
      for (const dh of [0.25, -0.25, 0.5, -0.5]) {
        const tris = rampTris(q, r, j, dh);
        ok(tris.length === 6, `${tag} dh=${dh} → 6 个三角形 ` + tris.length);
        ok(tris.every(t => t.band === Band.Ramp), `${tag} dh=${dh} band = Band.Ramp`);
        const vs = uniqVerts(tris);
        ok(vs.every(p => Number.isFinite(p.x) && Number.isFinite(p.y) && Number.isFinite(p.z)), `${tag} dh=${dh} 无 NaN`);
        const ys = vs.map(p => p.y);
        ok(near(Math.max(...ys) - Math.min(...ys), Math.abs(dh), 1e-9), `${tag} dh=${dh} 两端高度差 = ${(Math.max(...ys) - Math.min(...ys)).toFixed(6)}`);
        ok(near(Math.max(...ys), Math.max(0, dh), 1e-9), `${tag} dh=${dh} 最高端 y=${Math.max(0, dh)}`);
        ok(near(Math.min(...ys), Math.min(0, dh), 1e-9), `${tag} dh=${dh} 最低端 y=${Math.min(0, dh)}`);
        // 两端分别落在两块地的顶面（六边形 footprint 内）：本块端恒 y=0，邻居端恒 y=dh
        const f = seamFrame(q, r, j);
        const aSide = vs.filter(p => near(p.y, 0, 1e-9));
        const bSide = vs.filter(p => near(p.y, dh, 1e-9));
        ok(aSide.length >= 2 && bSide.length >= 2, `${tag} dh=${dh} 两端各至少 2 个顶点 (${aSide.length}/${bSide.length})`);
        ok(aSide.every(p => inHex(p, f.cA.x, f.cA.z, A32_LIM)), `${tag} dh=${dh} 本块端在本块顶面内`);
        ok(bSide.every(p => inHex(p, f.cB.x, f.cB.z, A32_LIM)), `${tag} dh=${dh} 邻居端在邻居顶面内`);
        ok(tris.every(t => triArea(t) > 0), `${tag} dh=${dh} 三角形面积 > 0`);
      }
    }
  }
}

/* ================================================================== E · 关键几何事实自洽 */

/* E1 · 相邻两块地的真 footprint 在公共边上正好相切：公共边线距各自中心 = HEX_INRADIUS。 */
{
  for (const [q, r] of TILES) {
    for (let j = 0; j < 6; j++) {
      const f = seamFrame(q, r, j);
      const dA = Math.hypot(f.mid.x - f.cA.x, f.mid.z - f.cA.z);
      const dB = Math.hypot(f.mid.x - f.cB.x, f.mid.z - f.cB.z);
      ok(near(dA, HEX_INRADIUS, 1e-9), `(${q},${r}) j=${j} 公共边线距本块中心 = HEX_INRADIUS（${dA.toFixed(9)}）`);
      ok(near(dB, HEX_INRADIUS, 1e-9), `(${q},${r}) j=${j} 公共边线距邻居中心 = HEX_INRADIUS（${dB.toFixed(9)}）`);
      ok(near(Math.hypot(f.cB.x - f.cA.x, f.cB.z - f.cA.z), 2 * HEX_INRADIUS, 1e-9), `(${q},${r}) j=${j} 两中心距 = 2·HEX_INRADIUS`);
    }
  }
}

/* E2 · 公共边线落在两块 footprint 的**并集内部** ⇒ 岩桥可对称跨骑而不违反 A32。 */
{
  for (const [q, r] of [[0, 0], [1, 0], [-2, 5]] as ReadonlyArray<readonly [number, number]>) {
    for (let j = 0; j < 6; j++) {
      const f = seamFrame(q, r, j);
      const tag = `(${q},${r}) j=${j}`;
      // 公共边中点
      const pm = { x: f.mid.x, y: 0, z: f.mid.z };
      // 公共边中点周围的一小圈都必须落在 A ∪ B 内（两块 footprint 的并集）
      for (const rho of [0.05, 0.15, 0.3]) {
        for (let k = 0; k < 16; k++) {
          const ang = (k / 16) * Math.PI * 2;
          const sx = pm.x + Math.cos(ang) * rho, sz = pm.z + Math.sin(ang) * rho;
          const inA = inHex({ x: sx, y: 0, z: sz }, f.cA.x, f.cA.z);
          const inB = inHex({ x: sx, y: 0, z: sz }, f.cB.x, f.cB.z);
          ok(inA || inB, `${tag} 公共边中点周围 ρ=${rho} 的样本落在两地块并集内`);
        }
      }
      // 公共边中点相对两块中心都恰好在 footprint 边界上（相切）
      ok(near(hexMargin(pm, f.cA.x, f.cA.z), 0, 1e-9), `${tag} 公共边中点在 A 的 footprint 边界上`);
      ok(near(hexMargin(pm, f.cB.x, f.cB.z), 0, 1e-9), `${tag} 公共边中点在 B 的 footprint 边界上`);
    }
  }
}

/* ================================================================== 汇总输出 */

const seamMeasured = (() => {
  const f = seamFrame(0, 0, 0);
  const ds = uniqVerts(seamTris(0, 0, 0)).map(p => signedToSeam(p, f));
  return Math.max(...ds) - Math.min(...ds);
})();
const bridgeMeasured = TILES.flatMap(([q, r]) => [0, 1, 2, 3, 4, 5].map(j => bridgeWidth(q, r, j)));
const out = {
  checks,
  fails: fails.length,
  list: fails.slice(0, 30),
  measured: {
    seamWidth: seamMeasured,
    seamWidthNominal: GAP_NOMINAL,
    bridgeWidthMin: Math.min(...bridgeMeasured),
    bridgeWidthMax: Math.max(...bridgeMeasured),
    bridgeWidthRatioMin: Math.min(...bridgeMeasured) / HEX_S,
    bridgeWidthRatioMax: Math.max(...bridgeMeasured) / HEX_S,
    bridgeTriMax: Math.max(...TILES.flatMap(([q, r]) => [0, 1, 2, 3, 4, 5].map(j => bridgeTris(q, r, j).length)))
  }
};
writeFileSync(process.argv[2] ?? '/tmp/island-connect.json', JSON.stringify(out, null, 2));
if (fails.length > 0) {
  console.error(`S-25 连接带单测：${checks} 断言，失败 ${fails.length} 条`);
  for (const f of fails.slice(0, 12)) { console.error(' - ' + f); }
  process.exit(1);
}
console.log(`S-25 连接带单测：${checks} 断言全部通过`);
console.log(`  缝宽实测 ${seamMeasured.toFixed(6)}（标称 ${GAP_NOMINAL.toFixed(6)}）`);
console.log(`  岩桥总宽实测 [${out.measured.bridgeWidthMin.toFixed(4)}, ${out.measured.bridgeWidthMax.toFixed(4)}] = [${out.measured.bridgeWidthRatioMin.toFixed(3)}, ${out.measured.bridgeWidthRatioMax.toFixed(3)}]×HEX_S`);
console.log(`  岩桥三角形数上限 ${out.measured.bridgeTriMax}`);
