GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / globalgrid2050 / scripts

GlobalGrid2050 Gridbot Solar Peak Integrity Audit and 1 more file

A Python command-line tool in the scripts folder that fetches pvlive solar daily browser, pvlive solar daily candidate and pvlive solar recent 30d 30min browser, using SHA-256.

522 lines of Python from globalgrid2050, in 2 files. Topic: Solar and storage design. Section 70 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 Solar Peak Integrity Audit energy-data · globalgrid2050 / scripts/gridbot_solar_peak_integrity_audit.py lines 1–335
  2. GlobalGrid2050 Patch V8 Battery Energy Storage System (BESS) Tabs Small Step interaction · globalgrid2050 / scripts/patch_v8_bess_tabs_small_step.py lines 1–187

GlobalGrid2050 Gridbot Solar Peak Integrity Audit

A Python command-line tool in the scripts folder that fetches pvlive solar daily browser, pvlive solar daily candidate and pvlive solar recent 30d 30min browser, using SHA-256.

energy-dataglobalgrid2050 / scripts/gridbot_solar_peak_integrity_audit.py · lines 1–335 of 335 · Entry point · pattern compare_day (shared by 2 files)

What it does
It fetches pvlive solar daily browser, pvlive solar daily candidate, pvlive solar recent 30d 30min browser and pvlive solar daily backfill progress. Defines 21 functions or classes, including utc_now, load_json, sha256_file, payload_rows, as_float. Uses libraries __future__, argparse, datetime, hashlib, json. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file pvlive_solar_daily_browser.json; JSON file pvlive_solar_daily_candidate.json; JSON file pvlive_solar_recent_30d_30min_browser.json; JSON file pvlive_solar_daily_BACKFILL_PROGRESS.json; JSON file SOLAR_PEAK_INTEGRITY_LATEST.json; command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Gridbot Solar Peak Integrity Audit Workflow (globalgrid2050).
What it achieves
It parses time (`parse_time`) and compares day (`compare_day`). Defines `utc_now`, `load_json`, `sha256_file` and 17 more. It accepts `--start-month`, `--end-month` and `--dates`.
Why it matters
Run by GlobalGrid2050 Gridbot Solar Peak Integrity Audit Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, datetime, hashlib, json, urllib.parse, urllib.request, pathlib
Used by
run by GlobalGrid2050 Gridbot Solar Peak Integrity Audit Workflow (workflow run)
Produces
utc_now, load_json, sha256_file, payload_rows, as_float, month_start, next_month, month_key, expected_months, month_expected_days, parse_time, row_time
Defines here
utc_now, load_json, sha256_file, payload_rows, as_float, month_start, next_month, month_key, expected_months, month_expected_days, parse_time, row_time, row_mw, api_fetch_day, daily_index, coverage, top_daily_highs, recent_peak, field_integrity, compare_day, 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_solar_peak_integrity_audit.py:1-335 · blob ca39a95fc1f3ccb81487ed9b7e5242bafe285e16 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations

import argparse
import datetime as dt
import hashlib
import json
import urllib.parse
import urllib.request
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
DAILY_BROWSER = ROOT / 'uk_energy_tracking_v6' / 'generation_history' / 'pvlive_solar_daily_browser.json'
DAILY_CANDIDATE = ROOT / 'data' / 'confirmed' / 'pvlive_solar_daily_candidate.json'
RECENT_BROWSER = ROOT / 'uk_energy_tracking_v6' / 'generation_history' / 'pvlive_solar_recent_30d_30min_browser.json'
PROGRESS = ROOT / 'data' / 'confirmed' / 'pvlive_solar_daily_BACKFILL_PROGRESS.json'
REPORT = ROOT / 'data_science_protocol' / 'audit_reports' / 'SOLAR_PEAK_INTEGRITY_LATEST.md'
REPORT_JSON = ROOT / 'data_science_protocol' / 'audit_reports' / 'json' / 'SOLAR_PEAK_INTEGRITY_LATEST.json'
API = 'https://api.solar.sheffield.ac.uk/pvlive/api/v4/gsp/0'
SOURCE = 'Sheffield Solar PVLive'


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


def load_json(path: Path) -> dict:
    if not path.exists():
        return {}
    try:
        return json.loads(path.read_text(encoding='utf-8'))
    except Exception as exc:
        return {'_error': str(exc)}


def sha256_file(path: Path) -> str:
    if not path.exists():
        return ''
    return hashlib.sha256(path.read_bytes()).hexdigest()


def payload_rows(payload: dict) -> list:
    rows = payload.get('rows')
    return rows if isinstance(rows, list) else []


def as_float(value):
    try:
        return float(value)
    except Exception:
        return None


def month_start(value: str) -> dt.date:
    y, m = value.split('-')[:2]
    return dt.date(int(y), int(m), 1)


def next_month(value: dt.date) -> dt.date:
    return dt.date(value.year + 1, 1, 1) if value.month == 12 else dt.date(value.year, value.month + 1, 1)


def month_key(value: dt.date) -> str:
    return f'{value.year:04d}-{value.month:02d}'


def expected_months(start_month: str, end_month: str) -> list[str]:
    start = month_start(start_month)
    end = month_start(end_month)
    out = []
    d = start
    while d <= end:
        out.append(month_key(d))
        d = next_month(d)
    return out


def month_expected_days(month: str) -> int:
    start = month_start(month)
    end = next_month(start)
    return (end - start).days


def parse_time(value) -> str:
    try:
        d = dt.datetime.fromisoformat(str(value).replace('Z', '+00:00'))
        if d.tzinfo is None:
            d = d.replace(tzinfo=dt.timezone.utc)
        return d.astimezone(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
    except Exception:
        return ''


def row_time(row):
    if isinstance(row, list) and len(row) >= 2:
        return row[1]
    if isinstance(row, dict):
        return row.get('datetime_gmt') or row.get('datetime') or row.get('time') or row.get('timestamp') or row.get('periodStartUTC')
    return ''


def row_mw(row):
    if isinstance(row, list) and len(row) >= 3:
        return as_float(row[2])
    if isinstance(row, dict):
        return as_float(row.get('generation_mw') or row.get('generationMW') or row.get('generation') or row.get('power'))
    return None


def api_fetch_day(day: str) -> dict:
    d = dt.date.fromisoformat(day)
    start = dt.datetime.combine(d, dt.time(0, 0), tzinfo=dt.timezone.utc)
    end = dt.datetime.combine(d, dt.time(23, 59), tzinfo=dt.timezone.utc)
    url = API + '?' + urllib.parse.urlencode({'start': start.isoformat().replace('+00:00', 'Z'), 'end': end.isoformat().replace('+00:00', 'Z')})
    req = urllib.request.Request(url, headers={'User-Agent': 'GlobalGrid2050 GridBot Solar Peak Integrity Audit'})
    with urllib.request.urlopen(req, timeout=90) as response:
        payload = json.loads(response.read().decode('utf-8'))
    if isinstance(payload, dict):
        raw_rows = payload.get('data') or payload.get('results') or payload.get('items') or []
    elif isinstance(payload, list):
        raw_rows = payload
    else:
        raw_rows = []
    samples = []
    for raw in raw_rows:
        ts = parse_time(row_time(raw))
        mw = row_mw(raw)
        if ts and mw is not None:
            samples.append({'time': ts, 'mw': mw})
    if not samples:
        return {'date': day, 'url': url, 'sampleCount': 0, 'error': 'no valid samples'}
    high = max(samples, key=lambda x: x['mw'])
    low = min(samples, key=lambda x: x['mw'])
    total = sum(x['mw'] for x in samples)
    return {
        'date': day,
        'url': url,
        'sampleCount': len(samples),
        'averageMW': round(total / len(samples), 3),
        'highMW': round(high['mw'], 3),
        'highTimeUTC': high['time'],
        'lowMW': round(low['mw'], 3),
        'lowTimeUTC': low['time'],
        'mwh': round(total * 0.5, 3),
        'completeness': round(len(samples) / 48, 3)
    }


def daily_index(daily_rows: list) -> dict:
    return {r.get('date'): r for r in daily_rows if isinstance(r, dict) and r.get('date')}


def coverage(daily_rows: list, start_month: str, end_month: str) -> dict:
    by_year = {}
    by_month = {}
    bad_rows = 0
    for row in daily_rows:
        if not isinstance(row, dict):
            bad_rows += 1
            continue
        date = str(row.get('date', ''))
        if len(date) >= 7:
            by_year[date[:4]] = by_year.get(date[:4], 0) + 1
            by_month[date[:7]] = by_month.get(date[:7], 0) + 1
    expected = expected_months(start_month, end_month)
    month_table = []
    missing = []
    partial = []
    complete = []
    for month in expected:
        stored_days = by_month.get(month, 0)
        expected_days = month_expected_days(month)
        row = {'month': month, 'storedDays': stored_days, 'expectedDays': expected_days, 'state': 'complete' if stored_days >= expected_days else 'missing' if stored_days == 0 else 'partial'}
        month_table.append(row)
        if row['state'] == 'complete':
            complete.append(month)
        elif row['state'] == 'partial':
            partial.append(row)
        else:
            missing.append(month)
    return {
        'byYear': dict(sorted(by_year.items())),
        'monthTable': month_table,
        'completeMonths': complete,
        'partialMonths': partial,
        'missingMonths': missing,
        'badRows': bad_rows
    }


def top_daily_highs(daily_rows: list, limit: int):
    out = []
    for row in daily_rows:
        if not isinstance(row, dict):
            continue
        high = as_float(row.get('highMW'))
        if high is not None:
            out.append({
                'date': row.get('date'),
                'highMW': high,
                'averageMW': as_float(row.get('averageMW')),
                'lowMW': as_float(row.get('lowMW')),
                'mwh': as_float(row.get('mwh')),
                'sampleCount': row.get('sampleCount'),
                'completeness': row.get('completeness'),
                'source': row.get('source'),
                'methodState': row.get('methodState'),
                'status': row.get('status')
            })
    return sorted(out, key=lambda x: x['highMW'], reverse=True)[:limit]


def recent_peak(recent_rows: list):
    best = None
    for row in recent_rows:
        if not isinstance(row, dict):
            continue
        mw = as_float(row.get('generationMW') or row.get('mw') or row.get('value'))
        if mw is None:
            continue
        if best is None or mw > best['generationMW']:
            best = {'time': row.get('time'), 'generationMW': mw, 'technology': row.get('technology'), 'source': row.get('source')}
    return best


def field_integrity(daily_rows: list):
    required = ['date', 'technology', 'averageMW', 'highMW', 'lowMW', 'mwh', 'sampleCount', 'completeness', 'source', 'sourceAttribution', 'methodState', 'status']
    counts = {k: 0 for k in required}
    bad_numeric = []
    for row in daily_rows:
        if not isinstance(row, dict):
            continue
        for key in required:
            if row.get(key) not in (None, ''):
                counts[key] += 1
        for key in ['averageMW', 'highMW', 'lowMW', 'mwh', 'sampleCount', 'completeness']:
            if row.get(key) not in (None, '') and as_float(row.get(key)) is None:
                bad_numeric.append({'date': row.get('date'), 'field': key, 'value': row.get(key)})
    return {'requiredFieldCounts': counts, 'badNumericSamples': bad_numeric[:50]}


def compare_day(stored, fetched):
    if not stored:
        return {'presentInStored': False, 'fetched': fetched}
    comparison = {}
    for key in ['averageMW', 'highMW', 'lowMW', 'mwh', 'sampleCount', 'completeness']:
        sv = as_float(stored.get(key))
        fv = as_float(fetched.get(key))
        comparison[key] = {'stored': sv, 'fetched': fv, 'delta': None if sv is None or fv is None else round(sv - fv, 3)}
    return {'presentInStored': True, 'stored': stored, 'fetched': fetched, 'comparison': comparison}


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument('--start-month', default='2016-01')
    parser.add_argument('--end-month', default='')
    parser.add_argument('--dates', default='2026-04-23,2026-05-24')
    parser.add_argument('--top-n', type=int, default=20)
    parser.add_argument('--fetch-live', action='store_true')
    args = parser.parse_args()
    if args.end_month:
        end_month = args.end_month
    else:
        today = dt.datetime.now(dt.timezone.utc).date()
        end_month = f'{today.year:04d}-{today.month:02d}'

    daily_browser = load_json(DAILY_BROWSER)
    daily_candidate = load_json(DAILY_CANDIDATE)
    recent_browser = load_json(RECENT_BROWSER)
    progress = load_json(PROGRESS)
    browser_rows = payload_rows(daily_browser)
    candidate_rows = payload_rows(daily_candidate)
    recent_rows = payload_rows(recent_browser)
    idx = daily_index(browser_rows)
    requested_dates = [x.strip() for x in args.dates.split(',') if x.strip()]
    date_checks = {}
    for day in requested_dates:
        if args.fetch_live:
            try:
                date_checks[day] = compare_day(idx.get(day), api_fetch_day(day))
            except Exception as exc:
                date_checks[day] = {'error': str(exc)[:300], 'presentInStored': day in idx}
        else:
            date_checks[day] = {'presentInStored': day in idx, 'stored': idx.get(day), 'liveFetchSkipped': True}

    top_highs = top_daily_highs(browser_rows, args.top_n)
    max_high = top_highs[0] if top_highs else None
    cov = coverage(browser_rows, args.start_month, end_month)
    integrity = field_integrity(browser_rows)
    complete_months_in_progress = progress.get('completeMonths') if isinstance(progress.get('completeMonths'), list) else []
    report = {
        'generatedUTC': utc_now(),
        'purpose': 'Read only integrity audit of stored Sheffield Solar PVLive daily and recent Solar output numbers from 2016 to present.',
        'sourceExpected': SOURCE,
        'targetCoverage': {'startMonth': args.start_month, 'endMonth': end_month, 'targetFields': ['highMW', 'averageMW', 'lowMW', 'mwh', 'sampleCount', 'completeness']},
        'files': {
            'dailyBrowser': {'path': str(DAILY_BROWSER.relative_to(ROOT)), 'exists': DAILY_BROWSER.exists(), 'sha256': sha256_file(DAILY_BROWSER), 'rows': len(browser_rows), 'schemaVersion': daily_browser.get('schemaVersion'), 'generatedUTC': daily_browser.get('generatedUTC')},
            'dailyCandidate': {'path': str(DAILY_CANDIDATE.relative_to(ROOT)), 'exists': DAILY_CANDIDATE.exists(), 'sha256': sha256_file(DAILY_CANDIDATE), 'rows': len(candidate_rows), 'schemaVersion': daily_candidate.get('schemaVersion'), 'generatedUTC': daily_candidate.get('generatedUTC')},
            'recentBrowser': {'path': str(RECENT_BROWSER.relative_to(ROOT)), 'exists': RECENT_BROWSER.exists(), 'sha256': sha256_file(RECENT_BROWSER), 'rows': len(recent_rows), 'schemaVersion': recent_browser.get('schemaVersion'), 'generatedUTC': recent_browser.get('generatedUTC')},
            'progress': {'path': str(PROGRESS.relative_to(ROOT)), 'exists': PROGRESS.exists(), 'sha256': sha256_file(PROGRESS), 'completeMonths': complete_months_in_progress, 'failedMonths': progress.get('failedMonths')}
        },
        'coverage': cov,
        'fieldIntegrity': integrity,
        'progressVsStored': {
            'completeMonthsInProgress': complete_months_in_progress,
            'completeMonthsInStoredRows': cov['completeMonths'],
            'progressMonthsMissingFromStoredRows': [m for m in complete_months_in_progress if m not in cov['completeMonths']],
            'storedMonthsMissingFromProgress': [m for m in cov['completeMonths'] if m not in complete_months_in_progress]
        },
        'maxStoredDailyHighMW': max_high,
        'topStoredDailyHighs': top_highs,
        'recentHalfHourlyPeak': recent_peak(recent_rows),
        'dateChecks': date_checks,
        'integrityFlags': {
            'has20260423': '2026-04-23' in idx,
            'has20260524': '2026-05-24' in idx,
            'hasHighMW': integrity['requiredFieldCounts'].get('highMW', 0) == len(browser_rows) if browser_rows else False,
            'hasAverageMW': integrity['requiredFieldCounts'].get('averageMW', 0) == len(browser_rows) if browser_rows else False,
            'hasLowMW': integrity['requiredFieldCounts'].get('lowMW', 0) == len(browser_rows) if browser_rows else False,
            'hasMwh': integrity['requiredFieldCounts'].get('mwh', 0) == len(browser_rows) if browser_rows else False,
            'missingMonthCount': len(cov['missingMonths']),
            'partialMonthCount': len(cov['partialMonths'])
        },
        'decisionRule': 'Fill missing months before using Solar peak UI as authoritative. Do not claim a 2016 to present Solar series unless coverage shows complete or justified partial months.',
        'pass': bool(browser_rows and top_highs)
    }
    REPORT.parent.mkdir(parents=True, exist_ok=True)
    REPORT_JSON.parent.mkdir(parents=True, exist_ok=True)
    REPORT.write_text('# Solar Peak Integrity Audit\n\n```json\n' + json.dumps(report, indent=2) + '\n```\n', encoding='utf-8')
    REPORT_JSON.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
    print(json.dumps(report, indent=2))
    return 0 if report['pass'] else 1

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

GlobalGrid2050 Patch V8 Battery Energy Storage System (BESS) Tabs Small Step

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

interactionglobalgrid2050 / scripts/patch_v8_bess_tabs_small_step.py · lines 1–187 of 187 · Entry point

What it does
It loads battery storage (BESS), cables and transformers. Defines replace_panel, append_once, main. Uses libraries pathlib, datetime. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'bess'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: battery storage (BESS), cables, transformers.
Inputs & outputs
In: form fields (user input).
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Defines `replace_panel` and `append_once`. Its code works with 50 MW.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib, datetime
Used by
none found
Produces
replace_panel, append_once, main
Defines here
replace_panel, append_once, 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/patch_v8_bess_tabs_small_step.py:1-187 · blob 89633658e8cfde6030a6f6af4b49f0a965ee882c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from pathlib import Path
import datetime as dt

ROOT = Path(__file__).resolve().parents[1]
APP = ROOT / "solar-bess-topology-v8" / "bess-gis-sld-financial-sandbox"
INDEX = APP / "index.html"
CSS = APP / "gis-sld-v5.css"
UI = APP / "gis-sld-v5-ui.js"
REPORT = ROOT / "gridbot_reports" / "patch_v8_bess_tabs_small_step.md"

TABBED_PANEL = '''    <section id="v8_bess_panel" class="v8-bess-panel">
        <h3>BESS GIS SLD Financial Sandbox V8</h3>
        <div class="ux-note">BESS only study frame. Containers provide energy in MWh. PCS provides power in MW. Grid export caps the maximum export. Cable sizing, R, X, Z, leakage, reverse current and protection coordination remain in the advanced topology review.</div>

        <div class="v8-bess-tabs" role="tablist" aria-label="BESS controls">
            <button class="v8-bess-tab-btn active" type="button" data-v8-bess-tab="layout">Layout</button>
            <button class="v8-bess-tab-btn" type="button" data-v8-bess-tab="pcs">PCS</button>
            <button class="v8-bess-tab-btn" type="button" data-v8-bess-tab="finance">Finance</button>
            <button class="v8-bess-tab-btn" type="button" data-v8-bess-tab="map">Map Export</button>
            <button class="v8-bess-tab-btn" type="button" data-v8-bess-tab="notes">Notes</button>
        </div>

        <div id="v8_bess_tab_layout" class="v8-bess-tab-panel active" data-v8-bess-panel="layout">
            <h3>BESS Power and Energy</h3>
            <div class="input-group"><label>Grid Export Limit MW</label><input type="number" id="bess_export_mw" value="50" step="1" min="0" /></div>
            <div class="input-group"><label>Storage Duration Hours</label><input type="number" id="bess_duration_h" value="3" step="0.25" min="0" /></div>
            <div class="input-group"><label>Required Energy MWh</label><input type="number" id="bess_energy_mwh" value="150" step="1" min="0" /></div>
            <button id="btn_bess_sync_energy" type="button" class="btn-main">Set MWh from MW x hours</button>

            <h3>BESS Containers</h3>
            <div class="input-group"><label>Container Size</label><select id="bess_container_size"><option value="20ft">20 ft</option><option value="40ft" selected>40 ft</option></select></div>
            <div class="input-group"><label>Energy per Container MWh</label><input type="number" id="bess_container_mwh" value="5" step="0.1" min="0.1" /></div>
            <div class="input-group"><label>Container Length m</label><input type="number" id="bess_container_l" value="12.2" step="0.1" min="1" /></div>
            <div class="input-group"><label>Container Width m</label><input type="number" id="bess_container_w" value="2.44" step="0.01" min="1" /></div>
            <div class="input-group"><label>Container Spacing m</label><input type="number" id="bess_container_gap" value="2.5" step="0.1" min="0" /></div>
            <div class="input-group"><label>Containers per Row</label><input type="number" id="bess_containers_per_row" value="10" step="1" min="1" /></div>
            <div class="input-group"><label>Row Spacing m</label><input type="number" id="bess_row_gap" value="6" step="0.5" min="0" /></div>
        </div>

        <div id="v8_bess_tab_pcs" class="v8-bess-tab-panel" data-v8-bess-panel="pcs">
            <h3>PCS and Layout Mode</h3>
            <div class="input-group"><label>Layout Mode</label><select id="bess_layout_mode"><option value="integrated">Integrated PCS Transformer Station</option><option value="separated">External Transformer with Separate PCS</option><option value="distributed">Distributed PCS Islands</option><option value="corridor">PCS Corridor Layout</option><option value="central">Central PCS Block</option><  … [line shortened here: 481 characters; full line on GitHub]
            <div class="input-group"><label>PCS Rating MW</label><input type="number" id="bess_pcs_mw" value="50" step="0.1" min="0.1" /></div>
            <div class="input-group"><label>Containers per PCS</label><input type="number" id="bess_containers_per_pcs" value="30" step="1" min="1" /></div>
            <div class="input-group"><label>Access Road Width m</label><input type="number" id="bess_access_road_m" value="6" step="0.5" min="0" /></div>
            <div class="input-group"><label>Rotation Degrees</label><input type="number" id="bess_rotation_deg" value="0" step="5" /></div>
        </div>

        <div id="v8_bess_tab_finance" class="v8-bess-tab-panel" data-v8-bess-panel="finance">
            <h3>BESS Summary</h3>
            <div class="stat-row"><span>Required Containers</span><span class="stat-val" id="bess_out_containers">30</span></div>
            <div class="stat-row"><span>PCS Count</span><span class="stat-val" id="bess_out_pcs">1</span></div>
            <div class="stat-row"><span>Total PCS Power</span><span class="stat-val" id="bess_out_pcs_power">50 MW</span></div>
            <div class="stat-row"><span>Approximate BESS Field</span><span class="stat-val" id="bess_out_field">0 m x 0 m</span></div>
            <div class="stat-row"><span>Export Cap</span><span class="stat-val" id="bess_out_export">50 MW</span></div>
            <div class="stat-row"><span>Energy Duration</span><span class="stat-val" id="bess_out_duration">3 h</span></div>
            <div class="ux-note">Finance fields will be added after the BESS geometry is stable. This prevents hidden PV finance assumptions from being mistaken for BESS economics.</div>
        </div>

        <div id="v8_bess_tab_map" class="v8-bess-tab-panel" data-v8-bess-panel="map">
            <h3>Map and Export</h3>
            <div class="v8-bess-actions">
                <button id="btn_bess_draw_geo" type="button" class="btn-main">Draw BESS on Map</button>
                <button id="btn_bess_reset_geo" type="button" class="btn-main">Reset BESS Drawing</button>
                <button id="btn_bess_export_geojson" type="button" class="btn-main">Export BESS GeoJSON</button>
            </div>
            <div class="ux-note">Map drawing is layout screening only. Cable sizing and protection validation remain outside this app.</div>
        </div>

        <div id="v8_bess_tab_notes" class="v8-bess-tab-panel" data-v8-bess-panel="notes">
            <h3>Scope Notes</h3>
            <div class="ux-note v8-bess-note-block">This V8 screen is for standalone BESS layout, PCS arrangement and simple geospatial placement. It keeps the working V7 GIS frame but must not destabilise V7.</div>
            <div class="ux-note v8-bess-note-block">Future advanced versions may add client substation footprint, transformer bay footprint, fire access logic, acoustic barrier allowance and separate electrical topology review links.</div>
            <div class="ux-note v8-bess-note-block">Do not add cable sizing, R, X, Z impedance, leakage, reverse current or protection coordination into this layout tab. Those belong in the advanced topology review.</div>
        </div>
    </section>'''

CSS_BLOCK = '''

/* GLOBALGRID2050 V8 BESS TABS SMALL STEP */
.v8-bess-tabs {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin: 12px 0 10px 0;
  border-bottom: 1px solid var(--line);
  padding-bottom: 8px;
}
.v8-bess-tab-btn {
  flex: 1 1 86px;
  background: rgba(5, 5, 5, 0.9);
  color: var(--muted);
  border: 1px solid #444;
  border-radius: 3px;
  padding: 8px 6px;
  font-family: "Courier New", monospace;
  font-size: 10px;
  font-weight: bold;
  text-transform: uppercase;
  cursor: pointer;
}
.v8-bess-tab-btn.active {
  color: var(--accent);
  border-color: var(--accent);
  background: rgba(0, 255, 255, 0.06);
}
.v8-bess-tab-panel { display: none; }
.v8-bess-tab-panel.active { display: block; }
.v8-bess-actions { display: grid; gap: 8px; }
.v8-bess-note-block {
  display: block;
  border-left: 2px solid var(--accent);
  padding-left: 8px;
  margin: 8px 0;
  font-style: normal;
}
@media (max-width: 520px) {
  .v8-bess-tab-btn { flex-basis: 45%; font-size: 9px; }
}
'''

JS_BLOCK = '''

// GLOBALGRID2050 V8 BESS TABS SMALL STEP
function v8InitBessTabsSmallStep() {
    const panel = document.getElementById('v8_bess_panel');
    if (!panel) return;
    const buttons = panel.querySelectorAll('[data-v8-bess-tab]');
    const panels = panel.querySelectorAll('[data-v8-bess-panel]');
    buttons.forEach(button => {
        button.addEventListener('click', () => {
            const target = button.dataset.v8BessTab;
            buttons.forEach(btn => btn.classList.toggle('active', btn === button));
            panels.forEach(item => item.classList.toggle('active', item.dataset.v8BessPanel === target));
        });
    });
}

document.addEventListener('DOMContentLoaded', v8InitBessTabsSmallStep);
'''


def replace_panel(text: str) -> str:
    marker = '    <section id="v8_bess_panel" class="v8-bess-panel">'
    start = text.find(marker)
    if start == -1:
        raise SystemExit('v8_bess_panel start not found')
    hidden_marker = '\n\n    <div class="tab-container v8-hidden-pv">'
    end = text.find(hidden_marker, start)
    if end == -1:
        raise SystemExit('hidden PV marker not found after BESS panel')
    return text[:start] + TABBED_PANEL + text[end:]


def append_once(text: str, marker: str, block: str) -> str:
    if marker in text:
        return text
    return text.rstrip() + block + '\n'


def main() -> int:
    index = INDEX.read_text(encoding='utf-8')
    css = CSS.read_text(encoding='utf-8')
    ui = UI.read_text(encoding='utf-8')

    INDEX.write_text(replace_panel(index), encoding='utf-8')
    CSS.write_text(append_once(css, 'GLOBALGRID2050 V8 BESS TABS SMALL STEP', CSS_BLOCK), encoding='utf-8')
    UI.write_text(append_once(ui, 'v8InitBessTabsSmallStep', JS_BLOCK), encoding='utf-8')

    REPORT.parent.mkdir(parents=True, exist_ok=True)
    REPORT.write_text(
        '# Patch V8 BESS Tabs Small Step\n\n'
        f'Generated UTC: {dt.datetime.now(dt.timezone.utc).isoformat()}\n\n'
        '## Scope\n\n'
        'Adds compact BESS tabs inside the existing V8 BESS panel. No V7 files are modified. Map logic is not rebuilt. Hidden PV controls are left in place for now to avoid destabilising the inherited V7 frame.\n\n'
        '## Tabs\n\n'
        'Layout, PCS, Finance, Map Export and Notes.\n\n'
        '## Next safe step\n\n'
        'After live testing, add one BESS finance input group or one BESS map improvement only.\n',
        encoding='utf-8'
    )
    print('Patched V8 BESS tabs small step')
    return 0

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