GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Cables and conductors / globalgrid2050 / repd_grid_atlasv6/.github/workflows

GlobalGrid2050 Modularise V6 Cable Geometry and 5 more files

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

618 lines of Python and YAML from globalgrid2050, in 6 files. Topic: Cables and conductors. Section 17 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. Fetch Subsea Data Cables v6 automation · globalgrid2050 / repd_grid_atlasv6/.github/workflows/fetch_subsea_data_cablesv6.yml lines 1–49
  2. Update 11kV UKPN v6 automation · globalgrid2050 / repd_grid_atlasv6/.github/workflows/update_11kv_ukpnv6.yml lines 1–46
  3. Fetch 11kV UKPN v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_11kv_ukpnv6.py lines 1–96
  4. Fetch 33kV Data v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_33kv_datav6.py lines 1–87
  5. Fetch Subsea Data Cables v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_subsea_data_cablesv6.py lines 1–109
  6. GlobalGrid2050 Modularise V6 Cable Geometry electrical · globalgrid2050 / scripts/modularise_v6_cable_geometry.py lines 1–231

Fetch Subsea Data Cables v6

A configuration file in GlobalGrid2050 covering cables. Runs on a schedule and by hand.

automationglobalgrid2050 / repd_grid_atlasv6/.github/workflows/fetch_subsea_data_cablesv6.yml · lines 1–49 of 49 · Not reached from any entry point (candidate for review)

Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: cables.
What it achieves
Runs `scripts/fetch_subsea_data_cables.py`.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · repd_grid_atlasv6/.github/workflows · configuration
Uses
none found
Used by
none found
Produces
none declared
Defines here
Fetch Subsea Data Cables
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 repd_grid_atlasv6/.github/workflows/fetch_subsea_data_cablesv6.yml:1-49 · blob 258699ad36f25566a0289fff5c8a2b47e4716f3c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
name: Fetch Subsea Data Cables

on:
  schedule:
    - cron: '0 4 2 * *'   # 2nd of every month at 04:00 UTC
  workflow_dispatch:

permissions:
  contents: write

env:
  FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true

jobs:
  fetch-subsea-data-cables:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.GRIDBOT_PAT }}

      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'

      - name: Install dependencies
        run: pip install requests

      - name: Run Subsea Data Cables Fetcher
        run: python scripts/fetch_subsea_data_cables.py

      - name: Commit and push changes
        env:
          PAT: ${{ secrets.GRIDBOT_PAT }}
        run: |
          git config --global user.name "gridbot"
          git config --global user.email "bot@globalgrid2050.com"
          
          git add subsea_data_cables.geojson || true
          
          if [ -n "$(git status --porcelain)" ]; then
            git commit -m "Automated Subsea Data Cables update: $(date -u +'%Y-%m-%d %H:%M UTC')"
            git push https://${PAT}@github.com/${{ github.repository }}.git HEAD:main
          else
            echo "No changes to commit"
          fi

Update 11kV UKPN v6

A configuration file in GlobalGrid2050 covering 11kV and substations. Runs on a schedule and by hand.

automationglobalgrid2050 / repd_grid_atlasv6/.github/workflows/update_11kv_ukpnv6.yml · lines 1–46 of 46 · Not reached from any entry point (candidate for review)

Why it exists in the grid workflow
Domain stage sub33kv_design (path word '11kv'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: 11kV, substations.
Inputs & outputs
Voltage levels named: 11kV.
What it achieves
Runs `scripts/fetch_11kv_ukpn.py`.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · repd_grid_atlasv6/.github/workflows · configuration
Uses
none found
Used by
none found
Produces
none declared
Defines here
Update 11kV UKPN Substations
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 repd_grid_atlasv6/.github/workflows/update_11kv_ukpnv6.yml:1-46 · blob 8fe484c6e42464e9b28bd04d58324960173dadab · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: sub33kv_design · users: IPP_developer, EPC_contractor, ICP_grid_engineer · canonical: unreached_review
name: Update 11kV UKPN Substations

on:
  schedule:
    - cron: '0 2 1 * *'   # monthly
  workflow_dispatch:

permissions:
  contents: write

jobs:
  fetch-11kv-ukpn:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.GRIDBOT_PAT }}

      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'

      - name: Install dependencies
        run: pip install requests

      - name: Run 11kV Substation Fetcher
        run: python scripts/fetch_11kv_ukpn.py

      - name: Commit and push changes
        env:
          PAT: ${{ secrets.GRIDBOT_PAT }}
        run: |
          git config --global user.name "gridbot"
          git config --global user.email "bot@globalgrid2050.com"

          git add grid_11kv_ukpn.geojson || true

          if [ -n "$(git status --porcelain)" ]; then
            git commit -m "Automated 11kV UKPN update: $(date -u +'%Y-%m-%d %H:%M UTC')"
            git push https://${PAT}@github.com/${{ github.repository }}.git HEAD:main
          else
            echo "No changes to commit"
          fi

Fetch 11kV UKPN v6

A Python command-line tool in the scripts folder of GlobalGrid2050 that fetches grid 11kV UKPN and substations from OpenStreetMap (Overpass).

storageglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_11kv_ukpnv6.py · lines 1–96 of 96 · Entry point

What it does
It fetches grid 11kV UKPN and substations. Defines fetch_11kv_substations. Uses libraries requests, json, time. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word '11kv'): 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, 11kV.
Inputs & outputs
In: data source: OpenStreetMap (Overpass); GeoJSON file grid_11kv_ukpn.geojson. Out: JSON file. Voltage levels named: 11kV.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Its name says it fetches 11kV UKPN. Defines `fetch_11kv_substations`. Its code works with 11 kV.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · repd_grid_atlasv6/scripts · Python CLI
Uses
requests, json, time
Used by
none found
Produces
fetch_11kv_substations
Defines here
fetch_11kv_substations
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 repd_grid_atlasv6/scripts/fetch_11kv_ukpnv6.py:1-96 · blob d0fd192eb20232b9baf1f3ba793ac22788eea600 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: sub33kv_design · users: IPP_developer, EPC_contractor, ICP_grid_engineer · canonical: production_core
import requests
import json
import time

OUTPUT_FILE = "grid_11kv_ukpn.geojson"

# UKPN coverage (London + South East + East)
UKPN_BBOX = [-1.5, 50.5, 1.8, 52.8]

OVERPASS_URL = "https://overpass-api.de/api/interpreter"

def fetch_11kv_substations():
    print("🚀 Fetching UKPN 11kV substations...")

    query = f"""
    [out:json][timeout:60];
    (
      node["power"="substation"]({UKPN_BBOX[1]},{UKPN_BBOX[0]},{UKPN_BBOX[3]},{UKPN_BBOX[2]});
      way["power"="substation"]({UKPN_BBOX[1]},{UKPN_BBOX[0]},{UKPN_BBOX[3]},{UKPN_BBOX[2]});
    );
    out center;
    """

    for attempt in range(3):
        try:
            response = requests.post(OVERPASS_URL, data=query, timeout=120)
            if response.status_code == 200:
                print("  ✅ Download successful")
                break
            else:
                print(f"  ⚠️ Attempt {attempt+1}: {response.status_code}")
                time.sleep(10)
        except Exception as e:
            print(f"  ❌ Error: {e}")
            time.sleep(10)
    else:
        print("  ❌ Failed after retries")
        return

    data = response.json()
    elements = data.get("elements", [])
    print(f"  📦 Raw elements: {len(elements)}")

    geojson = {"type": "FeatureCollection", "features": []}
    skipped = 0

    for el in elements:
        try:
            tags = el.get("tags", {})

            # STRICT: substations only
            if tags.get("power") != "substation":
                skipped += 1
                continue

            # Exclude transmission-level sites
            voltage = tags.get("voltage", "")
            if voltage and any(v in voltage for v in ["400000", "275000"]):
                skipped += 1
                continue

            lat = el.get("lat") or el.get("center", {}).get("lat")
            lon = el.get("lon") or el.get("center", {}).get("lon")

            if not lat or not lon:
                skipped += 1
                continue

            feature = {
                "type": "Feature",
                "properties": {
                    "name": tags.get("name", "Substation"),
                    "operator": tags.get("operator", "UKPN (est)"),
                    "voltage": voltage if voltage else "11kV (est)",
                    "type": "substation"
                },
                "geometry": {
                    "type": "Point",
                    "coordinates": [round(lon, 6), round(lat, 6)]
                }
            }

            geojson["features"].append(feature)

        except:
            skipped += 1
            continue

    with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
        json.dump(geojson, f)

    print(f"  ⏭️ Skipped: {skipped}")
    print(f"🎉 Saved: {len(geojson['features'])} substations")

if __name__ == "__main__":
    fetch_11kv_substations()

Fetch 33kV Data v6

A Python command-line tool in the scripts folder of GlobalGrid2050 that fetches 33kV from OpenStreetMap (Overpass). It fetches region (`fetch_region`).

storageglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_33kv_datav6.py · lines 1–87 of 87 · Entry point

What it does
It fetches 33kV. Defines fetch_region. Uses libraries requests, json, time, os. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word '33kv'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: 33kV.
Inputs & outputs
In: data source: OpenStreetMap (Overpass). Out: JSON file. Voltage levels named: 33kV.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Define the UK regions using Bounding Boxes [`min_lat`, `min_lon`, `max_lat`, `max_lon`]. Its code works with 33 kV.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · repd_grid_atlasv6/scripts · Python CLI
Uses
requests, json, time, os
Used by
none found
Produces
fetch_region
Defines here
fetch_region
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 repd_grid_atlasv6/scripts/fetch_33kv_datav6.py:1-87 · blob 8eaffbd04a76ca368209cf3dcac6eef9ef7d387d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: sub33kv_design · users: IPP_developer, EPC_contractor, ICP_grid_engineer · canonical: production_core
import requests
import json
import time
import os

# Define the UK regions using Bounding Boxes [min_lat, min_lon, max_lat, max_lon]
REGIONS = {
    "Scotland_North": [56.5, -7.5, 59.0, -1.5],
    "Scotland_South": [54.8, -5.5, 56.5, -1.5],
    "North_East_England": [54.0, -2.0, 55.8, -0.0],
    "North_West_England": [53.0, -3.5, 55.0, -2.0],
    "Yorkshire": [53.0, -1.5, 54.5, 0.5],
    "Wales_North": [52.5, -5.0, 53.5, -2.8],
    "Wales_South": [51.3, -5.5, 52.5, -2.5],
    "Midlands": [52.0, -3.0, 53.0, 0.5],
    "East_of_England": [51.5, 0.0, 53.0, 1.8],
    "South_West_England": [50.0, -6.0, 51.5, -2.0],
    "South_East_England": [50.5, -1.5, 51.5, 0.5],
    "London_Area": [51.2, -0.5, 51.8, 0.3]
}

def fetch_region(name, bbox):
    filename = f"grid_33kv_{name}.geojson"
    print(f"\n⚡ Fetching 33kV Data for: {name}...")
    
    # The (bbox) tag tells Overpass to only look inside these coordinates
    query = f"""
    [out:json][timeout:180];
    (
      way["power"="line"]["voltage"~"33000"]({bbox[0]},{bbox[1]},{bbox[2]},{bbox[3]});
      way["power"="cable"]["voltage"~"33000"]({bbox[0]},{bbox[1]},{bbox[2]},{bbox[3]});
    );
    out geom;
    """
    
    url = "https://overpass-api.de/api/interpreter"
    
    for attempt in range(3):
        print(f"  Attempt {attempt + 1}...")
        try:
            response = requests.post(url, data={'data': query})
            if response.status_code == 200:
                print("  ✅ Download successful!")
                break
            elif response.status_code == 429:
                print("  ⚠️ Server busy, sleeping 60s...")
                time.sleep(60)
            else:
                print(f"  ❌ Error: {response.status_code}")
                return
        except Exception as e:
            print(f"  ❌ Connection Error: {e}")
            return

    try:
        osm_data = response.json()
    except ValueError:
        print("  ❌ Failed to parse JSON.")
        return

    geojson = {"type": "FeatureCollection", "features": []}
    
    for element in osm_data.get('elements', []):
        if element['type'] == 'way' and 'geometry' in element:
            coords = [[node['lon'], node['lat']] for node in element['geometry']]
            # Strip metadata to keep file tiny, just keep voltage
            feature = {
                "type": "Feature",
                "properties": {"voltage": "33000"},
                "geometry": {"type": "LineString", "coordinates": coords}
            }
            geojson['features'].append(feature)
            
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(geojson, f)
        
    print(f"  💾 Saved {len(geojson['features'])} lines to {filename}")
    
    # Crucial: Sleep so we don't get banned by the API
    print("  😴 Sleeping 30 seconds to respect server limits...")
    time.sleep(30)

if __name__ == "__main__":
    print("🚀 Starting 33kV Regional Scraper...")
    for region_name, bbox in REGIONS.items():
        fetch_region(region_name, bbox)
    print("\n🎉 All 33kV regions finished!")

Fetch Subsea Data Cables v6

A Python command-line tool in the scripts folder of GlobalGrid2050 that fetches subsea cables from OpenStreetMap (Overpass).

storageglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_subsea_data_cablesv6.py · lines 1–109 of 109 · Entry point · pattern process_data (shared by 5 files)

What it does
It fetches subsea cables. Defines build_query, process_data, main. Uses libraries requests, json. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: data source: OpenStreetMap (Overpass). Out: GeoJSON file subsea_data_cables.geojson; JSON file.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Its name says it fetches subsea data cables. Defines `build_query` and `process_data`. It writes `subsea_data_cables.geojson`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · repd_grid_atlasv6/scripts · Python CLI
Uses
requests, json
Used by
none found
Produces
build_query, process_data, main
Defines here
build_query, process_data, 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 repd_grid_atlasv6/scripts/fetch_subsea_data_cablesv6.py:1-109 · blob 990236acf0cf902051d3a1924cc28e88e39b1d4b · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import requests
import json

OVERPASS_URL = "https://overpass-api.de/api/interpreter"

def build_query() -> str:
    # Casts the widest possible net for data cables in both Ways and Relations using pure OSM.
    # Excludes power to ensure we don't grab HVDC electrical interconnectors.
    return """[out:json][timeout:180];
    (
      // 1. INDIVIDUAL WAYS
      way["telecom"="cable"]["submarine"="yes"];
      way["telecom"="communication_cable"]["location"="underwater"];
      way["man_made"="submarine_cable"]["cable"="telecommunication"];
      way["man_made"="submarine_cable"][!"power"];
      way["seamark:type"="cable_submarine"]["seamark:cable_submarine:category"="optical_fibre"];
      way["seamark:type"="cable_submarine"][!"power"];
      
      // 2. MASSIVE RELATIONS (Trans-oceanic backbones)
      relation["telecom"="cable"]["submarine"="yes"];
      relation["telecom"="communication_cable"]["location"="underwater"];
      relation["man_made"="submarine_cable"]["cable"="telecommunication"];
      relation["man_made"="submarine_cable"][!"power"];
      relation["route"="telecom"]["submarine"="yes"];
      relation["seamark:type"="cable_submarine"][!"power"];
    );
    out geom;
    """

def process_data(data: dict) -> list:
    features = []
    seen_ways = set()

    # 1. FIRST PASS: Unpack the massive trans-oceanic Relations
    for el in data.get("elements", []):
        if el["type"] == "relation":
            tags = el.get("tags", {})
            name = tags.get("name", tags.get("seamark:name", "Global Subsea Route"))
            operator = tags.get("operator", "Telecom Operator")
            
            multiline = []
            for member in el.get("members", []):
                if member["type"] == "way" and "geometry" in member:
                    line = [[pt["lon"], pt["lat"]] for pt in member["geometry"]]
                    if len(line) >= 2:
                        multiline.append(line)
                        seen_ways.add(member["ref"]) 
            
            if multiline:
                features.append({
                    "type": "Feature",
                    "properties": {
                        "name": name,
                        "operator": operator,
                        "osm_id": el["id"],
                        "type": "subsea_data_cable"
                    },
                    "geometry": {
                        "type": "MultiLineString",
                        "coordinates": multiline
                    }
                })

    # 2. SECOND PASS: Grab individual ways (that weren't part of a larger relation)
    for el in data.get("elements", []):
        if el["type"] == "way" and el["id"] not in seen_ways and "geometry" in el:
            tags = el.get("tags", {})
            name = tags.get("name", tags.get("seamark:name", "Subsea Data Cable"))
            operator = tags.get("operator", "Telecom Operator")
            
            line = [[pt["lon"], pt["lat"]] for pt in el["geometry"]]
            if len(line) >= 2:
                features.append({
                    "type": "Feature",
                    "properties": {
                        "name": name,
                        "operator": operator,
                        "osm_id": el["id"],
                        "type": "subsea_data_cable"
                    },
                    "geometry": {
                        "type": "LineString",
                        "coordinates": line
                    }
                })

    return features

def main():
    print("Fetching Global Subsea Data Cables (Pure OpenStreetMap)...")
    query = build_query()
    try:
        res = requests.post(OVERPASS_URL, data={"data": query}, timeout=180)
        res.raise_for_status()
        raw_data = res.json()
    except Exception as e:
        print(f"Error fetching data: {e}")
        return
        
    features = process_data(raw_data)
    
    geojson = {"type": "FeatureCollection", "features": features}
    with open("subsea_data_cables.geojson", "w", encoding="utf-8") as f:
        json.dump(geojson, f, ensure_ascii=False, separators=(",", ":"))
        
    print(f"Saved {len(features)} global data cable structures to subsea_data_cables.geojson")

if __name__ == "__main__":
    main()

GlobalGrid2050 Modularise V6 Cable Geometry

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

electricalglobalgrid2050 / scripts/modularise_v6_cable_geometry.py · lines 1–231 of 231 · Entry point · pattern make_report (shared by 3 files)

What it does
It loads cables, solar and battery storage (BESS). Defines 12 functions or classes, including sha256, read, write, extract_style, extract_inline_scripts. Uses libraries pathlib, hashlib, re, datetime. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'cable'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables, solar, battery storage (BESS).
Downstream impact
Used directly by 1 file: GlobalGrid2050 V6 Cable Geometry Modularise Workflow (globalgrid2050).
What it achieves
It extracts style (`extract_style`), extracts inline scripts (`extract_inline_scripts`) and extracts main script (`extract_main_script`). Defines `sha256`, `read`, `write` and 8 more.
Why it matters
Run by GlobalGrid2050 V6 Cable Geometry Modularise Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib, hashlib, re, datetime
Used by
run by GlobalGrid2050 V6 Cable Geometry Modularise Workflow (workflow run)
Produces
sha256, read, write, extract_style, extract_inline_scripts, extract_main_script, find_anchor, split_js, replace_block, normalise_for_compare, make_report, main
Defines here
sha256, read, write, extract_style, extract_inline_scripts, extract_main_script, find_anchor, split_js, replace_block, normalise_for_compare, make_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/modularise_v6_cable_geometry.py:1-231 · blob 13f092b86738e7360d237621d1fce50bcbb8e50c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
from pathlib import Path
import hashlib
import re
from datetime import datetime, timezone

ROOT = Path(__file__).resolve().parents[1]
V5_HTML = ROOT / "solar-bess-topology-v5" / "cable-geometry-visualiser-v5.html"
APP_DIR = ROOT / "solar-bess-topology-v6" / "cable-geometry-visualiser"
V6_HTML = APP_DIR / "index.html"
REPORTS = ROOT / "gridbot_reports"
REPORT = REPORTS / "v6_cable_geometry_modularisation_phase_1.md"

OUTPUT_FILES = {
    "style.css": None,
    "data.js": None,
    "calculations.js": None,
    "rendering.js": None,
    "export.js": None,
    "ui.js": None,
}

SCRIPT_TAGS = """<script src=\"./data.js\"></script>
<script src=\"./calculations.js\"></script>
<script src=\"./rendering.js\"></script>
<script src=\"./export.js\"></script>
<script src=\"./ui.js\"></script>"""


def sha256(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


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


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


def extract_style(html: str) -> tuple[str, re.Match]:
    matches = list(re.finditer(r"<style>\s*(.*?)\s*</style>", html, flags=re.DOTALL | re.IGNORECASE))
    if len(matches) != 1:
        raise RuntimeError(f"Expected exactly 1 inline style block, found {len(matches)}")
    return matches[0].group(1), matches[0]


def extract_inline_scripts(html: str) -> list[re.Match]:
    return list(re.finditer(r"<script(?![^>]*\bsrc=)[^>]*>\s*(.*?)\s*</script>", html, flags=re.DOTALL | re.IGNORECASE))


def extract_main_script(html: str) -> tuple[str, re.Match]:
    matches = extract_inline_scripts(html)
    if len(matches) != 1:
        raise RuntimeError(f"Expected exactly 1 inline non src script block, found {len(matches)}")
    return matches[0].group(1), matches[0]


def find_anchor(js: str, anchor: str) -> int:
    pos = js.find(anchor)
    if pos < 0:
        raise RuntimeError(f"Missing required JavaScript anchor: {anchor}")
    return pos


def split_js(js: str) -> dict[str, str]:
    anchors = {
        "calculations": find_anchor(js, "function byId("),
        "rendering": find_anchor(js, "function renderStatus("),
        "export": find_anchor(js, "function exportJson("),
        "ui": find_anchor(js, "function populateFormationOptions("),
    }

    ordered = [
        ("data.js", 0, anchors["calculations"]),
        ("calculations.js", anchors["calculations"], anchors["rendering"]),
        ("rendering.js", anchors["rendering"], anchors["export"]),
        ("export.js", anchors["export"], anchors["ui"]),
        ("ui.js", anchors["ui"], len(js)),
    ]

    parts = {name: js[start:end] for name, start, end in ordered}
    for name, text in parts.items():
        if not text.strip():
            raise RuntimeError(f"Generated empty module: {name}")
    return parts


def replace_block(text: str, match: re.Match, replacement: str) -> str:
    return text[:match.start()] + replacement + text[match.end():]


def normalise_for_compare(text: str) -> str:
    return text.replace("\r\n", "\n").strip()


def make_report(
    css_v6: str,
    js_v6: str,
    parts: dict[str, str],
    rebuilt_css: str,
    rebuilt_js: str,
    v5_css: str | None,
    v5_js: str | None,
    checks: list[tuple[str, bool, str]],
) -> str:
    now = datetime.now(timezone.utc).isoformat()
    lines = [
        "# V6 Cable Geometry Modularisation Phase 1",
        "",
        f"UTC created: {now}",
        "",
        "Target app:",
        "",
        "`solar-bess-topology-v6/cable-geometry-visualiser/index.html`",
        "",
        "Purpose:",
        "",
        "Split the V6 cable geometry visualiser into external CSS and JavaScript files while preserving the original V6 runtime order and comparing the extracted logic against the original V5 visualiser.",
        "",
        "Generated files:",
        "",
    ]
    for name in OUTPUT_FILES:
        path = APP_DIR / name
        lines.append(f"- `{path.relative_to(ROOT)}`")

    lines.extend([
        "",
        "Checks:",
        "",
    ])
    for label, ok, detail in checks:
        status = "PASS" if ok else "FAIL"
        lines.append(f"- {status}: {label} {detail}".rstrip())

    lines.extend([
        "",
        "Hashes:",
        "",
        f"- V6 inline CSS before extraction: `{sha256(css_v6)}`",
        f"- V6 rebuilt CSS from module: `{sha256(rebuilt_css)}`",
        f"- V6 inline JS before extraction: `{sha256(js_v6)}`",
        f"- V6 rebuilt JS from modules: `{sha256(rebuilt_js)}`",
    ])
    if v5_css is not None:
        lines.append(f"- V5 original inline CSS: `{sha256(v5_css)}`")
    if v5_js is not None:
        lines.append(f"- V5 original inline JS: `{sha256(v5_js)}`")

    lines.extend([
        "",
        "Module sizes:",
        "",
        f"- `style.css`: {len(css_v6.splitlines())} lines",
    ])
    for name, text in parts.items():
        lines.append(f"- `{name}`: {len(text.splitlines())} lines")

    lines.extend([
        "",
        "Instruction:",
        "",
        "After the workflow runs, manually open the V6 cable geometry visualiser in the browser and compare the default visual output, input controls, export JSON and copy snapshot behaviour against the V5 original.",
        "",
    ])
    return "\n".join(lines)


def main() -> None:
    if not V6_HTML.exists():
        raise SystemExit(f"Missing V6 file: {V6_HTML}")
    if not V5_HTML.exists():
        raise SystemExit(f"Missing V5 baseline file: {V5_HTML}")

    html_v6 = read(V6_HTML)
    css_v6, style_match = extract_style(html_v6)
    js_v6, script_match = extract_main_script(html_v6)

    html_v5 = read(V5_HTML)
    v5_css, _ = extract_style(html_v5)
    v5_js, _ = extract_main_script(html_v5)

    parts = split_js(js_v6)
    rebuilt_js = "".join(parts[name] for name in ["data.js", "calculations.js", "rendering.js", "export.js", "ui.js"])
    rebuilt_css = css_v6

    new_html = replace_block(html_v6, script_match, SCRIPT_TAGS)
    new_html = replace_block(new_html, style_match, '<link rel="stylesheet" href="./style.css" />')

    write(APP_DIR / "style.css", css_v6)
    for name, text in parts.items():
        write(APP_DIR / name, text)
    write(V6_HTML, new_html)

    updated_html = read(V6_HTML)
    checks: list[tuple[str, bool, str]] = []
    checks.append(("V6 CSS module exactly rebuilds original V6 inline CSS", normalise_for_compare(rebuilt_css) == normalise_for_compare(css_v6), ""))
    checks.append(("V6 JS modules exactly rebuild original V6 inline JS", normalise_for_compare(rebuilt_js) == normalise_for_compare(js_v6), ""))
    checks.append(("V6 CSS matches original V5 inline CSS", normalise_for_compare(css_v6) == normalise_for_compare(v5_css), ""))
    checks.append(("V6 JS matches original V5 inline JS", normalise_for_compare(js_v6) == normalise_for_compare(v5_js), ""))
    checks.append(("V6 index now loads external style.css", '<link rel="stylesheet" href="./style.css" />' in updated_html, ""))
    checks.append(("V6 index now loads all 5 JavaScript modules", all(f'<script src="./{name}"></script>' in updated_html for name in ["data.js", "calculations.js", "rendering.js", "export.js", "ui.js"]), ""))
    checks.append(("V6 index no longer contains inline style block", "<style>" not in updated_html.lower(), ""))

    required_symbols = {
        "data.js": ["const DEFAULT_BURIAL_DEPTHS", "const FORMATION_LIBRARY", "const OD_CONFIRMED"],
        "calculations.js": ["function byId(", "function computeLayout(", "function buildReview("],
        "rendering.js": ["function renderStatus(", "function drawFormation(", "function drawTrench(", "function drawBend("],
        "export.js": ["function exportJson(", "function copySnapshot("],
        "ui.js": ["function populateFormationOptions(", "function renderAll(", "function bindEvents(", "init();"],
    }
    for name, symbols in required_symbols.items():
        text = read(APP_DIR / name)
        ok = all(symbol in text for symbol in symbols)
        checks.append((f"{name} contains expected runtime symbols", ok, ""))

    report = make_report(css_v6, js_v6, parts, rebuilt_css, rebuilt_js, v5_css, v5_js, checks)
    write(REPORT, report)

    failed = [label for label, ok, _ in checks if not ok]
    if failed:
        raise SystemExit("Modularisation checks failed:\n" + "\n".join(f"- {item}" for item in failed))

    print("V6 cable geometry modularisation phase 1 complete")
    print(f"Report written to {REPORT.relative_to(ROOT)}")


if __name__ == "__main__":
    main()