GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / globalgrid2050 / solar-design-studio/202609270220-site-world-v3/world

Plant Template and 1 more file (part 1)

A JavaScript module in the world folder of GlobalGrid2050 that works with transformers, cables, solar and 33kV, using IEC 60287 and IEC 60949.

454 lines of JavaScript from globalgrid2050, in 2 files. Topic: Solar and storage design. Section 141 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Plant Template electrical · globalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/plant-template.mjs lines 1–240
  2. Plant UI interaction · globalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/plant-ui.mjs lines 1–214

Plant Template

A JavaScript module in the world folder of GlobalGrid2050 that works with transformers, cables, solar and 33kV, using IEC 60287 and IEC 60949.

electricalglobalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/plant-template.mjs · lines 1–240 of 240 · version 2026-09-27 02:20 · Not reached from any entry point (candidate for review) · pattern layoutDiagram (shared by 4 files)

What it does
It calculates transformers, cables, solar and 33kV. Defines 16 functions or classes, including up, r3, autoPocKv, modulesPerString, faultMinArea.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: transformers, cables, solar, 33kV, 400kV, 1500V.
Inputs & outputs
Voltage levels named: 400kV, 33kV, 1500V.
Downstream impact
Used directly by 5 files: Block MV (globalgrid2050); Design Options (globalgrid2050); MV Network (globalgrid2050); Plant Layout (globalgrid2050); and 1 more.
What it achieves
It sizes feeder (`sizeFeeder`) and is built from the auto poc kV helper (`autoPocKv`) and the modules per string helper (`modulesPerString`). A generic, parameterised solar plant block diagram, sized from engineering rules. Its code works with 33 kV, 10 MVA and 240 MVA.
Why it matters
Imported by 5 files, including Block MV, Design Options and MV Network.
Application
globalgrid2050 · solar-design-studio/202609270220-site-world-v3/world · JavaScript module
Uses
Cable Rating (import)
Used by
imported by Block MV (import), imported by Design Options (import), imported by MV Network (import), imported by Plant Layout (import), imported by Plant UI (import), mentioned in Standalone (comment link)
Produces
STATION_MVA, GRID_MVA, TEMPLATE_DEFAULTS, autoPocKv, modulesPerString, faultMinArea, plantTemplate, gridChoice, pack, layoutDiagram
Defines here
up, r3, autoPocKv, modulesPerString, faultMinArea, plantTemplate, node, link, check, gridChoice, maxLoad, pack, L, sizeFeeder, drop, layoutDiagram
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270220-site-world-v3/world/plant-template.mjs:1-240 · blob 1004d0148f9d6303da31337a49a310b13a60f1e3 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// plant-template.mjs: a generic, parameterised solar plant block diagram, sized from engineering rules.
//
// Give it a target export in MW and any of the choices below; it works out the string length, strings per
// inverter, stations, 33 kV feeders (radial chains, or rings with a normally-open point), MV board sections with
// normally-open ties, grid transformers and the connection, then sizes each feeder cable segment from the load it
// carries (cable-rating.mjs, IEC 60287 method) and checks every level against its limit. Counts come out of the
// arithmetic, so no size reproduces any real plant. Illustrative: a real design is set by studies.
//
// Ranges (general practice; the defaults sit inside them):
//   string length: cold open-circuit voltage stays under the 1500 V system limit; 12-24 strings per inverter
//   string inverters 100-350 kVA; 8-30 per station, a smaller station takes any remainder
//   station transformers 2.5-10 MVA, ONAN, two LV windings (Dy11y11), one auxiliary transformer each
//   33 kV feeder 20-30 MVA and 2-4 stations; 2-6 solar feeders per board section plus spares
//   grid transformers 1.0-1.2 x the export in total (30-240 MVA steps); connection at 132, 275 or 400 kV (33 kV up to about 30 MW)
//   MV voltage drop 0.5 % or less; conductor short-circuit by the adiabatic rule (IEC 60949, k = 94 for Al XLPE)
// Pure: imports only the cable rating.

import { sizeFor, dropPercent, rating, SIZES } from './cable-rating.mjs';

export const STATION_MVA = Object.freeze([2.5, 3.15, 4, 5, 6.3, 8, 10]);
export const GRID_MVA = Object.freeze([20, 30, 40, 45, 60, 75, 90, 100, 120, 150, 180, 200, 240]);

export const TEMPLATE_DEFAULTS = Object.freeze({
  dcAcRatio: 1.25, moduleWp: 600, moduleVoc: 50, vocCoeffPerK: -0.0027, minCellC: -10, systemV: 1500,
  inverterKVA: 300, invertersPerStation: 20, stringsMin: 12, stringsMax: 24, powerFactor: 0.95,
  feederLimitMVA: 25, stationsPerFeederMax: 4, feedersPerBoardMax: 6, spareWays: 1, topology: 'radial',
  gridFactor: 1.1, gridUnits: null, gridBank: 'three-phase', pocKv: null, harmonicFilter: false,
  headLengthM: 1500, linkLengthM: 300, vdropLimitPct: 0.5, maxUtilisation: 0.9, faultKA: 20, faultS: 1, soilKmW: 1.2
});

const up = (steps, v) => steps.find(s => s >= v - 1e-9) ?? null;
const r3 = v => (v == null ? v : Math.round(v * 1000) / 1000);

export const autoPocKv = mw => (mw <= 30 ? 33 : mw <= 150 ? 132 : 400);

// Modules per string: the most whose open-circuit voltage at the coldest cell temperature stays under the limit.
export function modulesPerString(p) {
  const vCold = p.moduleVoc * (1 + p.vocCoeffPerK * (p.minCellC - 25));
  return Math.floor(p.systemV / vCold);
}

// Smallest conductor that survives the fault: A >= I * sqrt(t) / k, k = 94 for aluminium XLPE 90 to 250 C.
export const faultMinArea = (kA, s) => SIZES.find(a => a >= kA * 1000 * Math.sqrt(s) / 94) ?? SIZES.at(-1);

/**
 * plantTemplate({ targetMW, ...choices }) -> { params, counts, ratings, nodes, links, feeders, checks, ok, note }
 * nodes: { id, kind, label, rating } ; links: { from, to, kind, kv, mva, areaMm2?, lengthM?, normallyOpen? }
 */
export function plantTemplate(opts = {}) {
  const p = { ...TEMPLATE_DEFAULTS, ...opts }, mw = Number(p.targetMW);
  if (!(mw > 0 && mw <= 5000)) throw new Error('plant template: targetMW must be between 0 and 5000');
  if (!(p.inverterKVA >= 100 && p.inverterKVA <= 350)) throw new Error('plant template: inverterKVA must be 100 to 350');
  if (!(p.invertersPerStation >= 8 && p.invertersPerStation <= 30)) throw new Error('plant template: invertersPerStation must be 8 to 30');
  const kvMv = 33, kvPoc = p.pocKv || autoPocKv(mw);
  const mps = modulesPerString(p), stringKWp = mps * p.moduleWp / 1000;
  const spi = Math.min(p.stringsMax, Math.max(p.stringsMin, Math.round(p.inverterKVA * p.dcAcRatio / stringKWp)));
  const inverters = Math.ceil(mw / p.powerFactor * 1000 / p.inverterKVA);

  // Stations: full ones of the chosen size; a smaller station takes the remainder.
  const full = Math.floor(inverters / p.invertersPerStation), rest = inverters % p.invertersPerStation;
  const stationInv = [...Array(full).fill(p.invertersPerStation), ...(rest ? [rest] : [])];
  const stations = stationInv.map((n, i) => ({ id: `S${i + 1}`, inverters: n, kva: n * p.inverterKVA,
    mva: up(STATION_MVA, n * p.inverterKVA / 1000) ?? n * p.inverterKVA / 1000 }));

  // Feeders: as many stations as both the feeder limit and the cap allow.
  const stMax = Math.max(...stations.map(s => s.kva / 1000));
  const perFeeder = Math.max(1, Math.min(p.stationsPerFeederMax, Math.floor(p.feederLimitMVA / stMax)));
  const nFeeders = Math.ceil(stations.length / perFeeder);
  const cableOpts = { soilKmW: p.soilKmW, kv: kvMv };
  const minArea = faultMinArea(p.faultKA, p.faultS);
  const feeders = [];
  for (let f = 0, k = 0; f < nFeeders; f++) {
    const n = Math.floor(stations.length / nFeeders) + (f < stations.length % nFeeders ? 1 : 0);
    const chain = stations.slice(k, k + n); k += n;
    feeders.push(sizeFeeder(chain, p, cableOpts, minArea));
  }

  // Grid transformers, then feeders packed onto them by load, then board sections of at most N solar ways each.
  const gridTotal = mw * p.gridFactor;
  const grid = kvPoc === kvMv ? { units: 0, mva: null, smallest: false } : gridChoice(mw, gridTotal, p.gridUnits, feeders);
  const { units: gridUnits, mva: gridMVA } = grid;
  const txOf = pack(feeders, Math.max(1, gridUnits));
  const sections = [];                                     // [{ tx, feeders: [] }]
  for (let t = 0; t < Math.max(1, gridUnits); t++) {
    const mine = feeders.filter((f, i) => txOf[i] === t), n = Math.max(1, Math.ceil(mine.length / p.feedersPerBoardMax));
    for (let k = 0; k < n; k++) sections.push({ tx: t, feeders: mine.filter((f, j) => j % n === k) });
  }
  const boards = sections.length;
  const nodes = [], links = [];
  const node = (id, kind, label, rating = {}) => nodes.push({ id, kind, label, rating });
  const link = (from, to, kind, kv, mva, extra = {}) => links.push({ from, to, kind, kv, mva: r3(mva), ...extra });
  node('POC', 'poc', `Connection ${kvPoc} kV`, { kv: kvPoc, exportMW: mw });
  if (p.harmonicFilter && gridUnits) { node('HF', 'harmonic-filter', 'Harmonic filter (optional)', { kv: kvPoc }); link('POC', 'HF', 'hv-bus', kvPoc, 0); }
  for (let g = 0; g < gridUnits; g++) {
    node(`GT${g + 1}`, 'grid-transformer', `Grid transformer ${g + 1}: ${gridMVA} MVA ${kvPoc}/${kvMv} kV, ${p.gridBank}`,
      { mva: gridMVA, kv: [kvPoc, kvMv], bank: p.gridBank });
    link('POC', `GT${g + 1}`, 'hv-cable', kvPoc, gridMVA);
  }
  const boardWays = sections.map(x => x.feeders.length), txLoad = new Array(Math.max(1, gridUnits)).fill(0);
  sections.forEach((sec, b) => {
    node(`MVB${b + 1}`, 'switchboard', `${kvMv} kV board section ${b + 1}`, { kv: kvMv, spareWays: p.spareWays });
    if (gridUnits) link(`GT${sec.tx + 1}`, `MVB${b + 1}`, 'mv-bus', kvMv, gridMVA);
    else link('POC', `MVB${b + 1}`, 'mv-cable', kvMv, mw / p.powerFactor);
    if (b) link(`MVB${b}`, `MVB${b + 1}`, 'bus-tie', kvMv, 0, { normallyOpen: true });
    for (const f of sec.feeders) { f.board = `MVB${b + 1}`; txLoad[sec.tx] += f.loadMVA; }
  });
  feeders.forEach(f => {
    const bid = f.board;
    f.chain.forEach((s, k) => {
      node(s.id, 'station', `Station ${s.id.slice(1)}: ${s.inverters} x ${p.inverterKVA} kVA, ${s.mva} MVA`,
        { mva: s.mva, kva: s.kva, inverters: s.inverters, strings: s.inverters * spi, modulesPerString: mps });
      node(`R${s.id.slice(1)}`, 'rmu', `Ring main unit ${s.id.slice(1)}`, { kv: kvMv, amps: 630 });
      node(`A${s.id.slice(1)}`, 'aux', `Auxiliary transformer ${s.id.slice(1)}`, {});
      link(`R${s.id.slice(1)}`, s.id, 'station-tee', kvMv, s.mva); link(s.id, `A${s.id.slice(1)}`, 'aux', 0.4, 0);
      const seg = f.segments[k];
      link(k ? `R${f.chain[k - 1].id.slice(1)}` : bid, `R${s.id.slice(1)}`, 'feeder-cable', kvMv, seg.loadMVA,
        { areaMm2: seg.area, lengthM: seg.lengthM });
    });
  });
  if (p.topology === 'ring') for (let i = 0; i + 1 < feeders.length; i += 2) {
    const a = feeders[i].chain.at(-1).id.slice(1), b = feeders[i + 1].chain.at(-1).id.slice(1);
    link(`R${a}`, `R${b}`, 'feeder-cable', kvMv, 0, { normallyOpen: true, areaMm2: feeders[i].segments.at(-1).area, lengthM: p.linkLengthM });
  }

  const check = (name, value, max, min = -Infinity) => ({ name, value: r3(value), min, max, ok: value <= max + 1e-9 && value >= min - 1e-9 });
  const checks = [
    check('modules per string (1500 V, cold)', mps, 32, 26),
    check('strings per inverter', spi, p.stringsMax, p.stringsMin),
    check('DC/AC ratio', spi * stringKWp / p.inverterKVA, 1.4, 1.1),
    check('station load / transformer', Math.max(...stations.map(s => s.kva / 1000 / s.mva)), 1),
    check('feeder load MVA', Math.max(...feeders.map(f => f.loadMVA)), p.feederLimitMVA),
    check('cable utilisation (worst segment)', Math.max(...feeders.flatMap(f => f.segments.map(s => s.utilisation))), p.maxUtilisation),
    check('MV voltage drop % (worst feeder)', Math.max(...feeders.map(f => f.dropPct)), p.vdropLimitPct),
    check('solar feeders per board section', Math.max(...boardWays), p.feedersPerBoardMax),
    // 1.0-1.2 x export; above that only when no standard step fits (grid.smallest), and then it is said so.
    check(grid.smallest ? 'grid transformers / export (smallest standard size that carries the load)' : 'grid transformers / export',
      gridUnits ? gridUnits * gridMVA / mw : 1, grid.smallest ? Infinity : 1.2 + 1e-6, 1.0),
    check('load on each grid transformer', gridUnits ? Math.max(...txLoad) / gridMVA : 0, 1)
  ];
  const counts = { modulesPerString: mps, stringsPerInverter: spi, inverters, strings: inverters * spi, modules: inverters * spi * mps,
    stations: stations.length, feeders: nFeeders, stationsPerFeederMax: perFeeder, boardSections: boards, gridTransformers: gridUnits };
  const ratings = { collectorKv: kvMv, pocKv: kvPoc, inverterKVA: p.inverterKVA, stationMVA: [...new Set(stations.map(s => s.mva))],
    gridMVA, feederLimitMVA: p.feederLimitMVA, faultMinAreaMm2: minArea, acMVA: r3(inverters * p.inverterKVA / 1000),
    dcMWp: r3(counts.strings * stringKWp / 1000), cableSizesMm2: [...new Set(feeders.flatMap(f => f.segments.map(s => s.area)))].sort((a, b) => a - b) };
  return { params: p, counts, ratings, nodes, links, feeders, checks, ok: checks.every(c => c.ok),
    note: 'Generic template from rating rules; illustrative, not a design for any site. Segment lengths are placeholders until set from a layout.' };
}

// Grid transformers: the least total standard MVA that carries the feeders as packed (fewer units on a tie).
// Within 1.0-1.2 x the export where a standard step allows it; below about 40 MW no step does, and the choice is
// flagged as the smallest standard size that carries the load (smallest: true), not forced up or down.
export function gridChoice(mw, total, fixedUnits = null, feeders = []) {
  const loadTotal = feeders.reduce((s, f) => s + f.loadMVA, 0) || total;
  const first = fixedUnits || Math.max(1, Math.ceil(loadTotal / GRID_MVA.at(-1)));
  const maxLoad = n => { const t = pack(feeders, n), load = new Array(n).fill(0);
    feeders.forEach((f, i) => { load[t[i]] += f.loadMVA; }); return feeders.length ? Math.max(...load) : loadTotal / n; };
  let best = null;
  for (let n = first; n <= (fixedUnits || first + 8); n++) {
    const mva = up(GRID_MVA, maxLoad(n));
    if (mva == null) continue;
    if (!best || n * mva < best.units * best.mva - 1e-9) best = { units: n, mva };
  }
  if (!best) best = { units: first, mva: GRID_MVA.at(-1) };
  best.smallest = best.units * best.mva > 1.2 * mw + 1e-9;
  return best;
}

// Feeders onto n transformers: largest first onto the least-loaded one, then single moves and pairwise swaps
// while they lower the heaviest transformer's load. Returns the transformer index per feeder.
export function pack(feeders, n) {
  const load = new Array(n).fill(0), out = new Array(feeders.length);
  feeders.map((f, i) => [f.loadMVA, i]).sort((a, b) => b[0] - a[0]).forEach(([l, i]) => {
    const t = load.indexOf(Math.min(...load)); out[i] = t; load[t] += l;
  });
  const L = i => feeders[i].loadMVA;
  for (let pass = 0, better = true; better && pass < 200; pass++) {
    better = false;
    const hi = load.indexOf(Math.max(...load));
    for (let i = 0; i < out.length && !better; i++) {
      if (out[i] !== hi) continue;
      for (let t = 0; t < n && !better; t++) {
        if (t === hi) continue;
        if (Math.max(load[hi] - L(i), load[t] + L(i)) < load[hi] - 1e-9) {        // move i to t
          load[hi] -= L(i); load[t] += L(i); out[i] = t; better = true; break;
        }
        for (let j = 0; j < out.length; j++) {                                    // swap i with j on t
          if (out[j] !== t || L(j) >= L(i)) continue;
          const d = L(i) - L(j);
          if (Math.max(load[hi] - d, load[t] + d) < load[hi] - 1e-9) {
            load[hi] -= d; load[t] += d; out[i] = t; out[j] = hi; better = true; break;
          }
        }
      }
    }
  }
  return out;
}

// Size each segment of a radial chain from the load it carries, then upsize from the head until the drop is met.
function sizeFeeder(chain, p, cableOpts, minArea) {
  const segments = chain.map((s, k) => {
    const loadMVA = chain.slice(k).reduce((t, x) => t + x.kva / 1000, 0);
    const pick = sizeFor(loadMVA / p.maxUtilisation, { ...cableOpts, minArea }) || { area: SIZES.at(-1) };
    return { loadMVA, area: pick.area, lengthM: k ? p.linkLengthM : p.headLengthM };
  });
  const drop = () => segments.reduce((t, s) => t + dropPercent(s.area, s.lengthM, s.loadMVA, { ...cableOpts, pf: p.powerFactor }), 0);
  for (let guard = 0; drop() > p.vdropLimitPct && guard < 40; guard++) {
    const s = segments.find(x => x.area < SIZES.at(-1));
    if (!s) break;
    // Upsize the segment that saves most drop per step: the most loaded, longest one still below the top size.
    const best = segments.filter(x => x.area < SIZES.at(-1)).sort((a, b) => b.loadMVA * b.lengthM - a.loadMVA * a.lengthM)[0];
    best.area = SIZES[SIZES.indexOf(best.area) + 1];
  }
  for (const s of segments) s.utilisation = s.loadMVA * 1e6 / (Math.sqrt(3) * cableOpts.kv * 1000) / rating(s.area, cableOpts).amps;
  return { chain, segments, loadMVA: segments[0].loadMVA, dropPct: drop() };
}

/**
 * layoutDiagram(d) -> nodes with schematic positions { x, y } in panel units: connection at the top, grid
 * transformers, board sections, then each feeder as a column of ring main units with their stations beside them.
 */
export function layoutDiagram(d) {
  const pos = new Map(), boards = d.nodes.filter(n => n.kind === 'switchboard');
  const byBoard = boards.map(b => d.feeders.filter(f => f.board === b.id));
  let x = 0;
  boards.forEach((b, i) => {
    const w = Math.max(1, byBoard[i].length);
    pos.set(b.id, { x: x + (w - 1) / 2, y: 2 });
    byBoard[i].forEach((f, j) => f.chain.forEach((s, k) => {
      const n = s.id.slice(1);
      pos.set(`R${n}`, { x: x + j, y: 3 + k }); pos.set(s.id, { x: x + j + 0.4, y: 3 + k }); pos.set(`A${n}`, { x: x + j + 0.4, y: 3.4 + k });
    }));
    x += w + 1;
  });
  const gts = d.nodes.filter(n => n.kind === 'grid-transformer');
  gts.forEach((g, i) => { const b = pos.get(`MVB${i + 1}`) || { x: i * 2 }; pos.set(g.id, { x: b.x, y: 1 }); });
  const mid = (Math.max(0, ...[...pos.values()].map(v => v.x))) / 2;
  pos.set('POC', { x: mid, y: 0 }); pos.set('HF', { x: mid + 1, y: 0 });
  return d.nodes.map(n => ({ ...n, ...(pos.get(n.id) || { x: 0, y: 0 }) }));
}

Plant UI

A JavaScript module in the world folder of GlobalGrid2050 that draws ground (`drawGround`), sets boundary (`setBoundary`), builds lines (`buildLines`) and calculates planar distances (units: MW, kV).

interactionglobalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/plant-ui.mjs · lines 1–214 of 214 · version 2026-09-27 02:20 · Not reached from any entry point (candidate for review) · pattern clearLayout (shared by 2 files)

What it does
It draws substations and transformers. Defines 20 functions or classes, including PAUSE, createPlant, $, say, measured. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: substations, transformers, 33kV.
Inputs & outputs
Voltage levels named: 33kV.
Downstream impact
Used directly by 1 file: Design Sections (globalgrid2050).
What it achieves
It creates plant (`createPlant`), draws ground (`drawGround`) and sets boundary (`setBoundary`). Design > Plant layout. The user draws a boundary (the Boundary tool, or the open land around them), picks a capacity and a layout, and the plant is laid out on the measured ground (`plant-layout.mjs`), in slices between frames. Its code works with 33 kV. It responds to click events.
Why it matters
Imported by Design Sections.
Application
globalgrid2050 · solar-design-studio/202609270220-site-world-v3/world · JavaScript module
Uses
Origin (import), Plant Layout (import), Plant Template (import), MV Network (import), Plant Ground (import), Measure Format (import)
Used by
imported by Design Sections (dynamic import)
Produces
createPlant
Defines here
PAUSE, createPlant, $, say, measured, drawGround, setBoundary, useOpenLand, run, buildLines, make, put, seg, at, path, c, place, batches, showReport, clearLayout
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270220-site-world-v3/world/plant-ui.mjs:1-214 · blob b230190158317ef8e5651b53c1b013e45818dca7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// plant-ui.mjs: Design > Plant layout. The user draws a boundary (the Boundary tool, or the open land around them),
// picks a capacity and a layout, and the plant is laid out on the measured ground (plant-layout.mjs), in slices
// between frames. It is drawn as quiet lines: fence, tables, roads, stations, the compound and the MV trenches.
// Everything is held in national-grid metres; each batch keeps its positions relative to its own base point, so
// a move of the site origin only moves the base (no rebuild, no upload).

import { toBng, toLocal } from './origin.mjs';
import { layoutPlantAsync, LAYOUTS, LABEL, tableGeometry, LAYOUT_DEFAULTS } from './plant-layout.mjs';
import { plantTemplate } from './plant-template.mjs';
import { equipmentSolids, solidLines } from './mv-network.mjs';
import { createSiteGround } from './plant-ground.mjs';
import { formatNumber, formatLength } from './measure-format.mjs';

const COLOUR = { fence: [0.8, 0.8, 0.8, 0.7], tables: [0.6, 0.67, 0.78, 0.55], roads: [0.78, 0.74, 0.62, 0.6],
  equipment: [0.85, 0.88, 0.95, 1], mv: [1, 0.55, 0.25, 0.9] };
const PAUSE = () => new Promise(r => setTimeout(r, 0));

// deps: { doc, origin(), viewer(), measuredAt(x, y) local, heightAt(x, y) local, assets() -> [{ kind, e, n }], redraw(),
//   nearest(e, n) -> Promise<{ e, n } | null> the nearest substation in the national index }
export function createPlant({ doc, origin, viewer, measuredAt, heightAt, assets = () => [], nearest = null, redraw }) {
  const $ = id => doc.getElementById(id);
  const ground = createSiteGround();
  const state = { boundary: null, result: null, draw: null, running: false, version: 0, summary: null, rows: null };
  const say = (msg, warn = false) => { const el = $('plant-status'); el.textContent = msg; el.className = warn ? 'warn' : ''; };
  const measured = fn => (e, n) => {
    const h = fn(e, n);
    if (Number.isFinite(h)) return h;
    const [x, y] = toLocal(origin(), e, n);
    return measuredAt(x, y);
  };
  let sample = ground.heightAt;
  const drawGround = (e, n) => { const h = measured(sample)(e, n); if (Number.isFinite(h)) return h; const [x, y] = toLocal(origin(), e, n); return heightAt(x, y); };

  $('plant-layout').replaceChildren(...LAYOUTS.map(([id, label]) => new Option(label, id)));
  ground.start().then(() => {
    // Presets only on open-land sites; elsewhere the capacity is typed.
    $('plant-presets').hidden = !/^open-land-/.test(ground.site()?.name || '');
  }).catch(() => {});
  for (const b of doc.querySelectorAll('#plant-presets [data-mw]')) b.addEventListener('click', () => { $('plant-mw').value = b.dataset.mw; });

  function setBoundary(path) {
    if (path.length < 3) { say('A boundary needs at least three corners.', true); return false; }
    state.boundary = path.map(p => [p.e, p.n]); clearLayout(false);
    say(`Boundary set: ${path.length} corners. Choose a capacity and press Lay out.`);
    return true;
  }
  // The open land around the viewer: a square big enough for the capacity asked, kept on the measured tiles.
  async function useOpenLand() {
    await ground.start().catch(() => {});
    const mw = Number($('plant-mw').value), v = viewer(), c = toBng(origin(), v.pos[0], v.pos[1]);
    const tpl = plantTemplate({ targetMW: Math.min(5000, Math.max(1, mw || 1)) });
    const T = tableGeometry($('plant-layout').value, LAYOUT_DEFAULTS, tpl);
    const side = Math.sqrt(Math.ceil(tpl.counts.strings / 2) * T.pitch * (T.lenU + LAYOUT_DEFAULTS.tableGapM) * 1.35) + 2 * Number($('plant-fence').value);
    const x = ground.extent();
    let [e0, n0, e1, n1] = [c.e - side / 2, c.n - side / 2, c.e + side / 2, c.n + side / 2];
    if (x) { e0 = Math.max(e0, x.e0 + 1); n0 = Math.max(n0, x.n0 + 1); e1 = Math.min(e1, x.e1 - 1); n1 = Math.min(n1, x.n1 - 1); }
    setBoundary([{ e: e0, n: n0 }, { e: e1, n: n0 }, { e: e1, n: n1 }, { e: e0, n: n1 }]);
    say(`Open land around you: ${formatLength(e1 - e0)} × ${formatLength(n1 - n0)}${x ? ', kept on the measured tiles' : ''}. Press Lay out.`);
    redraw();
  }

  async function run() {
    if (state.running) return null;
    if (!state.boundary) { say('Draw a boundary, or use the open land around you, first.', true); return null; }
    state.running = true; $('plant-run').disabled = true;
    const t0 = performance.now();
    try {
      const b = state.boundary, box = { e0: Math.min(...b.map(q => q[0])), n0: Math.min(...b.map(q => q[1])),
        e1: Math.max(...b.map(q => q[0])), n1: Math.max(...b.map(q => q[1])) };
      say('Reading the measured ground under the boundary…');
      await ground.loadFor(box, k => say(`Reading the measured ground: ${k} tiles`)).catch(() => null);
      const water = await ground.water().catch(() => []); // the water layer's watercourses (OS Open Rivers), for the setback
      const mid = [(box.e0 + box.e1) / 2, (box.n0 + box.n1) / 2];
      // The compound faces the nearest substation: the national index (read tile by tile) where the page has it, else the
      // substations loaded here. With neither, the layout says so and puts the compound on the south side.
      say('Finding the nearest substation…');
      const national = nearest ? await Promise.resolve().then(() => nearest(mid[0], mid[1])).catch(() => null) : null;
      const sub = national || assets().filter(a => a.kind === 'substation')
        .sort((p, q) => Math.hypot(p.e - mid[0], p.n - mid[1]) - Math.hypot(q.e - mid[0], q.n - mid[1]))[0];
      sample = ground.sampler();
      const r = await layoutPlantAsync({ boundary: b, targetMW: Number($('plant-mw').value), layout: $('plant-layout').value,
        groundAt: measured(sample), grid: sub ? [sub.e, sub.n] : null, water,
        options: { slopeLimitPct: Number($('plant-slope').value) || 15, fenceSetbackM: Number($('plant-fence').value) || 8 } },
      { onProgress: p => say(p.phase === 'tables' ? `Laying out: ${p.candidates} positions tried, ${p.accepted} tables fit` : `Laying out: ${p.phase}`) });
      state.draw = await buildLines(r);
      r.seconds = (performance.now() - t0) / 1000; r.grid = sub || null; r.waterLines = water.length;
      state.result = r; state.version++;
      showReport(r); redraw();
      return state.summary;
    } catch (e) { say(e.message, true); return null; }
    finally { state.running = false; $('plant-run').disabled = false; }
  }

  // ---- lines, built in slices; absolute national-grid positions kept relative to a base point per batch ----
  async function buildLines(r) {
    const F = r.frame, T = r.table, P = r.params, out = {};
    const make = () => ({ base: null, v: [] });
    const put = (L, e, n, z) => { if (!L.base) L.base = [e, n, z]; L.v.push(e - L.base[0], n - L.base[1], z - L.base[2]); };
    const seg = (L, a, b) => { put(L, ...a); put(L, ...b); };
    const at = (u, v, dz = 0) => { const [e, n] = F.en(u, v); return [e, n, drawGround(e, n) + dz]; };
    const path = (L, pts, dz = 0.05, step = 10) => {                    // a draped line, one point every step metres
      for (let i = 1; i < pts.length; i++) {
        const [u0, v0] = pts[i - 1], [u1, v1] = pts[i], k = Math.max(1, Math.ceil(Math.hypot(u1 - u0, v1 - v0) / step));
        for (let s = 0; s < k; s++) seg(L, at(u0 + (u1 - u0) * s / k, v0 + (v1 - v0) * s / k, dz), at(u0 + (u1 - u0) * (s + 1) / k, v0 + (v1 - v0) * (s + 1) / k, dz));
      }
    };
    out.fence = make(); path(out.fence, [...r.boundary, r.boundary[0]], 1.5);
    out.tables = make();
    const lo = P.lowEdgeM, hi = lo + T.rise, t = r.tables;
    let t0 = performance.now();
    for (let q = 0; q < t.length; q += 6) {
      const [ua, va, h0, h1, h2, h3] = t.subarray(q, q + 6), ub = ua + T.lenU, vb = va + T.depth;
      const c = (u, v, z) => { const [e, n] = F.en(u, v); return [e, n, z]; };
      if (T.south) {
        const A = c(ua, va, h0 + lo), B = c(ub, va, h1 + lo), C = c(ub, vb, h2 + hi), D = c(ua, vb, h3 + hi);
        seg(out.tables, A, B); seg(out.tables, B, C); seg(out.tables, C, D); seg(out.tables, D, A);
      } else {
        const vm = (va + vb) / 2, A = c(ua, va, h0 + lo), B = c(ub, va, h1 + lo), C = c(ub, vb, h2 + lo), D = c(ua, vb, h3 + lo);
        const M = c(ua, vm, (h0 + h3) / 2 + hi), N = c(ub, vm, (h1 + h2) / 2 + hi);
        seg(out.tables, A, B); seg(out.tables, D, C); seg(out.tables, M, N);
        seg(out.tables, A, M); seg(out.tables, M, D); seg(out.tables, B, N); seg(out.tables, N, C);
      }
      if (performance.now() - t0 > 10) { await PAUSE(); t0 = performance.now(); }
    }
    out.roads = make();
    const sp = r.spine;
    for (const d of [-P.spineWidthM / 2, P.spineWidthM / 2]) path(out.roads, [[sp.u + d, sp.v0], [sp.u + d, sp.v1]]);
    for (const tr of r.trackRoads) for (const d of [-P.trackWidthM / 2, P.trackWidthM / 2]) path(out.roads, [[tr.u0, tr.v + d], [tr.u1, tr.v + d]]);
    if (r.access) for (const d of [-P.trackWidthM / 2, P.trackWidthM / 2]) path(out.roads, [[r.access.u0, r.access.v + d], [r.access.u1, r.access.v + d]]);
    await PAUSE();
    // Equipment: station skids at their pads, the compound fence, the switchroom and the grid transformers.
    out.equipment = make();
    const cm = r.compound, [ce, cn] = F.en(cm.u, cm.v), cz = drawGround(ce, cn), base = [ce, cn, cz];
    const solids = [];
    const place = (kind, u, v, id) => { const [e, n] = F.en(u, v); solids.push(...equipmentSolids(kind, [e - ce, n - cn, drawGround(e, n) - cz], 0, id)); };
    for (const s of r.stations) place('station', s.u, s.v, s.id);
    place('switchboard', cm.u - cm.w / 4, cm.v, 'switchroom');
    const gts = r.template?.counts.gridTransformers || 0;
    for (let g = 0; g < gts; g++) place('grid-transformer', cm.u + 4 + (g % 2) * 14 - 2, cm.v - cm.d / 4 + Math.floor(g / 2) * 10, 'GT' + (g + 1));
    out.equipment.base = base; out.equipment.v = solidLines(solids);
    path(out.fence, [[cm.u - cm.w / 2, cm.v - cm.d / 2], [cm.u + cm.w / 2, cm.v - cm.d / 2], [cm.u + cm.w / 2, cm.v + cm.d / 2],
      [cm.u - cm.w / 2, cm.v + cm.d / 2], [cm.u - cm.w / 2, cm.v - cm.d / 2]], 2.4);
    // MV trenches: beside the road they follow, one line per trench wall.
    out.mv = make();
    const off = P.trackWidthM / 2 + 1.5, sOff = P.spineWidthM / 2 + 1.5;
    for (const pc of r.electrical?.pieces || []) {
      const w = (pc.c > 1 ? 0.8 : 0.45) * Math.ceil(pc.c / 2) / 2;
      for (const d of [-w, w]) {
        if (pc.key === 's') path(out.mv, [[r.spine.u + sOff + d, pc.a], [r.spine.u + sOff + d, pc.b]], 0.02);
        else if (pc.key === 'a') path(out.mv, [[pc.a, r.access.v + off + d], [pc.b, r.access.v + off + d]], 0.02);
        else if (pc.key.startsWith('t')) { const v = r.tracks[Number(pc.key.slice(1))] + off + d; path(out.mv, [[pc.a, v], [pc.b, v]], 0.02); }
        else path(out.mv, [[pc.u + d, pc.a + off], [pc.u + d, pc.b]], 0.02);
      }
    }
    for (const k of Object.keys(out)) if (!(out[k].v instanceof Float32Array)) out[k].v = new Float32Array(out[k].v);
    return out;
  }

  function batches() {
    const out = [], o = origin(), d = state.draw;
    if (state.boundary && !d) {                                     // the boundary alone, before a layout
      const v = [], b = state.boundary, z = (e, n) => drawGround(e, n) + 1.5;
      for (let i = 0; i < b.length; i++) { const [e0, n0] = b[i], [e1, n1] = b[(i + 1) % b.length]; v.push(e0, n0, z(e0, n0), e1, n1, z(e1, n1)); }
      const base = v.slice(0, 3), rel = new Float32Array(v.map((x, i) => x - base[i % 3]));
      out.push({ key: 'plant-boundary', version: `${state.version}:${b.length}`, positions: rel, color: COLOUR.fence, origin: [base[0] - o.e, base[1] - o.n, base[2]] });
    }
    if (d) for (const k of ['fence', 'tables', 'roads', 'equipment', 'mv']) {
      const L = d[k];
      if (!L.base || L.v.length < 6) continue;
      out.push({ key: 'plant-' + k, version: state.version, positions: L.v, color: COLOUR[k === 'fence' ? 'fence' : k], origin: [L.base[0] - o.e, L.base[1] - o.n, L.base[2]] });
    }
    return out;
  }

  // ---- report ----
  function showReport(r) {
    const e = r.electrical, km = m => `${formatNumber(m / 1000, 2)} km`, pct = x => formatNumber(x, 2) + ' %';
    const rows = [['Asked', `${r.asked.mw} MW export, ${formatNumber(r.asked.mwp, 1)} MWp DC`],
      ['Achieved', `${r.built.mw} MW export, ${formatNumber(r.built.mwp, 1)} MWp DC${r.fits ? '' : ' (does not all fit)'}`],
      ['Tables', `${r.built.tables} of ${r.table.modules} modules, ${r.layout === 'south' ? 'south-facing' : 'east-west'}`],
      ['Stations', String(r.built.stations)], ['33 kV feeders', String(r.built.feeders)],
      ['Roads', `${km(r.built.roadM)} (spine, ${r.trackRoads.length} track runs${r.access ? ', access' : ''})`]];
    if (e) {
      rows.push(['Trench', km(e.trenchM)], ...Object.entries(e.trenchByType).map(([k, m]) => ['', `${k}: ${km(m)}`]));
      rows.push(['Cable (single core)', km(e.cableM)], ...Object.entries(e.cableBySize).sort((a, b) => a[0] - b[0]).map(([a, m]) => ['', `${a} mm² Al: ${km(m)}`]));
      rows.push(['Worst MV drop', pct(e.worstDropPct)]);
    }
    const sk = r.skipped;
    rows.push(['Left out', `slope ${sk.slope} · hollows ${sk.hollow} · water ${sk.water} · setback ${sk.setback} · not measured ${sk.unmeasured}`]);
    if (r.grid) {
      const [ce, cn] = r.frame.en(r.compound.u, r.compound.v), d = Math.hypot(r.grid.e - ce, r.grid.n - cn);
      rows.push(['Grid', `compound ${km(d)} from the nearest ${r.grid.kv ? r.grid.kv + ' kV ' : ''}substation (straight line; the connection is not drawn)`]);
    }
    if (r.waterLines) rows.push(['Water', `${r.waterLines} mapped watercourses; tables kept ${r.params.waterSetbackM} m from them`]);
    rows.push(['Worked out in', `${formatNumber(r.seconds, 1)} s`], ...r.notes.map((n, i) => [i ? '' : 'Notes', n]));
    state.rows = rows;
    $('plant-readout').replaceChildren(...rows.flatMap(([k, v]) => { const dt = doc.createElement('dt'), dd = doc.createElement('dd'); dt.textContent = k; dd.textContent = v; return [dt, dd]; }));
    state.summary = { asked: r.asked, built: r.built, fits: r.fits, skipped: sk, seconds: r.seconds, longestSliceMs: r.longestSliceMs,
      trenchM: e?.trenchM ?? 0, trenchByType: e?.trenchByType ?? {}, cableM: e?.cableM ?? 0, cableBySize: e?.cableBySize ?? {},
      worstDropPct: e?.worstDropPct ?? null, notes: r.notes, label: LABEL };
    say(`${LABEL} ${r.fits ? 'Laid out.' : r.notes[0]}`, !r.fits);
  }
  function clearLayout(all = true) {
    state.result = null; state.draw = null; state.summary = null; state.version++;
    if (all) state.boundary = null;
    $('plant-readout').replaceChildren(); redraw();
  }
  $('plant-open').addEventListener('click', () => useOpenLand());
  $('plant-run').addEventListener('click', () => run());
  $('plant-clear').addEventListener('click', () => { clearLayout(true); say('Layout cleared.'); });
  say(LABEL);
  return { setBoundary, useOpenLand, run, batches, clear: clearLayout,
    snapshot: () => (state.summary ? JSON.parse(JSON.stringify(state.summary)) : { boundary: state.boundary ? state.boundary.length : 0, running: state.running }) };
}