GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / globalgrid2050 / scripts

GlobalGrid2050 Add V6 V7 GIS Single-Line Diagram (SLD) Print Map Pack and 1 more file

A Python command-line tool in the scripts folder that patches folder (`patch_folder`) (units: kV), covering overhead lines (OHL), 66kV, 132kV and 275kV.

700 lines of Python from globalgrid2050, in 2 files. Topic: Grid network and substations. Section 330 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. GlobalGrid2050 Add V6 V7 GIS Single-Line Diagram (SLD) Print Formatting electrical · globalgrid2050 / scripts/add_v6_v7_gis_sld_print_formatting.py lines 1–302
  2. GlobalGrid2050 Add V6 V7 GIS Single-Line Diagram (SLD) Print Map Pack electrical · globalgrid2050 / scripts/add_v6_v7_gis_sld_print_map_pack.py lines 1–398

GlobalGrid2050 Add V6 V7 GIS Single-Line Diagram (SLD) Print Formatting

A Python command-line tool in the scripts folder that reads solar and battery storage (BESS).

electricalglobalgrid2050 / scripts/add_v6_v7_gis_sld_print_formatting.py · lines 1–302 of 302 · Entry point · pattern update_target (shared by 2 files)

What it does
It loads solar and battery storage (BESS). Defines read, write, update_target, main. Uses libraries __future__, datetime, pathlib. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar, battery storage (BESS).
Downstream impact
Used directly by 1 file: GlobalGrid2050 Add V6 V7 GIS Single-Line Diagram (SLD) Print Formatting Workflow (globalgrid2050).
What it achieves
It updates target (`update_target`) and is built from the read step (`read`) and the write step (`write`). Add print formatting to V6 and V7 GIS SLD Financial Sandbox.
Why it matters
Run by GlobalGrid2050 Add V6 V7 GIS Single-Line Diagram (SLD) Print Formatting Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, datetime, pathlib
Used by
run by GlobalGrid2050 Add V6 V7 GIS Single-Line Diagram (SLD) Print Formatting Workflow (workflow run)
Produces
read, write, update_target, main
Defines here
read, write, update_target, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/add_v6_v7_gis_sld_print_formatting.py:1-302 · blob 18c5a9dfcaece963fe9f209eb67f35b6a73e466f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""
Add print formatting to V6 and V7 GIS SLD Financial Sandbox.

Purpose:
- Improve browser print / save to PDF output.
- Hide interactive controls from print.
- Preserve left panel inputs, summaries, explanations and disclaimers.
- Place the map as a clean report figure.
- Add a print button that calls window.print().
"""

from __future__ import annotations

import datetime as dt
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
REPORTS = ROOT / "gridbot_reports"
REPORT = REPORTS / "add_v6_v7_gis_sld_print_formatting.md"

TARGETS = [
    ("V6", ROOT / "solar-bess-topology-v6" / "gis-sld-financial-sandbox"),
    ("V7", ROOT / "solar-bess-topology-v7" / "gis-sld-financial-sandbox"),
]

PRINT_BUTTON = '<button id="btn_print_report" class="map-toggle-btn">PRINT</button>'
PRINT_BUTTON_MARKER = '<button id="btn_key_toggle" class="map-toggle-btn active">KEY ON</button>'
PRINT_EVENT_MARKER = '$("btn_key_toggle")?.addEventListener("click", toggleKeyCollapse);'
PRINT_EVENT_LINE = '$("btn_print_report")?.addEventListener("click", () => window.print());'

PRINT_CSS_MARKER = '/* VENTUS GIS SLD PRINT REPORT MODE */'
PRINT_CSS = r'''

/* VENTUS GIS SLD PRINT REPORT MODE */
@media print {
  @page {
    size: A4 portrait;
    margin: 12mm;
  }

  html,
  body {
    height: auto !important;
    min-height: 0 !important;
    overflow: visible !important;
    display: block !important;
    background: #ffffff !important;
    color: #111111 !important;
    padding: 0 !important;
    margin: 0 !important;
    font-size: 9.5pt !important;
    line-height: 1.35 !important;
  }

  body::before {
    content: "VENTUS GIS SLD Financial Sandbox  |  Early Stage Engineering Screening Report";
    display: block;
    color: #111111;
    font-weight: bold;
    font-size: 13pt;
    border-bottom: 1px solid #999999;
    padding: 0 0 6mm 0;
    margin: 0 0 6mm 0;
  }

  .dashboard {
    display: block !important;
    width: 100% !important;
    max-width: none !important;
    height: auto !important;
  }

  .panel,
  .panel-left,
  .panel-right {
    display: block !important;
    width: 100% !important;
    max-width: none !important;
    height: auto !important;
    min-height: 0 !important;
    overflow: visible !important;
    background: #ffffff !important;
    color: #111111 !important;
    border: 1px solid #cccccc !important;
    border-radius: 0 !important;
    box-shadow: none !important;
    padding: 8mm !important;
    margin: 0 0 8mm 0 !important;
  }

  .panel-right {
    page-break-before: always;
    break-before: page;
  }

  #map {
    display: block !important;
    height: 170mm !important;
    min-height: 170mm !important;
    width: 100% !important;
    border: 1px solid #999999 !important;
    page-break-inside: avoid;
    break-inside: avoid;
  }

  .maplibregl-canvas,
  .maplibregl-map {
    max-width: 100% !important;
  }

  .map-controls,
  .map-tool-overlay,
  .crosshair,
  #fetch_status,
  .maplibregl-control-container,
  .maplibregl-ctrl,
  .maplibregl-ctrl-group,
  button,
  .search-box,
  .tab-container,
  .btn,
  .action-row,
  .toolbar,
  [class*="toggle"],
  [id*="btn_"] {
    display: none !important;
  }

  .legend {
    display: block !important;
    position: static !important;
    width: 100% !important;
    max-width: none !important;
    background: #ffffff !important;
    color: #111111 !important;
    border: 1px solid #cccccc !important;
    padding: 4mm !important;
    margin: 4mm 0 0 0 !important;
    font-size: 8pt !important;
    page-break-inside: avoid;
    break-inside: avoid;
  }

  .legend * {
    color: #111111 !important;
  }

  h2,
  h3 {
    color: #111111 !important;
    border-color: #999999 !important;
    page-break-after: avoid;
    break-after: avoid;
  }

  p,
  label,
  div,
  span,
  small,
  strong {
    color: #111111 !important;
  }

  input,
  select,
  textarea {
    color: #111111 !important;
    background: #ffffff !important;
    border: 1px solid #999999 !important;
    print-color-adjust: exact;
    -webkit-print-color-adjust: exact;
  }

  .input-group,
  .stat-row,
  .summary-row,
  .warning,
  .notice,
  .card,
  .panel-section {
    page-break-inside: avoid;
    break-inside: avoid;
  }

  .tab-content {
    display: block !important;
  }

  .tab-content:not(.active) {
    display: block !important;
  }

  a::after {
    content: "" !important;
  }

  * {
    text-shadow: none !important;
    box-shadow: none !important;
    print-color-adjust: exact;
    -webkit-print-color-adjust: exact;
  }
}
'''


def read(path: Path) -> str:
    return path.read_text(encoding="utf-8")


def write(path: Path, text: str) -> None:
    path.write_text(text, encoding="utf-8")


def update_target(version: str, folder: Path) -> list[str]:
    index = folder / "index.html"
    css = folder / "gis-sld-v5.css"
    ui = folder / "gis-sld-v5-ui.js"

    for p in (index, css, ui):
        if not p.exists():
            raise SystemExit(f"Missing {version} file: {p.relative_to(ROOT)}")

    actions: list[str] = []

    html = read(index)
    if PRINT_BUTTON not in html:
        if PRINT_BUTTON_MARKER not in html:
            raise SystemExit(f"{version}: print button marker not found")
        html = html.replace(PRINT_BUTTON_MARKER, PRINT_BUTTON_MARKER + "\n" + PRINT_BUTTON, 1)
        write(index, html)
        actions.append(f"{version}: added print button")
    else:
        actions.append(f"{version}: print button already present")

    js = read(ui)
    if PRINT_EVENT_LINE not in js:
        if PRINT_EVENT_MARKER not in js:
            raise SystemExit(f"{version}: print event marker not found")
        js = js.replace(PRINT_EVENT_MARKER, PRINT_EVENT_MARKER + "\n" + PRINT_EVENT_LINE, 1)
        write(ui, js)
        actions.append(f"{version}: wired print button to window.print")
    else:
        actions.append(f"{version}: print button already wired")

    style = read(css)
    if PRINT_CSS_MARKER not in style:
        write(css, style.rstrip() + PRINT_CSS + "\n")
        actions.append(f"{version}: appended print report CSS")
    else:
        actions.append(f"{version}: print report CSS already present")

    return actions


def main() -> int:
    all_actions: list[str] = []
    for version, folder in TARGETS:
        all_actions.extend(update_target(version, folder))

    REPORTS.mkdir(parents=True, exist_ok=True)
    timestamp = dt.datetime.now(dt.timezone.utc).isoformat()
    report = "\n".join([
        "# Add V6 V7 GIS SLD Print Formatting",
        "",
        f"UTC created: {timestamp}",
        "",
        "## Purpose",
        "",
        "Improve browser print and Save as PDF output for the V6 and V7 GIS SLD Financial Sandbox pages.",
        "",
        "## Changes",
        "",
        "- Adds a PRINT button to map controls.",
        "- Wires the PRINT button to `window.print()`.",
        "- Adds print CSS to hide interactive map controls, tool overlays and buttons.",
        "- Keeps report content, assumptions, summaries, explanatory text and map figure visible.",
        "- Forces printable white background and black text for cleaner PDF output.",
        "",
        "## Actions",
        "",
        *[f"- {action}" for action in all_actions],
        "",
        "## Test links",
        "",
        "- `/solar-bess-topology-v6/gis-sld-financial-sandbox/`",
        "- `/solar-bess-topology-v7/gis-sld-financial-sandbox/`",
        "",
        "## Manual test",
        "",
        "Open either GIS SLD page, press PRINT, then preview Save as PDF. Confirm the PDF is report style, the map prints cleanly, and interactive controls are hidden.",
        "",
    ])
    write(REPORT, report)
    print(f"Print formatting update complete. Report: {REPORT.relative_to(ROOT)}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

GlobalGrid2050 Add V6 V7 GIS Single-Line Diagram (SLD) Print Map Pack

A Python command-line tool in the scripts folder that patches folder (`patch_folder`) (units: kV), covering overhead lines (OHL), 66kV, 132kV and 275kV.

electricalglobalgrid2050 / scripts/add_v6_v7_gis_sld_print_map_pack.py · lines 1–398 of 452 · Entry point · pattern patch_folder (shared by 3 files)

What it does
It draws overhead lines (OHL), 66kV, 132kV and 275kV. Defines read, write, patch_folder, main. Uses libraries __future__, datetime, pathlib. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: overhead lines (OHL), 66kV, 132kV, 275kV, 400kV.
Inputs & outputs
Voltage levels named: 400kV, 275kV, 132kV, 66kV.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Add V6 V7 GIS Single-Line Diagram (SLD) Print Map Pack Workflow (globalgrid2050).
What it achieves
It is built from the read step (`read`) and the write step (`write`). Make overhead line and public substation layers default OFF for a cleaner working map. - Replace the print button with a print preparation routine. - Add 3 print map pages after the normal report: 1.
Why it matters
Run by GlobalGrid2050 Add V6 V7 GIS Single-Line Diagram (SLD) Print Map Pack Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, datetime, pathlib
Used by
run by GlobalGrid2050 Add V6 V7 GIS Single-Line Diagram (SLD) Print Map Pack Workflow (workflow run)
Produces
read, write, patch_folder, main
Defines here
read, write, patch_folder
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/add_v6_v7_gis_sld_print_map_pack.py:1-398 · blob adb596cee555ca1f4814caceb8e6a1b02a17ba86 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""
Add V6 and V7 GIS SLD print map pack.

Purpose:
- Make overhead line and public substation layers default OFF for a cleaner working map.
- Replace the print button with a print preparation routine.
- Add 3 print map pages after the normal report:
  1. Full page current map figure.
  2. Full page zoomed out context map figure.
  3. Full page satellite map figure.
- Keep the normal report above the map figures.

The print figures use MapLibre canvas snapshots.
"""

from __future__ import annotations

import datetime as dt
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
REPORTS = ROOT / "gridbot_reports"
REPORT = REPORTS / "add_v6_v7_gis_sld_print_map_pack.md"

TARGETS = [
    ROOT / "solar-bess-topology-v6" / "gis-sld-financial-sandbox",
    ROOT / "solar-bess-topology-v7" / "gis-sld-financial-sandbox",
]

PRINT_PACK_JS_MARKER = "// GLOBALGRID2050 GIS SLD PRINT MAP PACK"
PRINT_PACK_CSS_MARKER = "/* GLOBALGRID2050 GIS SLD PRINT MAP PACK */"

PRINT_EVENT_OLD = '$("btn_print_report")?.addEventListener("click", () => window.print());'
PRINT_EVENT_NEW = '$("btn_print_report")?.addEventListener("click", prepareGisSldPrintReport);'

JS_PATCH = r'''

// GLOBALGRID2050 GIS SLD PRINT MAP PACK
function sleepForPrintPack(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

function setLayerVisibilityForPrintPack(layerId, visible) {
    if (!map || !map.getLayer(layerId)) return;
    map.setLayoutProperty(layerId, "visibility", visible ? "visible" : "none");
}

function setAtlasLayersDefaultOff() {
    if (typeof atlasV8GridLayerVisibility === "undefined") return;
    Object.keys(atlasV8GridLayerVisibility).forEach(voltageKey => {
        atlasV8GridLayerVisibility[voltageKey] = false;
        const layerId = atlasV8GridLayerIds?.[voltageKey];
        if (layerId) setLayerVisibilityForPrintPack(layerId, false);
    });
    updateAtlasV8GridToggleButtons?.();
    updateLegend?.();
}

function setSubsDefaultOff() {
    if (typeof state === "undefined") return;
    state.subsVisible = false;
    setLayerVisibilityForPrintPack("l-subs", false);
    updateSubsToggleButton?.();
    updateLegend?.();
}

function enforceCleanDefaultMapLayers() {
    setAtlasLayersDefaultOff();
    setSubsDefaultOff();
}

function getMapPrintState() {
    if (!map) return null;
    return {
        center: map.getCenter(),
        zoom: map.getZoom(),
        bearing: map.getBearing(),
        pitch: map.getPitch(),
        satActive: !!state.satActive,
        subsVisible: !!state.subsVisible,
        atlas: typeof atlasV8GridLayerVisibility !== "undefined" ? { ...atlasV8GridLayerVisibility } : {},
        keyCollapsed: $("map_legend")?.classList.contains("key-collapsed") || false,
        toolsCollapsed: $("map_tool_overlay")?.classList.contains("tools-collapsed") || false,
        mapExpanded: document.body.classList.contains("map-expanded")
    };
}

async function restoreMapPrintState(saved) {
    if (!map || !saved) return;

    if (typeof state !== "undefined") {
        state.satActive = saved.satActive;
        state.subsVisible = saved.subsVisible;
    }

    setLayerVisibilityForPrintPack("l-sat", saved.satActive);
    setLayerVisibilityForPrintPack("l-subs", saved.subsVisible);

    if (typeof atlasV8GridLayerVisibility !== "undefined") {
        Object.keys(saved.atlas || {}).forEach(voltageKey => {
            atlasV8GridLayerVisibility[voltageKey] = saved.atlas[voltageKey];
            const layerId = atlasV8GridLayerIds?.[voltageKey];
            if (layerId) setLayerVisibilityForPrintPack(layerId, saved.atlas[voltageKey]);
        });
    }

    const legend = $("map_legend");
    if (legend) legend.classList.toggle("key-collapsed", saved.keyCollapsed);
    const keyBtn = $("btn_key_toggle");
    if (keyBtn) {
        keyBtn.textContent = saved.keyCollapsed ? "KEY OFF" : "KEY ON";
        keyBtn.classList.toggle("active", !saved.keyCollapsed);
    }

    const overlay = $("map_tool_overlay");
    if (overlay) overlay.classList.toggle("tools-collapsed", saved.toolsCollapsed);
    const toolsBtn = $("btn_map_tools_toggle");
    if (toolsBtn) {
        toolsBtn.textContent = saved.toolsCollapsed ? "TOOLS OFF" : "TOOLS ON";
        toolsBtn.classList.toggle("active", !saved.toolsCollapsed);
    }

    document.body.classList.toggle("map-expanded", saved.mapExpanded);
    document.querySelector(".panel-right")?.classList.toggle("map-expanded", saved.mapExpanded);

    map.jumpTo({ center: saved.center, zoom: saved.zoom, bearing: saved.bearing, pitch: saved.pitch });
    updateSubsToggleButton?.();
    updateAtlasV8GridToggleButtons?.();
    updateLegend?.();
    map.resize();
    await sleepForPrintPack(350);
}

function ensurePrintMapPackContainer() {
    let pack = document.getElementById("print_map_pack");
    if (!pack) {
        pack = document.createElement("section");
        pack.id = "print_map_pack";
        pack.className = "print-map-pack";
        document.body.appendChild(pack);
    }
    pack.innerHTML = "";
    return pack;
}

function addPrintMapFigure(pack, title, dataUrl, note, landscape = false) {
    const page = document.createElement("section");
    page.className = landscape ? "print-map-page print-map-page-landscape" : "print-map-page";

    const heading = document.createElement("h2");
    heading.textContent = title;

    const img = document.createElement("img");
    img.src = dataUrl;
    img.alt = title;

    const caption = document.createElement("p");
    caption.textContent = note || "Map figure generated from current GIS SLD sandbox view. Indicative only.";

    page.appendChild(heading);
    page.appendChild(img);
    page.appendChild(caption);
    pack.appendChild(page);
}

async function captureCurrentMapForPrint() {
    if (!map) return "";
    map.resize();
    await sleepForPrintPack(650);
    return map.getCanvas().toDataURL("image/png");
}

function getTopologyBoundsForPrintPack() {
    if (typeof turf === "undefined" || !state?.currentGeoJSON?.features?.length) return null;
    try {
        const bbox = turf.bbox(state.currentGeoJSON);
        if (!bbox || bbox.length !== 4 || bbox.some(v => !Number.isFinite(v))) return null;
        return [[bbox[0], bbox[1]], [bbox[2], bbox[3]]];
    } catch (err) {
        console.warn("Print pack bbox failed", err);
        return null;
    }
}

async function fitContextMapForPrint() {
    const bounds = getTopologyBoundsForPrintPack();
    if (bounds) {
        map.fitBounds(bounds, { padding: 90, duration: 0, maxZoom: 12 });
    } else {
        const currentZoom = map.getZoom();
        map.setZoom(Math.max(currentZoom - 4, 7));
    }
    await sleepForPrintPack(750);
}

async function setSatelliteForPrintPack(active) {
    if (!map) return;
    if (typeof state !== "undefined") state.satActive = !!active;
    setLayerVisibilityForPrintPack("l-sat", !!active);
    const btn = $("btn_basemap");
    if (btn) {
        btn.textContent = active ? "DARK MATTER VIEW" : "SATELLITE VIEW";
        btn.classList.toggle("active", !!active);
    }
    await sleepForPrintPack(500);
}

async function prepareGisSldPrintReport() {
    if (!map) {
        window.print();
        return;
    }

    const btn = $("btn_print_report");
    const oldText = btn ? btn.textContent : "";
    if (btn) btn.textContent = "PREPARING";

    const saved = getMapPrintState();
    const pack = ensurePrintMapPackContainer();

    try {
        document.body.classList.add("preparing-print-pack");
        document.body.classList.remove("map-expanded");
        document.querySelector(".panel-right")?.classList.remove("map-expanded");
        $("map_tool_overlay")?.classList.add("tools-collapsed");
        $("map_legend")?.classList.add("key-collapsed");

        // Page 1 map: current working view, but clean with user selected layers retained.
        map.resize();
        await sleepForPrintPack(600);
        const currentMap = await captureCurrentMapForPrint();
        addPrintMapFigure(pack, "Map Figure 1: Current Project View", currentMap, "Current GIS SLD project view. Interactive controls are removed from print output.");

        // Page 2 map: zoomed out context. Keep current basemap and layer settings.
        await fitContextMapForPrint();
        const contextMap = await captureCurrentMapForPrint();
        addPrintMapFigure(pack, "Map Figure 2: Wider Grid And Route Context", contextMap, "Zoomed out context view showing wider relationship between project, route assumptions and grid geography.");

        // Page 3 map: satellite view, clean and full page.
        await setSatelliteForPrintPack(true);
        await fitContextMapForPrint();
        const satelliteMap = await captureCurrentMapForPrint();
        addPrintMapFigure(pack, "Map Figure 3: Satellite Context View", satelliteMap, "Satellite context view for visual land, route and surrounding area review. Indicative only.", true);

        await restoreMapPrintState(saved);
        document.body.classList.remove("preparing-print-pack");
        if (btn) btn.textContent = oldText || "PRINT";
        window.print();
    } catch (err) {
        console.error("GIS SLD print pack failed", err);
        await restoreMapPrintState(saved);
        document.body.classList.remove("preparing-print-pack");
        if (btn) btn.textContent = oldText || "PRINT";
        window.print();
    }
}

// Clean map defaults after the map and controls have loaded.
setTimeout(enforceCleanDefaultMapLayers, 1200);
'''

CSS_PATCH = r'''

/* GLOBALGRID2050 GIS SLD PRINT MAP PACK */
@media print {
  .panel-right {
    page-break-before: auto !important;
    break-before: auto !important;
  }

  #map {
    height: 150mm !important;
    min-height: 150mm !important;
    max-height: 150mm !important;
    width: 100% !important;
    overflow: hidden !important;
  }

  .print-map-pack {
    display: block !important;
    width: 100% !important;
    margin: 0 !important;
    padding: 0 !important;
    background: #ffffff !important;
    color: #111111 !important;
  }

  .print-map-page {
    display: block !important;
    width: 100% !important;
    min-height: 265mm !important;
    page-break-before: always !important;
    break-before: page !important;
    page-break-after: always !important;
    break-after: page !important;
    page-break-inside: avoid !important;
    break-inside: avoid !important;
    margin: 0 !important;
    padding: 0 !important;
    background: #ffffff !important;
    color: #111111 !important;
  }

  .print-map-page h2 {
    display: block !important;
    font-size: 12pt !important;
    color: #111111 !important;
    margin: 0 0 4mm 0 !important;
    padding: 0 0 2mm 0 !important;
    border-bottom: 1px solid #999999 !important;
  }

  .print-map-page img {
    display: block !important;
    width: 100% !important;
    height: 225mm !important;
    object-fit: contain !important;
    border: 1px solid #999999 !important;
    background: #ffffff !important;
    margin: 0 0 3mm 0 !important;
  }

  .print-map-page p {
    display: block !important;
    color: #111111 !important;
    font-size: 8pt !important;
    line-height: 1.2 !important;
    margin: 0 !important;
  }

  .print-map-page-landscape {
    min-height: 265mm !important;
  }

  .print-map-page-landscape img {
    height: 225mm !important;
  }
}

@media screen {
  .print-map-pack {
    display: none;
  }
}
'''


def read(path: Path) -> str:
    return path.read_text(encoding="utf-8")


def write(path: Path, text: str) -> None:
    path.write_text(text, encoding="utf-8")


def patch_folder(folder: Path) -> list[str]:
    actions: list[str] = []
    map_js = folder / "gis-sld-v5-map.js"
    ui_js = folder / "gis-sld-v5-ui.js"
    css = folder / "gis-sld-v5.css"

    for path in [map_js, ui_js, css]:
        if not path.exists():
            raise SystemExit(f"Missing file: {path.relative_to(ROOT)}")

    map_text = read(map_js)
    if '"66kv": true' in map_text or '"132kv": true' in map_text or '"275kv": true' in map_text or '"400kv": true' in map_text:
        map_text = map_text.replace('"66kv": true', '"66kv": false')
        map_text = map_text.replace('"132kv": true', '"132kv": false')
        map_text = map_text.replace('"275kv": true', '"275kv": false')
        map_text = map_text.replace('"400kv": true', '"400kv": false')
        write(map_js, map_text)
        actions.append(f"set Atlas overhead line layers default OFF in {map_js.relative_to(ROOT)}")
    else:
        actions.append(f"Atlas overhead line defaults already OFF in {map_js.relative_to(ROOT)}")

    ui_text = read(ui_js)
    if PRINT_EVENT_OLD in ui_text:
        ui_text = ui_text.replace(PRINT_EVENT_OLD, PRINT_EVENT_NEW, 1)
        actions.append(f"replaced direct window.print with print preparation routine in {ui_js.relative_to(ROOT)}")
    elif PRINT_EVENT_NEW in ui_text:
        actions.append(f"print preparation routine already wired in {ui_js.relative_to(ROOT)}")
    else:
        raise SystemExit(f"Print event marker not found in {ui_js.relative_to(ROOT)}")

    if PRINT_PACK_JS_MARKER not in ui_text:
        ui_text = ui_text.rstrip() + JS_PATCH + "\n"
        actions.append(f"added GIS SLD print map pack JS in {ui_js.relative_to(ROOT)}")
    else:
        actions.append(f"GIS SLD print map pack JS already present in {ui_js.relative_to(ROOT)}")
    write(ui_js, ui_text)

    css_text = read(css)
    if PRINT_PACK_CSS_MARKER not in css_text:
        css_text = css_text.rstrip() + CSS_PATCH + "\n"
        write(css, css_text)
        actions.append(f"added GIS SLD print map pack CSS in {css.relative_to(ROOT)}")