GLOBALGRID2050 / EXPLORE CODE

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

GlobalGrid2050 Update Commodities V5 and 1 more file

A Python command-line tool in the scripts folder that fetches live oil prices, oil price history and fredgraph. It parses dt (`parse_dt`) and loads existing live (`load_existing_live`).

582 lines of Python from globalgrid2050, in 2 files. Topic: Automation and CI. Section 1780 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 Track Repository Size storage · globalgrid2050 / scripts/track_repository_size.py lines 1–234
  2. GlobalGrid2050 Update Commodities V5 storage · globalgrid2050 / scripts/update_commodities_v5.py lines 1–348

GlobalGrid2050 Track Repository Size

A Python command-line tool in the scripts folder that fetches repository size history from GitHub API. It runs command (`run_command`), fetches GitHub repo metadata (`fetch_github_repo_metadata`) and reads history (`read_history`).

storageglobalgrid2050 / scripts/track_repository_size.py · lines 1–234 of 234 · Entry point · pattern append_history (shared by 2 files)

What it does
It fetches repository size history. Defines 11 functions or classes, including utc_now, mb_from_kb, run_command, local_du_kb, git_objects_summary. Uses libraries __future__, csv, json, os, subprocess. Side effects: reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
README: "It can be updated manually through the `Track Repository Size` GitHub Actions workflow and is scheduled to run once per month."
Inputs & outputs
In: data source: GitHub API; CSV file repository_size_history.csv.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Track Repository Size Workflow (globalgrid2050).
What it achieves
Creates a root level Markdown report and CSV history using GitHub repository metadata plus optional local checkout measurements when run inside GitHub.
Why it matters
Run by GlobalGrid2050 Track Repository Size Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, csv, json, os, subprocess, sys, datetime, pathlib
Used by
run by GlobalGrid2050 Track Repository Size Workflow (workflow run)
Produces
utc_now, mb_from_kb, run_command, local_du_kb, git_objects_summary, fetch_github_repo_metadata, read_history, append_history, status_for_size, write_report, main
Defines here
utc_now, mb_from_kb, run_command, local_du_kb, git_objects_summary, fetch_github_repo_metadata, read_history, append_history, status_for_size, 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/track_repository_size.py:1-234 · blob 477c320c9d7bb436caa173a773f57f248da7cb43 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""
GlobalGrid2050 repository size tracker.

Creates a root level Markdown report and CSV history using GitHub repository
metadata plus optional local checkout measurements when run inside GitHub
Actions.

This script is deliberately non destructive. It does not move data, delete files,
rewrite history, migrate to Git LFS or alter application paths.
"""

from __future__ import annotations

import csv
import json
import os
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen

ROOT = Path(__file__).resolve().parent.parent
REPORT_FILE = ROOT / "REPOSITORY_SIZE_REPORT.md"
HISTORY_FILE = ROOT / "repository_size_history.csv"

REPO_FULL_NAME = os.getenv("GITHUB_REPOSITORY", "Ventusltd/globalgrid2050")
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN") or os.getenv("GH_TOKEN") or os.getenv("GRIDBOT_PAT")

PRACTICAL_WATCH_MB = 500
PRACTICAL_PLAN_MB = 1000
HARD_SINGLE_FILE_WARNING_MB = 100


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


def mb_from_kb(kb: float | int | None) -> float | None:
    if kb is None:
        return None
    return round(float(kb) / 1024.0, 2)


def run_command(args: list[str]) -> str | None:
    try:
        completed = subprocess.run(args, cwd=ROOT, check=True, text=True, capture_output=True)
    except Exception:
        return None
    return completed.stdout.strip()


def local_du_kb(path: Path) -> int | None:
    text = run_command(["du", "-sk", str(path)])
    if not text:
        return None
    try:
        return int(text.split()[0])
    except (ValueError, IndexError):
        return None


def git_objects_summary() -> dict[str, str]:
    text = run_command(["git", "count-objects", "-vH"])
    if not text:
        return {}
    out: dict[str, str] = {}
    for line in text.splitlines():
        if ":" not in line:
            continue
        key, value = line.split(":", 1)
        out[key.strip()] = value.strip()
    return out


def fetch_github_repo_metadata() -> dict[str, object]:
    url = f"https://api.github.com/repos/{REPO_FULL_NAME}"
    headers = {
        "Accept": "application/vnd.github+json",
        "User-Agent": "GlobalGrid2050 repository size tracker",
    }
    if GITHUB_TOKEN:
        headers["Authorization"] = f"Bearer {GITHUB_TOKEN}"
    request = Request(url, headers=headers)
    try:
        with urlopen(request, timeout=30) as response:
            return json.loads(response.read().decode("utf-8"))
    except HTTPError as exc:
        raise SystemExit(f"GitHub API HTTP error {exc.code}: {exc.reason}") from exc
    except URLError as exc:
        raise SystemExit(f"GitHub API error: {exc.reason}") from exc


def read_history() -> list[dict[str, str]]:
    if not HISTORY_FILE.exists():
        return []
    with HISTORY_FILE.open("r", encoding="utf-8", newline="") as handle:
        return list(csv.DictReader(handle))


def append_history(row: dict[str, object]) -> list[dict[str, str]]:
    fields = [
        "checked_utc",
        "repository",
        "github_size_kb",
        "github_size_mb",
        "working_tree_kb",
        "working_tree_mb",
        "git_size_pack",
        "git_size_garbage",
        "watch_status",
    ]
    existing = read_history()
    new_row = {field: str(row.get(field, "")) for field in fields}
    if existing and existing[-1].get("github_size_kb") == new_row["github_size_kb"]:
        existing[-1] = new_row
    else:
        existing.append(new_row)
    with HISTORY_FILE.open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields)
        writer.writeheader()
        writer.writerows(existing)
    return existing


def status_for_size(size_mb: float | None) -> str:
    if size_mb is None:
        return "unknown"
    if size_mb >= PRACTICAL_PLAN_MB:
        return "plan data repository or paid storage now"
    if size_mb >= PRACTICAL_WATCH_MB:
        return "watch closely and design data split"
    return "normal"


def write_report(row: dict[str, object], history: list[dict[str, str]]) -> None:
    github_mb = row.get("github_size_mb")
    working_mb = row.get("working_tree_mb")
    status = row.get("watch_status")
    history_tail = history[-12:]

    lines = [
        "# GlobalGrid2050 Repository Size Report",
        "",
        "This report is generated by `scripts/track_repository_size.py` and can be updated manually or monthly by GitHub Actions.",
        "",
        "The purpose is to monitor repository growth without moving files, deleting history or splitting the data layer before there is a real need.",
        "",
        "## Latest measurement",
        "",
        f"Checked UTC: `{row.get('checked_utc')}`",
        f"Repository: `{row.get('repository')}`",
        f"GitHub reported size: `{row.get('github_size_kb')} KB` / `{github_mb} MB`",
        f"Local checkout size during workflow: `{row.get('working_tree_kb') or 'not measured'} KB` / `{working_mb if working_mb is not None else 'not measured'} MB`",
        f"Git object pack size: `{row.get('git_size_pack') or 'not measured'}`",
        f"Git garbage size: `{row.get('git_size_garbage') or 'not measured'}`",
        f"Watch status: `{status}`",
        "",
        "## Interpretation",
        "",
        "GitHub's reported repository size is the primary governance number for this project.",
        "",
        "A zipped download, a local checkout and a full clone can show different sizes because CSV and GeoJSON compress heavily and local clones include working files plus Git history.",
        "",
        "Historical data is not treated as junk. It is intentionally retained when it supports traceability, energy analysis or platform intelligence.",
        "",
        "Junk means local generated files such as Python cache, operating system files, temporary build folders or local environment files. Those are controlled by `.gitignore`.",
        "",
        "## Watch thresholds",
        "",
        f"Normal zone: below `{PRACTICAL_WATCH_MB} MB` reported by GitHub.",
        f"Planning zone: `{PRACTICAL_WATCH_MB} MB` to `{PRACTICAL_PLAN_MB} MB` reported by GitHub.",
        f"Action zone: around `{PRACTICAL_PLAN_MB} MB` reported by GitHub, or earlier if clone and workflow performance becomes poor.",
        f"Single file warning zone: around `{HARD_SINGLE_FILE_WARNING_MB} MB` for any individual file.",
        "",
        "## Future expansion options",
        "",
        "Do not execute these before launch unless explicitly approved.",
        "",
        "1. Keep the main repository as the website and application repository.",
        "2. Create a separate `globalgrid2050-data` repository only when repository size or workflow performance justifies it.",
        "3. Move high frequency CSV and GeoJSON history to the data repository only after dual path testing.",
        "4. Keep old data paths in the main repository during transition until live pages are proven stable.",
        "5. Consider Git LFS, GitHub Releases or commercial object storage only when the data layer requires it.",
        "",
        "## Last 12 measurements",
        "",
        "| Checked UTC | GitHub MB | Working tree MB | Status |",
        "|---|---:|---:|---|",
    ]
    for item in history_tail:
        lines.append(
            f"| {item.get('checked_utc', '')} | {item.get('github_size_mb', '')} | {item.get('working_tree_mb', '') or 'not measured'} | {item.get('watch_status', '')} |"
        )
    lines.extend([
        "",
        "## Launch freeze rule",
        "",
        "Until launch is complete, repository size monitoring is informational only. Do not move datasets, delete versions, split repositories or rewrite Git history without explicit human approval.",
        "",
    ])
    REPORT_FILE.write_text("\n".join(lines), encoding="utf-8")


def main() -> None:
    metadata = fetch_github_repo_metadata()
    github_size_kb = metadata.get("size")
    github_size_mb = mb_from_kb(github_size_kb if isinstance(github_size_kb, (int, float)) else None)
    working_tree_kb = local_du_kb(ROOT)
    working_tree_mb = mb_from_kb(working_tree_kb)
    git_summary = git_objects_summary()

    row: dict[str, object] = {
        "checked_utc": utc_now(),
        "repository": REPO_FULL_NAME,
        "github_size_kb": github_size_kb,
        "github_size_mb": github_size_mb,
        "working_tree_kb": working_tree_kb or "",
        "working_tree_mb": working_tree_mb if working_tree_mb is not None else "",
        "git_size_pack": git_summary.get("size-pack", ""),
        "git_size_garbage": git_summary.get("garbage", ""),
        "watch_status": status_for_size(github_size_mb),
    }
    history = append_history(row)
    write_report(row, history)
    print(f"Repository size report updated: {REPORT_FILE.name}")
    print(f"GitHub reported size: {github_size_mb} MB")
    print(f"Watch status: {row['watch_status']}")


if __name__ == "__main__":
    main()

GlobalGrid2050 Update Commodities V5

A Python command-line tool in the scripts folder that fetches live oil prices, oil price history and fredgraph. It parses dt (`parse_dt`) and loads existing live (`load_existing_live`).

storageglobalgrid2050 / scripts/update_commodities_v5.py · lines 1–348 of 348 · Entry point · pattern load_existing_history (shared by 5 files)

What it does
It fetches live oil prices, oil price history and fredgraph. Defines 17 functions or classes, including build_session, now_dt, now_utc, display_utc, parse_dt. Uses libraries csv, json, os, datetime, io. Side effects: reads or writes files; makes network requests.
Inputs & outputs
In: JSON file live_oil_prices.json; GeoJSON file oil_price_history.geojson; CSV file fredgraph.csv.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Update Prices Workflow (globalgrid2050).
What it achieves
Defines `build_session`, `now_dt`, `now_utc` and 13 more.
Why it matters
Run by GlobalGrid2050 Update Prices Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
csv, json, os, datetime, io, pathlib, requests, requests.adapters
Used by
run by GlobalGrid2050 Update Prices Workflow (workflow run)
Produces
build_session, now_dt, now_utc, display_utc, parse_dt, load_existing_live, should_skip_live_update, yahoo_price, fetch_fx, fetch_live_commodities, yahoo_history, fred_csv
Defines here
build_session, now_dt, now_utc, display_utc, parse_dt, load_existing_live, should_skip_live_update, yahoo_price, fetch_fx, fetch_live_commodities, yahoo_history, fred_csv, load_existing_history, history_is_recent, add_rows, oil_history_geojson, 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/update_commodities_v5.py:1-348 · blob 885256f3a520e0e33c9812b303733ece17b78f5f · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: unknown · users: none · canonical: production_core
import csv
import json
import os
from datetime import datetime, timezone, timedelta
from io import StringIO
from pathlib import Path

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

OUT_DIR = Path(__file__).parent.parent / "uk_energy_tracking_v5"
LIVE_FILE = OUT_DIR / "live_oil_prices.json"
HISTORY_FILE = OUT_DIR / "oil_price_history.geojson"
HEADERS = {"User-Agent": "Mozilla/5.0 GlobalGrid2050/1.0"}
LIVE_TIMEOUT = 15
HISTORY_TIMEOUT = 60
HISTORY_MAX_AGE_HOURS = 24
COMMODITY_MIN_UPDATE_MINUTES = 30
HISTORY_YEARS = 25

FALLBACK = {
    "gbpUSD": 1.3339,
    "gbpEUR": 1.1510,
    "copperUSDperTonne": 12850.0,
    "aluminiumUSDperTonne": 3520.0,
}


def build_session():
    retry_strategy = Retry(
        total=3,
        connect=3,
        read=3,
        status=3,
        backoff_factor=2,
        status_forcelist=[429, 500, 502, 503, 504],
        allowed_methods=["GET"],
        raise_on_status=False,
    )
    session = requests.Session()
    adapter = HTTPAdapter(max_retries=retry_strategy)
    session.mount("https://", adapter)
    session.mount("http://", adapter)
    session.headers.update(HEADERS)
    return session


SESSION = build_session()


def now_dt():
    return datetime.now(timezone.utc)


def now_utc():
    return now_dt().isoformat()


def display_utc(dt):
    return dt.astimezone(timezone.utc).strftime("%A %d %B %Y %H:%M UTC")


def parse_dt(value):
    if not value:
        return None
    try:
        text = str(value).replace("Z", "+00:00")
        dt = datetime.fromisoformat(text)
        if dt.tzinfo is None:
            dt = dt.replace(tzinfo=timezone.utc)
        return dt.astimezone(timezone.utc)
    except Exception:
        return None


def load_existing_live():
    if not LIVE_FILE.exists():
        return {}
    try:
        return json.loads(LIVE_FILE.read_text(encoding="utf-8"))
    except Exception:
        return {}


def should_skip_live_update():
    if os.getenv("FORCE_COMMODITIES") == "1":
        return False
    existing = load_existing_live()
    updated = parse_dt(existing.get("updated"))
    if not updated:
        return False
    return now_dt() - updated < timedelta(minutes=COMMODITY_MIN_UPDATE_MINUTES)


def yahoo_price(ticker):
    url = f"https://query1.finance.yahoo.com/v8/finance/chart/{ticker}"
    r = SESSION.get(url, timeout=LIVE_TIMEOUT)
    r.raise_for_status()
    payload = r.json()
    result = payload["chart"]["result"][0]
    return float(result["meta"]["regularMarketPrice"])


def fetch_fx():
    data = {"gbpUSD": FALLBACK["gbpUSD"], "gbpEUR": FALLBACK["gbpEUR"], "health": "fallback"}
    try:
        fx = SESSION.get("https://open.er-api.com/v6/latest/GBP", timeout=LIVE_TIMEOUT).json()
        data["gbpUSD"] = float(fx["rates"]["USD"])
        data["gbpEUR"] = float(fx["rates"]["EUR"])
        data["health"] = "ok"
    except Exception as exc:
        data["error"] = str(exc)
    return data


def fetch_live_commodities():
    health = {}
    out = {
        "updated": now_utc(),
        "updatedDisplayUTC": display_utc(now_dt()),
        "brentUSDperBarrel": None,
        "wtiUSDperBarrel": None,
        "copperUSDperTonne": None,
        "copperGBPperTonne": None,
        "copperEURperTonne": None,
        "aluminiumUSDperTonne": None,
        "aluminiumGBPperTonne": None,
        "aluminiumEURperTonne": None,
        "fx": {},
        "health": health,
    }

    for ticker, key in [("BZ=F", "brentUSDperBarrel"), ("CL=F", "wtiUSDperBarrel")]:
        try:
            out[key] = yahoo_price(ticker)
            health[ticker] = {"ok": True, "source": "Yahoo Finance chart endpoint"}
        except Exception as exc:
            health[ticker] = {"ok": False, "error": str(exc), "source": "Yahoo Finance chart endpoint"}

    fx = fetch_fx()
    out["fx"] = {
        "gbpUSD": fx["gbpUSD"],
        "gbpEUR": fx["gbpEUR"],
        "usdGBP": 1 / fx["gbpUSD"] if fx["gbpUSD"] else None,
        "usdEUR": fx["gbpEUR"] / fx["gbpUSD"] if fx["gbpUSD"] else None,
        "health": fx.get("health"),
    }
    if fx.get("error"):
        out["fx"]["error"] = fx["error"]

    metal_sources = [
        ("HG=F", "copperUSDperTonne", 2204.62, FALLBACK["copperUSDperTonne"], "Copper futures converted from USD per pound to USD per tonne"),
        ("ALI=F", "aluminiumUSDperTonne", 1.0, FALLBACK["aluminiumUSDperTonne"], "Aluminium futures in USD per tonne"),
    ]
    for ticker, key, multiplier, fallback, note in metal_sources:
        try:
            out[key] = yahoo_price(ticker) * multiplier
            health[ticker] = {"ok": True, "source": "Yahoo Finance chart endpoint", "note": note}
        except Exception as exc:
            out[key] = fallback
            health[ticker] = {"ok": False, "error": str(exc), "source": "Yahoo Finance chart endpoint", "fallbackUsed": True, "note": note}

    usd_gbp = out["fx"].get("usdGBP")
    usd_eur = out["fx"].get("usdEUR")
    if usd_gbp and usd_eur:
        out["copperGBPperTonne"] = out["copperUSDperTonne"] * usd_gbp if out["copperUSDperTonne"] is not None else None
        out["copperEURperTonne"] = out["copperUSDperTonne"] * usd_eur if out["copperUSDperTonne"] is not None else None
        out["aluminiumGBPperTonne"] = out["aluminiumUSDperTonne"] * usd_gbp if out["aluminiumUSDperTonne"] is not None else None
        out["aluminiumEURperTonne"] = out["aluminiumUSDperTonne"] * usd_eur if out["aluminiumUSDperTonne"] is not None else None

    return out


def yahoo_history(ticker):
    url = f"https://query1.finance.yahoo.com/v8/finance/chart/{ticker}?range={HISTORY_YEARS}y&interval=1d"
    r = SESSION.get(url, timeout=HISTORY_TIMEOUT)
    r.raise_for_status()
    result = r.json()["chart"]["result"][0]
    timestamps = result.get("timestamp") or []
    closes = (((result.get("indicators") or {}).get("quote") or [{}])[0].get("close") or [])
    rows = []
    cutoff = now_dt() - timedelta(days=HISTORY_YEARS * 366)
    for ts, close in zip(timestamps, closes):
        if close is None:
            continue
        dt = datetime.fromtimestamp(ts, timezone.utc)
        if dt < cutoff:
            continue
        rows.append((dt.strftime("%Y-%m-%d"), float(close)))
    if not rows:
        raise RuntimeError(f"Yahoo returned no usable history rows for {ticker}")
    return rows


def fred_csv(series):
    url = f"https://fred.stlouisfed.org/graph/fredgraph.csv?id={series}"
    r = SESSION.get(url, timeout=HISTORY_TIMEOUT)
    r.raise_for_status()
    rows = []
    cutoff = now_dt() - timedelta(days=HISTORY_YEARS * 366)
    for row in csv.DictReader(StringIO(r.text)):
        date = row.get("observation_date")
        value = row.get(series)
        if not date or not value or value == ".":
            continue
        try:
            dt = datetime.strptime(date, "%Y-%m-%d").replace(tzinfo=timezone.utc)
            if dt >= cutoff:
                rows.append((date, float(value)))
        except ValueError:
            continue
    if not rows:
        raise RuntimeError(f"FRED returned no usable rows for {series}")
    return rows


def load_existing_history():
    if not HISTORY_FILE.exists():
        return None
    try:
        existing = json.loads(HISTORY_FILE.read_text(encoding="utf-8"))
        if isinstance(existing.get("features"), list) and len(existing["features"]) > 0:
            return existing
    except Exception:
        return None
    return None


def history_is_recent(existing):
    if not existing:
        return False
    updated = existing.get("metadata", {}).get("updated")
    dt = parse_dt(updated)
    return bool(dt and now_dt() - dt < timedelta(hours=HISTORY_MAX_AGE_HOURS))


def add_rows(merged, rows, field):
    for date, value in rows:
        merged.setdefault(date, {})[field] = value


def oil_history_geojson():
    existing = load_existing_history()
    force_history = os.getenv("FORCE_OIL_HISTORY", "0") == "1"
    if existing and history_is_recent(existing) and not force_history:
        existing.setdefault("metadata", {})["lastSkippedHistoryUpdate"] = now_utc()
        existing["metadata"]["skipReason"] = "Existing oil history is less than 24 hours old. Live commodities update completed without re downloading full history."
        return existing, False

    health = []
    merged = {}
    for series, field, label in [
        ("DCOILBRENTEU", "brentUSDperBarrel", "FRED Brent Europe daily spot price"),
        ("DCOILWTICO", "wtiUSDperBarrel", "FRED WTI Cushing daily spot price"),
    ]:
        try:
            rows = fred_csv(series)
            add_rows(merged, rows, field)
            health.append({"ok": True, "source": label, "rows": len(rows)})
        except Exception as exc:
            msg = f"Failed to fetch {label}: {exc}"
            print(f"::warning::{msg}")
            health.append({"ok": False, "source": label, "error": msg})

    if not merged:
        for ticker, field, label in [
            ("BZ=F", "brentUSDperBarrel", "Yahoo Brent futures history"),
            ("CL=F", "wtiUSDperBarrel", "Yahoo WTI futures history"),
        ]:
            try:
                rows = yahoo_history(ticker)
                add_rows(merged, rows, field)
                health.append({"ok": True, "source": label, "rows": len(rows), "fallback": True})
            except Exception as exc:
                msg = f"Failed to fetch {label}: {exc}"
                print(f"::warning::{msg}")
                health.append({"ok": False, "source": label, "error": msg, "fallback": True})

    features = []
    for date in sorted(merged):
        features.append({
            "type": "Feature",
            "geometry": {"type": "Point", "coordinates": [0, 0]},
            "properties": {"date": date, **merged[date]},
        })

    if not features:
        if existing:
            existing.setdefault("metadata", {})["lastAttemptedUpdate"] = now_utc()
            existing["metadata"]["latestAttemptHealth"] = health
            existing["metadata"]["note"] = existing["metadata"].get("note", "") + " Existing non empty history preserved after latest failed fetch attempt."
            return existing, False
        return {
            "type": "FeatureCollection",
            "metadata": {
                "updated": now_utc(),
                "unit": "USD per barrel",
                "period": f"Last {HISTORY_YEARS} years",
                "note": "Oil history unavailable during this run. Live commodities were still updated.",
                "sources": health,
            },
            "features": [],
        }, False

    return {
        "type": "FeatureCollection",
        "metadata": {
            "updated": now_utc(),
            "unit": "USD per barrel",
            "period": f"Last {HISTORY_YEARS} years",
            "note": "Placeholder Point geometry. This is a portable time series for charting, not a spatial dataset. FRED is preferred. Yahoo history is used as fallback when FRED is unavailable.",
            "sources": health,
        },
        "features": features,
    }, True


def main():
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    if should_skip_live_update():
        print("V5 commodity slice skipped: existing live_oil_prices.json is less than 30 minutes old.")
        return

    live = fetch_live_commodities()
    LIVE_FILE.write_text(json.dumps(live, indent=2), encoding="utf-8")

    history, fetched_fresh_history = oil_history_geojson()
    HISTORY_FILE.write_text(json.dumps(history, indent=2), encoding="utf-8")

    print(json.dumps({
        "updatedDisplayUTC": live.get("updatedDisplayUTC"),
        "brentUSDperBarrel": live.get("brentUSDperBarrel"),
        "wtiUSDperBarrel": live.get("wtiUSDperBarrel"),
        "copperUSDperTonne": live.get("copperUSDperTonne"),
        "copperEURperTonne": live.get("copperEURperTonne"),
        "copperGBPperTonne": live.get("copperGBPperTonne"),
        "aluminiumUSDperTonne": live.get("aluminiumUSDperTonne"),
        "aluminiumEURperTonne": live.get("aluminiumEURperTonne"),
        "aluminiumGBPperTonne": live.get("aluminiumGBPperTonne"),
        "historyFeatures": len(history.get("features", [])),
        "freshHistoryWritten": fetched_fresh_history,
        "health": live.get("health", {}),
    }, indent=2))


if __name__ == "__main__":
    main()