GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / scripts

GlobalGrid2050 Clone UK Energy Tracking V4 to V5 and 3 more files

A Python command-line tool in the scripts folder that adds machine statement (`add_machine_statement`), updates homepage (`update_homepage`) and writes report (`write_report`).

466 lines of Python from globalgrid2050, in 4 files. Topic: Electricity markets and data pipelines. Section 870 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 Clone Generation History V6 to V6 2 energy-data · globalgrid2050 / scripts/clone_generation_history_v6_to_v6_2.py lines 1–133
  2. GlobalGrid2050 Clone UK Energy Tracking V2 storage · globalgrid2050 / scripts/clone_uk_energy_tracking_v2.py lines 1–24
  3. GlobalGrid2050 Clone UK Energy Tracking V2 to V3 storage · globalgrid2050 / scripts/clone_uk_energy_tracking_v2_to_v3.py lines 1–125
  4. GlobalGrid2050 Clone UK Energy Tracking V4 to V5 render · globalgrid2050 / scripts/clone_uk_energy_tracking_v4_to_v5.py lines 1–184

GlobalGrid2050 Clone Generation History V6 to V6 2

A Python command-line tool in the scripts folder that updates homepage (`update_homepage`) and writes report (`write_report`) (units: MWh).

energy-dataglobalgrid2050 / scripts/clone_generation_history_v6_to_v6_2.py · lines 1–133 of 133 · Entry point · pattern rewrite_text_files (shared by 2 files)

What it does
It loads data. Defines copy_tree, rewrite_text_files, update_homepage, write_report, main. Uses libraries pathlib, shutil, datetime. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'generation'): 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.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Clone Generation History V6 to V6 2 Workflow (globalgrid2050).
What it achieves
Defines `copy_tree`, `rewrite_text_files`, `update_homepage` and 1 more.
Why it matters
Run by GlobalGrid2050 Clone Generation History V6 to V6 2 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib, shutil, datetime
Used by
run by GlobalGrid2050 Clone Generation History V6 to V6 2 Workflow (workflow run)
Produces
copy_tree, rewrite_text_files, update_homepage, write_report, main
Defines here
copy_tree, rewrite_text_files, update_homepage, write_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/clone_generation_history_v6_to_v6_2.py:1-133 · blob aaacfaec1f9134b0d9867cba273af493acf54407 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
from pathlib import Path
import shutil
from datetime import datetime, timezone

ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "uk_energy_tracking_v6" / "generation_history"
DST = ROOT / "uk_energy_tracking_v6_2" / "generation_history"
REPORT = ROOT / "gridbot_reports" / "clone_generation_history_v6_to_v6_2.md"
INDEX = ROOT / "index.html"

TEXT_EXTS = {".md", ".html", ".js", ".css", ".json", ".geojson", ".csv", ".txt", ".yml", ".yaml"}

REPLACEMENTS = [
    ("/uk_energy_tracking_v6/generation_history/", "/uk_energy_tracking_v6_2/generation_history/"),
    ("./uk_energy_tracking_v6/generation_history/", "./uk_energy_tracking_v6_2/generation_history/"),
    ("uk_energy_tracking_v6/generation_history", "uk_energy_tracking_v6_2/generation_history"),
    ("UK Generation History V6 Module", "UK Generation History V6 2 Module"),
    ("GLOBALGRID2050 · ISOLATED V6 MODULE", "GLOBALGRID2050 · ISOLATED V6 2 MODULE"),
    ("V6GenerationHistoryConfig", "V62GenerationHistoryConfig"),
    ("V6LoadGenerationHistoryData", "V62LoadGenerationHistoryData"),
    ("V6RenderGenerationHistoryChart", "V62RenderGenerationHistoryChart"),
    ("V6ControlGenerationHistory", "V62ControlGenerationHistory"),
    ("V6LoadGenerationMwhAggregates", "V62LoadGenerationMwhAggregates"),
    ("V6RenderGenerationMwhAggregates", "V62RenderGenerationMwhAggregates"),
    ("V6ControlGenerationMwhAggregates", "V62ControlGenerationMwhAggregates"),
]


def copy_tree():
    if not SRC.exists():
        raise SystemExit(f"Missing source folder: {SRC}")
    if DST.exists():
        shutil.rmtree(DST)
    DST.mkdir(parents=True, exist_ok=True)
    copied = []
    for src_path in SRC.rglob("*"):
        rel = src_path.relative_to(SRC)
        dst_path = DST / rel
        if src_path.is_dir():
            dst_path.mkdir(parents=True, exist_ok=True)
            continue
        dst_path.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(src_path, dst_path)
        copied.append(dst_path.relative_to(ROOT).as_posix())
    return copied


def rewrite_text_files():
    changed = []
    for path in DST.rglob("*"):
        if not path.is_file() or path.suffix.lower() not in TEXT_EXTS:
            continue
        try:
            text = path.read_text(encoding="utf-8")
        except UnicodeDecodeError:
            continue
        original = text
        for old, new in REPLACEMENTS:
            text = text.replace(old, new)
        if "uk_energy_tracking_v6_2_2" in text or "V6 2 2" in text or "V622" in text:
            raise SystemExit(f"Unsafe double rewrite detected in {path.relative_to(ROOT)}")
        if text != original:
            path.write_text(text, encoding="utf-8")
            changed.append(path.relative_to(ROOT).as_posix())
    return changed


def update_homepage():
    row = '  <tr><td><a href="./uk_energy_tracking_v6_2/generation_history/">UK Generation History V6 2 Module</a> <span class="dev-status">(in development)</span></td></tr>'
    if not INDEX.exists():
        return False
    text = INDEX.read_text(encoding="utf-8")
    if row in text:
        return False
    anchor = '  <tr><td><a href="./uk_energy_tracking_v6/generation_history/">UK Generation History V6 Module</a></td></tr>'
    if anchor in text:
        text = text.replace(anchor, anchor + "\n" + row)
    else:
        text = text.replace("</table>", row + "\n</table>")
    INDEX.write_text(text, encoding="utf-8")
    return True


def write_report(copied, changed, homepage_changed):
    REPORT.parent.mkdir(parents=True, exist_ok=True)
    now = datetime.now(timezone.utc).strftime("%Y %m %d %H:%M UTC")
    changed_files = "\n".join(f"* {x}" for x in changed[:300]) or "* No text replacements required"
    REPORT.write_text(f"""# Clone Generation History V6 to V6 2

Generated: {now}

## Purpose

Create `uk_energy_tracking_v6_2/generation_history` as a controlled clone of the current V6 generation history module. V6 remains preserved as the live reference. V6 2 becomes the working module for FUELHH browser slim wiring, PV Live routing, reconciliation checks and user interface hardening.

## Source

* `uk_energy_tracking_v6/generation_history/`

## Destination

* `uk_energy_tracking_v6_2/generation_history/`

## Files copied

{len(copied)} files copied from V6 generation history to V6 2 generation history.

## Homepage

Root `index.html` V6 2 generation history link added: {homepage_changed}

## Text paths rewritten

{changed_files}

## Operating rule

V6 remains the live reference module. V6 2 is the working clone for safer data wiring and evidence closure. Future changes should land on V6 2 first, then be promoted only after human review.
""", encoding="utf-8")


def main():
    copied = copy_tree()
    changed = rewrite_text_files()
    homepage_changed = update_homepage()
    write_report(copied, changed, homepage_changed)
    print(f"Cloned {len(copied)} files from generation history V6 to V6 2")
    print(f"Text replacements: {len(changed)}")
    print(f"Homepage changed: {homepage_changed}")


if __name__ == "__main__":
    main()

GlobalGrid2050 Clone UK Energy Tracking V2

A Python module in the scripts folder that reads live grid energy, live grid price, live oil prices and oil price history.

storageglobalgrid2050 / scripts/clone_uk_energy_tracking_v2.py · lines 1–24 of 24 · Entry point

What it does
It loads live grid energy, live grid price, live oil prices and oil price history. Uses libraries pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): 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: JSON file live_grid_energy.json; JSON file live_grid_price.json; JSON file live_oil_prices.json; GeoJSON file oil_price_history.geojson.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Clone UK Energy Tracking V2 Workflow (globalgrid2050).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Run by GlobalGrid2050 Clone UK Energy Tracking V2 Workflow.
Application
globalgrid2050 · scripts · Python module
Uses
pathlib
Used by
run by GlobalGrid2050 Clone UK Energy Tracking V2 Workflow (workflow run)
Produces
none declared
Defines here
none
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/clone_uk_energy_tracking_v2.py:1-24 · blob 8076157b5e7ce2752fef231c46a272892c069cfb · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
from pathlib import Path

ROOT = Path(__file__).parent.parent
SRC = ROOT / "uk_energy_tracking" / "index.md"
DST_DIR = ROOT / "uk_energy_tracking_v2"
DST = DST_DIR / "index.md"

text = SRC.read_text(encoding="utf-8")
text = text.replace("title: UK Live Grid Tracker", "title: UK Live Grid Tracker V2")
text = text.replace("permalink: /uk_energy_tracking/", "permalink: /uk_energy_tracking_v2/")
text = text.replace("UK LIVE GRID TRACKER", "UK LIVE GRID TRACKER V2", 1)

# V2 is a UI test clone. It reads stable V1 data feeds until V2 pipelines are explicitly added.
text = text.replace('var ENERGY="./live_grid_energy.json", PRICE="./live_grid_price.json", OIL="./live_oil_prices.json", OIL_HISTORY="./oil_price_history.geojson", POLL=5*60*1000;',
                    'var ENERGY="/uk_energy_tracking/live_grid_energy.json", PRICE="/uk_energy_tracking/live_grid_price.json", OIL="/uk_energy_tracking/live_oil_prices.json", OIL_HISTORY="/uk_energy_tracking/oil_price_history.geojson", POLL=5*60*1000;')

marker = '<p class="scada-intro">'
note = '<p class="scada-intro" style="border:1px solid var(--gg-orange);padding:10px 12px;border-radius:4px;color:var(--gg-orange);">V2 development clone. Original tracker remains protected at /uk_energy_tracking/. This page uses V1 live feeds until V2 data pipelines are approved.</p>\n\n  '
if note not in text and marker in text:
    text = text.replace(marker, note + marker, 1)

DST_DIR.mkdir(parents=True, exist_ok=True)
DST.write_text(text, encoding="utf-8")
print(f"Cloned {SRC} to {DST}")

GlobalGrid2050 Clone UK Energy Tracking V2 to V3

A Python module in the scripts folder.

storageglobalgrid2050 / scripts/clone_uk_energy_tracking_v2_to_v3.py · lines 1–125 of 125 · Entry point

What it does
It loads data. Uses libraries pathlib, datetime, shutil. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): 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.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Clone UK Energy Tracking V2 to V3 Workflow (globalgrid2050).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Run by GlobalGrid2050 Clone UK Energy Tracking V2 to V3 Workflow.
Application
globalgrid2050 · scripts · Python module
Uses
pathlib, datetime, shutil
Used by
run by GlobalGrid2050 Clone UK Energy Tracking V2 to V3 Workflow (workflow run)
Produces
none declared
Defines here
none
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/clone_uk_energy_tracking_v2_to_v3.py:1-125 · blob 7ddb5063050b24812f9abb96d8f9e6dae0c03842 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
from pathlib import Path
from datetime import datetime, timezone
import shutil

ROOT = Path(__file__).resolve().parents[1]
V2 = ROOT / "uk_energy_tracking_v2"
V3 = ROOT / "uk_energy_tracking_v3"
SCRIPTS = ROOT / "scripts"
WORKFLOWS = ROOT / ".github" / "workflows"
REPORT = ROOT / "gridbot_reports" / "clone_uk_energy_tracking_v2_to_v3.md"

if not V2.exists():
    raise SystemExit("V2 folder missing: uk_energy_tracking_v2")

changes = []

if V3.exists():
    raise SystemExit("V3 already exists. Stop to avoid overwriting a working version.")

shutil.copytree(V2, V3)
changes.append("copied uk_energy_tracking_v2 to uk_energy_tracking_v3")

# Retarget text inside copied V3 files.
for path in V3.rglob("*"):
    if not path.is_file():
        continue
    if path.suffix.lower() not in {".md", ".json", ".geojson", ".html", ".js", ".css", ".txt"}:
        continue
    text = path.read_text(encoding="utf-8", errors="replace")
    new = text.replace("uk_energy_tracking_v2", "uk_energy_tracking_v3")
    new = new.replace("/uk_energy_tracking_v2/", "/uk_energy_tracking_v3/")
    new = new.replace("UK Live Grid Tracker V2", "UK Live Grid Tracker V3")
    new = new.replace("UK ENERGY TRACKING V2", "UK ENERGY TRACKING V3")
    new = new.replace("UK Live Grid Tracker V2 Development Twin", "UK Live Grid Tracker V3 Experimental Twin")
    new = new.replace("V2 development clone", "V3 experimental clone")
    new = new.replace("V2", "V3") if path.name in {"README.md", "AI_RELOAD_INSTRUCTIONS.md", "WORK_DIARY.md"} else new
    if new != text:
        path.write_text(new, encoding="utf-8")
        changes.append(f"retargeted {path.relative_to(ROOT)}")

# Clone V2 scripts into V3 scripts.
script_pairs = [
    ("update_uk_energy_v2.py", "update_uk_energy_v3.py"),
    ("update_uk_price_v2.py", "update_uk_price_v3.py"),
    ("update_oil_prices_v2.py", "update_oil_prices_v3.py"),
    ("update_uk_fuel_prices_v2.py", "update_uk_fuel_prices_v3.py"),
]
for src_name, dst_name in script_pairs:
    src = SCRIPTS / src_name
    dst = SCRIPTS / dst_name
    if src.exists():
        text = src.read_text(encoding="utf-8")
        text = text.replace("uk_energy_tracking_v2", "uk_energy_tracking_v3")
        text = text.replace("update_uk_energy_v2", "update_uk_energy_v3")
        text = text.replace("update_uk_price_v2", "update_uk_price_v3")
        text = text.replace("update_oil_prices_v2", "update_oil_prices_v3")
        text = text.replace("update_uk_fuel_prices_v2", "update_uk_fuel_prices_v3")
        dst.write_text(text, encoding="utf-8")
        changes.append(f"created {dst.relative_to(ROOT)}")

# Create V3 grid workflow from V2 workflow.
v2_workflow = WORKFLOWS / "fetch_uk_energy_and_prices_v2.yml"
v3_workflow = WORKFLOWS / "fetch_uk_energy_and_prices_v3.yml"
if v2_workflow.exists():
    text = v2_workflow.read_text(encoding="utf-8")
    text = text.replace("fetch_uk_energy_and_prices_v2", "fetch_uk_energy_and_prices_v3")
    text = text.replace("uk-energy-tracking-v2", "uk-energy-tracking-v3")
    text = text.replace("V2", "V3")
    text = text.replace("_v2.py", "_v3.py")
    text = text.replace("uk_energy_tracking_v2", "uk_energy_tracking_v3")
    text = text.replace("2-59/5", "4-59/5")
    v3_workflow.write_text(text, encoding="utf-8")
    changes.append(f"created {v3_workflow.relative_to(ROOT)}")

# Append V3 creation entry to V3 diary.
diary = V3 / "WORK_DIARY.md"
entry = f"""

## Diary entry: {datetime.now(timezone.utc).strftime('%Y-%m-%d')} V3 clone created

V3 was cloned from V2 as a controlled experimental build.

Purpose:

```text
V1 stable reference remains untouched.
V2 remains operational transport energy prototype.
V3 becomes the diary led experimental version for price history, graphs, diagnostics and competitor tracking comparison.
```

Operating rule:

```text
No wholesale rewrites.
One feature at a time.
One workflow at a time.
GridBot execution only.
Vikram triggers, tests and approves.
```

Next intended V3 feature:

```text
native electricity price history capture
last 7 days half hourly table
native one year price graph building from captured data only
no fake backfill
```
"""
with diary.open("a", encoding="utf-8") as f:
    f.write(entry)
changes.append("appended V3 creation diary entry")

# Create or update V3 reload note.
reload_file = V3 / "AI_RELOAD_INSTRUCTIONS.md"
with reload_file.open("a", encoding="utf-8") as f:
    f.write("\n\n## V3 reload note\n\nV3 is the experimental build. New energy graph and price history work should happen here first. Do not disturb V2 unless Vikram approves promotion.\n")
changes.append("appended V3 reload instruction")

REPORT.parent.mkdir(parents=True, exist_ok=True)
REPORT.write_text("# Clone UK energy tracker V2 to V3 report\n\n" + "\n".join(f"- {c}" for c in changes) + "\n", encoding="utf-8")

print("V3 clone complete")
for c in changes:
    print(c)

GlobalGrid2050 Clone UK Energy Tracking V4 to V5

A Python command-line tool in the scripts folder that adds machine statement (`add_machine_statement`), updates homepage (`update_homepage`) and writes report (`write_report`).

renderglobalgrid2050 / scripts/clone_uk_energy_tracking_v4_to_v5.py · lines 1–184 of 184 · Entry point · pattern rewrite_text_files (shared by 2 files)

What it does
It draws its content. Defines 6 functions or classes, including copy_tree, rewrite_text_files, add_machine_statement, update_homepage, write_report. Uses libraries pathlib, shutil, datetime. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): 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.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Clone UK Energy Tracking V4 to V5 Workflow (globalgrid2050).
What it achieves
Defines `copy_tree`, `rewrite_text_files`, `add_machine_statement` and 2 more.
Why it matters
Run by GlobalGrid2050 Clone UK Energy Tracking V4 to V5 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib, shutil, datetime
Used by
run by GlobalGrid2050 Clone UK Energy Tracking V4 to V5 Workflow (workflow run)
Produces
copy_tree, rewrite_text_files, add_machine_statement, update_homepage, write_report, main
Defines here
copy_tree, rewrite_text_files, add_machine_statement, update_homepage, write_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/clone_uk_energy_tracking_v4_to_v5.py:1-184 · blob e776c03db79133cd669cac2dd398cd63ec19032c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
from pathlib import Path
import shutil
from datetime import datetime, timezone

ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "uk_energy_tracking_v4"
DST = ROOT / "uk_energy_tracking_v5"
REPORT = ROOT / "gridbot_reports" / "clone_uk_energy_tracking_v4_to_v5.md"
INDEX = ROOT / "index.html"

TEXT_EXTS = {".md", ".html", ".js", ".css", ".json", ".geojson", ".csv", ".txt"}

REPLACEMENTS = [
    ("/uk_energy_tracking_v4/", "/uk_energy_tracking_v5/"),
    ("uk_energy_tracking_v4", "uk_energy_tracking_v5"),
    ("UK Live Grid Tracker V4", "UK Live Grid Tracker V5"),
    ("UK LIVE GRID TRACKER V4", "UK LIVE GRID TRACKER V5"),
    ("V4", "V5"),
    ("v4", "v5"),
]

MACHINE_BLOCK = """
      <div class=\"gg-machine-note\">
        <strong>Grid intelligence machine:</strong>
        <span><b>Inputs:</b> Elexon prices, live demand, carbon data, oil and fuel data, time windows, day and night filters.</span>
        <span><b>Mechanism:</b> lazy loading, event detection, high and low marker logic, date windowing, chart rendering, mobile full screen controls.</span>
        <span><b>Outputs:</b> price volatility insight, peak and trough timing, market spread visibility, battery opportunity signals, future circuit sizing logic.</span>
      </div>
"""

MACHINE_STYLE = """
#electricity-price-history-panel .gg-machine-note {
  border: 1px solid rgba(255,255,255,.10);
  background: rgba(255,255,255,.018);
  color: var(--gg-muted);
  font-size: 10.5px;
  line-height: 1.45;
  letter-spacing: .04em;
  padding: 8px 10px;
  margin: 8px 0 10px;
  border-radius: 5px;
}
#electricity-price-history-panel .gg-machine-note strong {
  color: var(--gg-cyan);
  text-transform: uppercase;
  letter-spacing: .10em;
  display: block;
  margin-bottom: 4px;
}
#electricity-price-history-panel .gg-machine-note span {
  display: block;
}
#electricity-price-history-panel .gg-machine-note b {
  color: var(--gg-text);
}
"""


def copy_tree():
    if not SRC.exists():
        raise SystemExit(f"Missing source folder: {SRC}")
    DST.mkdir(parents=True, exist_ok=True)
    copied = []
    for src_path in SRC.rglob("*"):
        rel = src_path.relative_to(SRC)
        dst_path = DST / rel
        if src_path.is_dir():
            dst_path.mkdir(parents=True, exist_ok=True)
            continue
        dst_path.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(src_path, dst_path)
        copied.append(dst_path.relative_to(ROOT).as_posix())
    return copied


def rewrite_text_files():
    changed = []
    for path in DST.rglob("*"):
        if not path.is_file() or path.suffix.lower() not in TEXT_EXTS:
            continue
        try:
            text = path.read_text(encoding="utf-8")
        except UnicodeDecodeError:
            continue
        original = text
        for old, new in REPLACEMENTS:
            text = text.replace(old, new)
        if text != original:
            path.write_text(text, encoding="utf-8")
            changed.append(path.relative_to(ROOT).as_posix())
    return changed


def add_machine_statement():
    index = DST / "index.md"
    if not index.exists():
        return False
    text = index.read_text(encoding="utf-8")
    changed = False
    if ".gg-machine-note" not in text:
        text = text.replace("</style>", MACHINE_STYLE + "\n</style>")
        changed = True
    if "Grid intelligence machine:" not in text:
        marker = '<canvas id="price-history-canvas" width="900" height="720"></canvas>'
        if marker in text:
            text = text.replace(marker, MACHINE_BLOCK + "\n" + marker)
            changed = True
    if changed:
        index.write_text(text, encoding="utf-8")
    return changed


def update_homepage():
    row = '  <tr><td><a href="./uk_energy_tracking_v5/">UK Live Grid Tracker V5, Electricity Market Intelligence Machine</a> <span class="dev-status">(in development)</span></td></tr>'
    if not INDEX.exists():
        return False
    text = INDEX.read_text(encoding="utf-8")
    if './uk_energy_tracking_v5/' in text:
        return False
    anchor = '  <tr><td><a href="./uk_energy_tracking_v3/">UK Live Grid Tracker V3, Experimental Intelligence Lab</a></td></tr>'
    if anchor in text:
        text = text.replace(anchor, anchor + "\n" + row)
    else:
        text = text.replace("</table>", row + "\n</table>")
    INDEX.write_text(text, encoding="utf-8")
    return True


def write_report(copied, changed, machine_changed, homepage_changed):
    REPORT.parent.mkdir(parents=True, exist_ok=True)
    now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
    changed_files = "\n".join(f"- {x}" for x in changed[:200]) or "- No text replacements required"
    REPORT.write_text(f"""# Clone UK Energy Tracking V4 to V5

Generated: {now}

## Purpose

Create `uk_energy_tracking_v5` as the next working clone of the current V4 electricity market intelligence tracker. V4 remains preserved as the digital twin and rollback reference.

## Source

- `uk_energy_tracking_v4/`

## Destination

- `uk_energy_tracking_v5/`

## Files copied

{len(copied)} files copied from V4 to V5.

## Homepage

Root `index.html` V5 link added: {homepage_changed}

## Machine statement

Small graph print added to V5: {machine_changed}

## Text paths rewritten

{changed_files}

## Operating rule

V4 is now the frozen twin. V5 is the working branch for the next round of chart, data pipeline, battery sizing and market intelligence development.
""", encoding="utf-8")


def main():
    copied = copy_tree()
    changed = rewrite_text_files()
    machine_changed = add_machine_statement()
    homepage_changed = update_homepage()
    write_report(copied, changed, machine_changed, homepage_changed)
    print(f"Cloned {len(copied)} files from V4 to V5")
    print(f"Text replacements: {len(changed)}")
    print(f"Machine statement changed: {machine_changed}")
    print(f"Homepage changed: {homepage_changed}")


if __name__ == "__main__":
    main()