GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / globalgrid2050 / scripts

GlobalGrid2050 Gridbot Mega Upgrade and 1 more file

A Python command-line tool in the scripts folder that reads generation recent halfhourly 30d and generation recent 30d 30min. It runs git (`run_git`), reads text (`read_text`) and reads JSON (`read_json`).

700 lines of Python from globalgrid2050, in 2 files. Topic: Automation and CI. Section 1765 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 Gridbot Mega Upgrade storage · globalgrid2050 / scripts/gridbot_mega_upgrade.py lines 1–411
  2. GlobalGrid2050 Gridbot Modularise Employers' Requirements interaction · globalgrid2050 / scripts/gridbot_modularise_employers_requirements.py lines 1–289

GlobalGrid2050 Gridbot Mega Upgrade

A Python command-line tool in the scripts folder that reads generation recent halfhourly 30d and generation recent 30d 30min. It runs git (`run_git`), reads text (`read_text`) and reads JSON (`read_json`).

storageglobalgrid2050 / scripts/gridbot_mega_upgrade.py · lines 1–411 of 411 · Entry point · pattern run_git (shared by 4 files)

What it does
It loads generation recent halfhourly 30d and generation recent 30d 30min. Defines 21 functions or classes, including utc_now, stamp, run_git, mib, read_text. Uses libraries __future__, argparse, json, math, re. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: JSON file generation_recent_halfhourly_30d.json; JSON file generation_recent_30d_30min.json; JSON file GRIDBOT_MEGA_UPGRADE_LATEST.json; command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Gridbot Mega Upgrade Workflow (globalgrid2050).
What it achieves
Manifest driven, audit first, CI suitable. It accepts `--manifest`, `--apply` and `--phase`.
Why it matters
Run by GlobalGrid2050 Gridbot Mega Upgrade Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, json, math, re, subprocess, collections, datetime
Used by
run by GlobalGrid2050 Gridbot Mega Upgrade Workflow (workflow run)
Produces
utc_now, stamp, run_git, mib, read_text, read_json, write_json, load_manifest, repo_size_audit, patch_gitignore, floor_to_30min, parse_ts
Defines here
utc_now, stamp, run_git, mib, read_text, read_json, write_json, load_manifest, repo_size_audit, patch_gitignore, floor_to_30min, parse_ts, resample_recent_30min, rewire_recent_loader, source_routing_audit, non_additive_peak_audit, merge_guard_audit, confirmed_fact_source_audit, confirmed_fact_schema_audit, render_report, 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/gridbot_mega_upgrade.py:1-411 · blob 7d2c3c8f8f39c4976954dbb3b5f8703ba8b961e0 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""
GlobalGrid2050 GridBot mega upgrade orchestrator.

Manifest driven, audit first, CI suitable. This script is designed to be run
from GitHub Actions by a human triggered workflow. It can run in audit only
mode or apply selected safe patches. It never deletes data and never rewrites
Git history.
"""

from __future__ import annotations

import argparse
import json
import math
import re
import subprocess
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

try:
    import yaml
except Exception:  # pragma: no cover
    yaml = None

ROOT = Path(__file__).resolve().parent.parent
REPORT_DIR = ROOT / "data_science_protocol" / "audit_reports"
JSON_DIR = REPORT_DIR / "json"
MANIFEST_DEFAULT = ROOT / "gridbot_manifests" / "001_generation_data_discipline.yml"


def utc_now() -> str:
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def stamp() -> str:
    return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")


def run_git(args: list[str]) -> str:
    try:
        return subprocess.run(["git", *args], cwd=ROOT, text=True, capture_output=True, check=True).stdout.strip()
    except Exception:
        return ""


def mib(size: int) -> float:
    return round(size / 1024 / 1024, 3)


def read_text(path: Path) -> str:
    return path.read_text(encoding="utf-8", errors="replace") if path.exists() else ""


def read_json(path: Path) -> dict[str, Any]:
    if not path.exists():
        return {"rows": []}
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except Exception:
        return {"rows": []}


def write_json(path: Path, payload: dict[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")


def load_manifest(path: Path) -> dict[str, Any]:
    if yaml is not None:
        return yaml.safe_load(path.read_text(encoding="utf-8"))
    raise RuntimeError("PyYAML is required for gridbot manifest parsing")


def repo_size_audit() -> dict[str, Any]:
    excluded = {".git", ".venv", "venv", "env", "node_modules", "__pycache__", ".pytest_cache", ".mypy_cache"}
    review_ext = {".csv", ".json", ".geojson", ".topojson", ".parquet", ".zip", ".db", ".sqlite"}
    rows = []
    total = 0
    for path in sorted(ROOT.rglob("*")):
        if not path.is_file():
            continue
        parts = path.relative_to(ROOT).parts
        if any(part in excluded for part in parts):
            continue
        size = path.stat().st_size
        total += size
        suffix = path.suffix.lower()
        if suffix not in review_ext and size < 5 * 1024 * 1024:
            continue
        rel = path.relative_to(ROOT).as_posix()
        low = rel.lower()
        if size >= 25 * 1024 * 1024:
            risk = "fail_threshold"
        elif size >= 5 * 1024 * 1024:
            risk = "warn_threshold"
        else:
            risk = "tracked"
        if suffix in {".geojson", ".topojson"}:
            kind = "gis"
        elif "archive" in low or "raw" in low or "half_hourly" in low:
            kind = "raw_or_archive_candidate"
        else:
            kind = "data_or_asset"
        if risk != "tracked" or kind in {"gis", "raw_or_archive_candidate"}:
            rows.append({"path": rel, "sizeMiB": mib(size), "risk": risk, "kind": kind})
    return {"totalWorkingTreeMiB": mib(total), "reviewFiles": sorted(rows, key=lambda r: r["sizeMiB"], reverse=True)}


def patch_gitignore(patterns: list[str], apply: bool) -> dict[str, Any]:
    path = ROOT / ".gitignore"
    existing = read_text(path)
    lines = existing.splitlines()
    present = {line.strip() for line in lines}
    additions = [p for p in patterns if p not in present]
    if apply and additions:
        if lines and lines[-1].strip():
            lines.append("")
        if "# GlobalGrid2050 generation archive discipline" not in present:
            lines.append("# GlobalGrid2050 generation archive discipline")
            lines.append("# Raw generation archives are transient CI inputs unless explicitly approved.")
        lines.extend(additions)
        path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")
    return {"path": ".gitignore", "patternsAdded": additions, "applied": bool(apply and additions)}


def floor_to_30min(ts: datetime) -> datetime:
    minute = 0 if ts.minute < 30 else 30
    return ts.replace(minute=minute, second=0, microsecond=0)


def parse_ts(value: Any) -> datetime | None:
    try:
        return datetime.fromisoformat(str(value).replace("Z", "+00:00")).astimezone(timezone.utc)
    except Exception:
        return None


def resample_recent_30min(source_path: Path, output_path: Path, apply: bool) -> dict[str, Any]:
    payload = read_json(source_path)
    rows = payload.get("rows", []) if isinstance(payload, dict) else []
    counts: defaultdict[tuple[str, str], int] = defaultdict(int)
    sums: defaultdict[tuple[str, str], float] = defaultdict(float)

    for row in rows:
        t = parse_ts(row.get("time") or row.get("ts") or row.get("periodStartUTC"))
        tech = row.get("technology")
        if t is None or not tech:
            continue
        mw = row.get("generationMW", row.get("mw"))
        try:
            mwf = float(mw)
            if not math.isfinite(mwf):
                continue
        except Exception:
            continue
        bucket_time = floor_to_30min(t).isoformat().replace("+00:00", "Z")
        key = (bucket_time, str(tech))
        sums[key] += mwf
        counts[key] += 1

    out_rows = []
    for (bucket_time, tech), total in sorted(sums.items()):
        n = counts[(bucket_time, tech)]
        out_rows.append({
            "time": bucket_time,
            "technology": tech,
            "generationMW": round(total / n, 3),
            "records": n,
            "source": "30 minute average resampled from recent generation source",
        })

    out_payload = {
        "schemaVersion": "1.0.0",
        "generatedUTC": utc_now(),
        "sourcePath": source_path.relative_to(ROOT).as_posix() if source_path.exists() else str(source_path),
        "description": "True 30 minute recent generation MW slice resampled by UTC half hour.",
        "unit": "MW",
        "rows": out_rows,
    }

    if apply:
        write_json(output_path, out_payload)

    source_size = source_path.stat().st_size if source_path.exists() else 0
    output_estimate = len(json.dumps(out_payload).encode("utf-8"))
    return {
        "sourcePath": source_path.relative_to(ROOT).as_posix() if source_path.exists() else str(source_path),
        "outputPath": output_path.relative_to(ROOT).as_posix(),
        "sourceRows": len(rows),
        "outputRows": len(out_rows),
        "sourceMiB": mib(source_size),
        "outputEstimatedMiB": mib(output_estimate),
        "applied": apply,
    }


def rewire_recent_loader(config_path: Path, old_path: str, new_path: str, apply: bool) -> dict[str, Any]:
    text = read_text(config_path)
    found_old = old_path in text
    found_new = new_path in text
    changed = False
    if apply and found_old:
        text = text.replace(old_path, new_path)
        config_path.write_text(text, encoding="utf-8")
        changed = True
    return {
        "configPath": config_path.relative_to(ROOT).as_posix() if config_path.exists() else str(config_path),
        "oldPathFound": found_old,
        "newPathAlreadyPresent": found_new,
        "applied": changed,
    }


def source_routing_audit(loader_path: Path, config_path: Path | None = None) -> dict[str, Any]:
    text = read_text(loader_path)
    cfg_text = read_text(config_path) if config_path else ""
    return {
        "loaderPath": loader_path.relative_to(ROOT).as_posix() if loader_path.exists() else str(loader_path),
        "configPath": config_path.relative_to(ROOT).as_posix() if config_path and config_path.exists() else None,
        "exists": loader_path.exists(),
        "hasTierFor": "function tierFor" in text,
        "longRangesRouteDaily": "'3m'" in text and "'10y'" in text and "daily" in text,
        "recentTierPresent": "recent" in text,
        "configStillUsesOldRecentFile": "generation_recent_halfhourly_30d.json" in cfg_text,
        "configUsesNewRecentFile": "generation_recent_30d_30min.json" in cfg_text,
    }


def non_additive_peak_audit(loader_path: Path) -> dict[str, Any]:
    text = read_text(loader_path)
    patterns = [
        r"highMW\s*\+=",
        r"lowMW\s*\+=",
        r"\.highMW\s*=\s*[^;]+\+\s*Number",
        r"\.lowMW\s*=\s*[^;]+\+\s*Number",
    ]
    hits = []
    for pat in patterns:
        if re.search(pat, text):
            hits.append(pat)
    return {"loaderPath": loader_path.relative_to(ROOT).as_posix() if loader_path.exists() else str(loader_path), "hits": hits, "riskPresent": bool(hits)}


def merge_guard_audit(script_path: Path) -> dict[str, Any]:
    text = read_text(script_path)
    danger = "for row in existing + new_rows" in text and "merged[key] = row" in text
    signals = ["should_replace_existing", "weak_row", "FAIL_ON_WEAK_OVERWRITE", "completeness", "record_count"]
    present = [s for s in signals if s in text]
    return {
        "scriptPath": script_path.relative_to(ROOT).as_posix() if script_path.exists() else str(script_path),
        "exists": script_path.exists(),
        "dangerousLastWriteWinsPatternPresent": danger,
        "guardSignalsPresent": present,
        "appearsGuarded": bool(present) and not danger,
    }


def confirmed_fact_source_audit(script_paths: list[str], data_paths: list[str]) -> dict[str, Any]:
    script_results = []
    for rel in script_paths:
        path = ROOT / rel
        text = read_text(path)
        script_results.append({
            "path": rel,
            "exists": path.exists(),
            "mentionsFUELINST": "FUELINST" in text,
            "mentionsFUELHH": "FUELHH" in text,
        })
    data_results = []
    for rel in data_paths:
        path = ROOT / rel
        payload = read_json(path)
        source_text = json.dumps({k: payload.get(k) for k in ("source", "sourceDatasets", "metadata", "description")}, ensure_ascii=False)
        data_results.append({
            "path": rel,
            "exists": path.exists(),
            "mentionsFUELINST": "FUELINST" in source_text,
            "mentionsFUELHH": "FUELHH" in source_text,
            "sourceText": source_text[:500],
        })
    return {"scripts": script_results, "dataFiles": data_results}


def confirmed_fact_schema_audit(paths: list[str], required_metadata: list[str], required_row_fields: list[str]) -> dict[str, Any]:
    results = []
    for rel in paths:
        path = ROOT / rel
        payload = read_json(path)
        rows = payload.get("rows", []) if isinstance(payload, dict) else []
        metadata = payload.get("metadata", payload if isinstance(payload, dict) else {})
        first = rows[0] if rows else {}
        missing_meta = [m for m in required_metadata if m not in metadata]
        missing_rows = [f for f in required_row_fields if f not in first]
        results.append({
            "path": rel,
            "exists": path.exists(),
            "rowCount": len(rows),
            "missingMetadata": missing_meta,
            "missingRowFields": missing_rows,
        })
    return {"files": results}


def render_report(payload: dict[str, Any]) -> str:
    lines = [
        "# GlobalGrid2050 GridBot Mega Upgrade Report",
        "",
        f"Generated UTC: `{payload['generatedUTC']}`",
        f"Mode: `{payload['mode']}`",
        f"Manifest: `{payload['manifestPath']}`",
        f"Git head: `{payload['gitHead'] or 'unknown'}`",
        "",
        "## Executive summary",
        "",
        payload["executiveSummary"],
        "",
        "## Phase results",
        "",
    ]
    for phase in payload["phases"]:
        lines.append(f"### {phase['id']}  {phase.get('title', '')}")
        lines.append("")
        lines.append(f"Operation: `{phase['operation']}`")
        lines.append(f"Applied: `{phase.get('applied', False)}`")
        lines.append("")
        lines.append("```json")
        lines.append(json.dumps(phase.get("result", {}), indent=2))
        lines.append("```")
        lines.append("")
    return "\n".join(lines)


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--manifest", default=str(MANIFEST_DEFAULT))
    parser.add_argument("--apply", action="store_true")
    parser.add_argument("--phase", default="all")
    args = parser.parse_args()

    manifest_path = Path(args.manifest)
    manifest = load_manifest(manifest_path)
    phases_out = []

    for phase in manifest.get("phases", []):
        if not phase.get("enabled", True):
            continue
        if args.phase != "all" and phase.get("id") != args.phase:
            continue
        op = phase.get("operation")
        apply_phase = bool(args.apply and phase.get("applyByDefault", False))
        if op == "repo_size_audit":
            result = repo_size_audit()
        elif op == "patch_gitignore":
            result = patch_gitignore(phase.get("patterns", []), apply_phase)
        elif op == "resample_recent_30min":
            result = resample_recent_30min(ROOT / phase["sourcePath"], ROOT / phase["outputPath"], apply_phase)
        elif op == "rewire_recent_loader":
            result = rewire_recent_loader(ROOT / phase["configPath"], phase["oldPath"], phase["newPath"], apply_phase)
        elif op == "source_routing_audit":
            cfg = ROOT / phase["configPath"] if phase.get("configPath") else None
            result = source_routing_audit(ROOT / phase["loaderPath"], cfg)
        elif op == "non_additive_peak_audit":
            result = non_additive_peak_audit(ROOT / phase["loaderPath"])
        elif op == "merge_guard_audit":
            result = merge_guard_audit(ROOT / phase["scriptPath"])
        elif op == "confirmed_fact_source_audit":
            result = confirmed_fact_source_audit(phase.get("scriptPaths", []), phase.get("dataPaths", []))
        elif op == "confirmed_fact_schema_audit":
            result = confirmed_fact_schema_audit(phase.get("paths", []), phase.get("requiredMetadata", []), phase.get("requiredRowFields", []))
        else:
            result = {"error": f"unknown operation {op}"}
        phase_out = dict(phase)
        phase_out["applied"] = apply_phase
        phase_out["result"] = result
        phases_out.append(phase_out)

    payload = {
        "reportTitle": "GlobalGrid2050 GridBot Mega Upgrade Report",
        "schemaVersion": "1.1.0",
        "generatedUTC": utc_now(),
        "mode": "apply" if args.apply else "audit only",
        "manifestPath": manifest_path.relative_to(ROOT).as_posix() if manifest_path.exists() else str(manifest_path),
        "gitHead": run_git(["rev-parse", "--short", "HEAD"]),
        "phases": phases_out,
        "executiveSummary": f"GridBot ran {len(phases_out)} phases in {'apply' if args.apply else 'audit only'} mode. Apply only affects phases with applyByDefault true.",
    }

    REPORT_DIR.mkdir(parents=True, exist_ok=True)
    JSON_DIR.mkdir(parents=True, exist_ok=True)
    st = stamp()
    md = REPORT_DIR / f"GRIDBOT_MEGA_UPGRADE_{st}.md"
    js = JSON_DIR / f"GRIDBOT_MEGA_UPGRADE_{st}.json"
    latest_md = REPORT_DIR / "GRIDBOT_MEGA_UPGRADE_LATEST.md"
    latest_js = JSON_DIR / "GRIDBOT_MEGA_UPGRADE_LATEST.json"
    md_text = render_report(payload)
    json_text = json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
    md.write_text(md_text, encoding="utf-8")
    latest_md.write_text(md_text, encoding="utf-8")
    js.write_text(json_text, encoding="utf-8")
    latest_js.write_text(json_text, encoding="utf-8")
    print(payload["executiveSummary"])
    print(f"Wrote {md.relative_to(ROOT)}")
    print(f"Wrote {js.relative_to(ROOT)}")
    return 0


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

GlobalGrid2050 Gridbot Modularise Employers' Requirements

A Python command-line tool in the scripts folder that reads section and solar. It extracts disclaimer (`extract_disclaimer`) and removes disclaimer last section (`remove_disclaimer_from_last_section`).

interactionglobalgrid2050 / scripts/gridbot_modularise_employers_requirements.py · lines 1–289 of 289 · Entry point · pattern slugify (shared by 2 files)

What it does
It loads section and solar. Defines 10 functions or classes, including safe_rel, slugify, split_top_level_sections, extract_disclaimer, remove_disclaimer_from_last_section. Uses libraries __future__, argparse, datetime, html, json. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain terms in the code: solar.
Inputs & outputs
In: form fields (user input); command-line arguments. Out: JSON file section_manifest.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Modularise Solar Er Workflow (globalgrid2050).
What it achieves
Defines `safe_rel`, `slugify`, `split_top_level_sections` and 6 more. It accepts `--target`, `--backup-dir` and `--report-dir`.
Why it matters
Run by GlobalGrid2050 Modularise Solar Er Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, datetime, html, json, re, shutil, pathlib
Used by
run by GlobalGrid2050 Modularise Solar Er Workflow (workflow run)
Produces
safe_rel, slugify, split_top_level_sections, extract_disclaimer, remove_disclaimer_from_last_section, write_section_pages, markdown_to_basic_html, write_print_page, write_main_index, main
Defines here
safe_rel, slugify, split_top_level_sections, extract_disclaimer, remove_disclaimer_from_last_section, write_section_pages, markdown_to_basic_html, write_print_page, write_main_index, 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/gridbot_modularise_employers_requirements.py:1-289 · blob 19e59aea2d0acf945f3a56f2bd15258e474edaf7 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations

import argparse
import datetime as dt
import html
import json
import re
import shutil
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]


def safe_rel(path_text: str) -> Path:
    path = Path(path_text)
    if not path_text or path.is_absolute() or ".." in path.parts:
        raise SystemExit(f"Unsafe path: {path_text}")
    return path


def slugify(text: str) -> str:
    text = text.lower()
    text = re.sub(r"&", " and ", text)
    text = re.sub(r"[^a-z0-9]+", "_", text)
    text = re.sub(r"_+", "_", text).strip("_")
    return text or "section"


def split_top_level_sections(text: str) -> tuple[str, list[dict[str, str]]]:
    matches = list(re.finditer(r"(?m)^# (\d+)\.\s+(.+)$", text))
    if not matches:
        raise SystemExit("No numbered top level sections found")

    preamble = text[: matches[0].start()].rstrip() + "\n"
    sections: list[dict[str, str]] = []

    for idx, match in enumerate(matches):
        start = match.start()
        end = matches[idx + 1].start() if idx + 1 < len(matches) else len(text)
        number = match.group(1)
        title = match.group(2).strip()
        body = text[start:end].strip() + "\n"
        slug = f"{int(number):02d}_{slugify(title)}"
        sections.append({"number": number, "title": title, "slug": slug, "body": body})

    return preamble, sections


def extract_disclaimer(text: str) -> str:
    marker = "# Disclaimer"
    idx = text.find(marker)
    if idx < 0:
        return ""
    return text[idx:].strip() + "\n"


def remove_disclaimer_from_last_section(sections: list[dict[str, str]]) -> None:
    marker = "\n# Disclaimer"
    for section in sections:
        idx = section["body"].find(marker)
        if idx >= 0:
            section["body"] = section["body"][:idx].rstrip() + "\n"
            return


def write_section_pages(base_dir: Path, sections: list[dict[str, str]], page_title: str) -> None:
    sections_dir = base_dir / "sections"
    sections_dir.mkdir(parents=True, exist_ok=True)

    for idx, section in enumerate(sections):
        section_dir = sections_dir / section["slug"]
        section_dir.mkdir(parents=True, exist_ok=True)
        prev_link = ""
        next_link = ""
        if idx > 0:
            prev_section = sections[idx - 1]
            prev_link = f"Previous: [{prev_section['number']}. {prev_section['title']}](../{prev_section['slug']}/)  \n"
        if idx + 1 < len(sections):
            next_section = sections[idx + 1]
            next_link = f"Next: [{next_section['number']}. {next_section['title']}](../{next_section['slug']}/)  \n"

        nav = (
            f"[Back to {page_title}](../../)  \n"
            "[Print selected sections](../../print/)  \n"
            f"{prev_link}{next_link}\n"
        )
        content = section["body"].strip() + "\n\n---\n\n" + nav
        (section_dir / "index.md").write_text(content, encoding="utf-8")


def markdown_to_basic_html(md: str) -> str:
    out: list[str] = []
    in_list = False
    for raw in md.splitlines():
        line = raw.rstrip()
        if not line:
            if in_list:
                out.append("</ul>")
                in_list = False
            continue
        if line.startswith("# "):
            if in_list:
                out.append("</ul>")
                in_list = False
            out.append(f"<h1>{html.escape(line[2:].strip())}</h1>")
        elif line.startswith("## "):
            if in_list:
                out.append("</ul>")
                in_list = False
            out.append(f"<h2>{html.escape(line[3:].strip())}</h2>")
        elif line.startswith("### "):
            if in_list:
                out.append("</ul>")
                in_list = False
            out.append(f"<h3>{html.escape(line[4:].strip())}</h3>")
        elif line.startswith("- "):
            if not in_list:
                out.append("<ul>")
                in_list = True
            out.append(f"<li>{html.escape(line[2:].strip())}</li>")
        else:
            if in_list:
                out.append("</ul>")
                in_list = False
            out.append(f"<p>{html.escape(line)}</p>")
    if in_list:
        out.append("</ul>")
    return "\n".join(out)


def write_print_page(base_dir: Path, sections: list[dict[str, str]], disclaimer: str, page_title: str) -> None:
    print_dir = base_dir / "print"
    print_dir.mkdir(parents=True, exist_ok=True)

    checklist = []
    bodies = []
    for section in sections:
        sid = section["slug"]
        label = f"{section['number']}. {section['title']}"
        checklist.append(
            f'<label><input type="checkbox" data-target="{sid}" checked> {html.escape(label)}</label>'
        )
        bodies.append(
            f'<section class="print-section" id="{sid}">\n{markdown_to_basic_html(section["body"])}\n</section>'
        )

    disclaimer_html = markdown_to_basic_html(disclaimer) if disclaimer else ""
    page = f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{html.escape(page_title)} Print Builder</title>
<style>
body {{ font-family: system-ui, Arial, sans-serif; margin: 0; background: #080b0f; color: #f2f2f2; }}
a {{ color: #7dd3fc; }}
.wrap {{ max-width: 1100px; margin: 0 auto; padding: 24px; }}
.panel {{ border: 1px solid #334155; background: #111827; padding: 18px; border-radius: 12px; margin-bottom: 18px; }}
.checklist {{ columns: 2; column-gap: 28px; }}
.checklist label {{ display: block; break-inside: avoid; margin: 0 0 8px; line-height: 1.35; }}
button {{ margin: 6px 8px 6px 0; padding: 10px 14px; border: 0; border-radius: 8px; cursor: pointer; }}
.print-section {{ background: white; color: #111827; padding: 28px; margin: 18px 0; border-radius: 10px; }}
.print-section h1 {{ border-bottom: 2px solid #111827; padding-bottom: 8px; }}
.disclaimer {{ background: white; color: #111827; padding: 28px; margin: 18px 0; border-radius: 10px; }}
@media print {{
  body {{ background: white; color: black; }}
  .no-print {{ display: none !important; }}
  .wrap {{ max-width: none; padding: 0; }}
  .print-section, .disclaimer {{ break-inside: avoid; border-radius: 0; margin: 0 0 18px; padding: 0; }}
}}
</style>
</head>
<body>
<div class="wrap">
  <div class="panel no-print">
    <h1>{html.escape(page_title)} Print Builder</h1>
    <p>Select the sections required, then print or save as PDF from the browser.</p>
    <p><a href="../">Back to modular index</a></p>
    <button onclick="selectAll(true)">Select all</button>
    <button onclick="selectAll(false)">Clear all</button>
    <button onclick="applySelection()">Apply checklist</button>
    <button onclick="applySelection(); window.print();">Print selected</button>
    <div class="checklist">{''.join(checklist)}</div>
  </div>
  <main id="print-root">
    {''.join(bodies)}
    <section class="disclaimer">{disclaimer_html}</section>
  </main>
</div>
<script>
function selectAll(value) {{
  document.querySelectorAll('input[type="checkbox"][data-target]').forEach(cb => cb.checked = value);
}}
function applySelection() {{
  document.querySelectorAll('input[type="checkbox"][data-target]').forEach(cb => {{
    const el = document.getElementById(cb.dataset.target);
    if (el) el.style.display = cb.checked ? '' : 'none';
  }});
}}
</script>
</body>
</html>
"""
    (print_dir / "index.html").write_text(page, encoding="utf-8")


def write_main_index(base_dir: Path, preamble: str, sections: list[dict[str, str]], disclaimer: str, page_title: str) -> None:
    intro = preamble.strip()
    cards = []
    for section in sections:
        cards.append(f"- [{section['number']}. {section['title']}](sections/{section['slug']}/)")

    content = f"{intro}\n\n# Modular Section Index\n\nThis page is intentionally shallow. Each technical topic opens into its own subpage so readers can navigate the guidance without being overwhelmed by the full depth of the document.\n\n[Print selected sections](print/)\n\n" + "\n".join(cards) + "\n\n"
    if disclaimer:
        content += disclaimer
    (base_dir / "index.md").write_text(content, encoding="utf-8")


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--target", required=True)
    parser.add_argument("--backup-dir", default="backups")
    parser.add_argument("--report-dir", default="gridbot_reports")
    parser.add_argument("--page-title", default="Employers Requirements Large Scale Solar")
    args = parser.parse_args()

    target = REPO_ROOT / safe_rel(args.target)
    if not target.exists():
        raise SystemExit(f"Target missing: {target}")

    base_dir = target.parent
    original = target.read_text(encoding="utf-8")
    preamble, sections = split_top_level_sections(original)
    disclaimer = extract_disclaimer(original)
    remove_disclaimer_from_last_section(sections)

    timestamp = dt.datetime.utcnow().strftime("%Y%m%d_%H%M%S")
    backup_dir = REPO_ROOT / safe_rel(args.backup_dir)
    backup_dir.mkdir(parents=True, exist_ok=True)
    backup_path = backup_dir / f"{target.stem}_before_modularise_{timestamp}{target.suffix}"
    backup_path.write_text(original, encoding="utf-8")

    sections_dir = base_dir / "sections"
    if sections_dir.exists():
        shutil.rmtree(sections_dir)
    print_dir = base_dir / "print"
    if print_dir.exists():
        shutil.rmtree(print_dir)

    write_section_pages(base_dir, sections, args.page_title)
    write_print_page(base_dir, sections, disclaimer, args.page_title)
    write_main_index(base_dir, preamble, sections, disclaimer, args.page_title)

    manifest = {
        "generated_at_utc": dt.datetime.utcnow().isoformat(timespec="seconds") + "Z",
        "target": args.target,
        "backup": str(backup_path.relative_to(REPO_ROOT)),
        "section_count": len(sections),
        "sections": [
            {"number": s["number"], "title": s["title"], "slug": s["slug"], "path": f"{base_dir.as_posix()}/sections/{s['slug']}/index.md"}
            for s in sections
        ],
        "print_page": f"{base_dir.as_posix()}/print/index.html",
    }
    (base_dir / "section_manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")

    report_dir = REPO_ROOT / safe_rel(args.report_dir)
    report_dir.mkdir(parents=True, exist_ok=True)
    report_path = report_dir / f"solar_er_modularise_{timestamp}.md"
    report_path.write_text(
        "# Solar ER Modularisation Report\n\n"
        f"UTC: {dt.datetime.utcnow().isoformat(timespec='seconds')}Z\n\n"
        f"Target: `{args.target}`\n\n"
        f"Backup: `{backup_path.relative_to(REPO_ROOT)}`\n\n"
        f"Sections generated: `{len(sections)}`\n\n"
        f"Print builder: `{base_dir.as_posix()}/print/index.html`\n\n"
        "Change: split top level numbered sections into clickable subpages and generated a checklist based print builder.\n",
        encoding="utf-8",
    )

    print(f"Modularised {target.relative_to(REPO_ROOT)}")
    print(f"Sections generated: {len(sections)}")
    print(f"Backup: {backup_path.relative_to(REPO_ROOT)}")
    print(f"Report: {report_path.relative_to(REPO_ROOT)}")


if __name__ == "__main__":
    main()