#!/usr/bin/env bash
# Refresh chain138-command-center.meta.json before deploy (bundle version + optional route-matrix stamp).
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
META="${REPO_ROOT}/frontend/public/chain138-command-center.meta.json"
ROUTE_MATRIX="${REPO_ROOT}/config/aggregator-route-matrix.json"

python3 - "$META" "$ROUTE_MATRIX" <<'PY'
import json
import sys
from datetime import datetime, timezone
from pathlib import Path

meta_path = Path(sys.argv[1])
route_matrix_path = Path(sys.argv[2])
now = datetime.now(timezone.utc)
route_updated = None
if route_matrix_path.is_file():
    try:
        data = json.loads(route_matrix_path.read_text(encoding="utf-8"))
        route_updated = data.get("updated") or data.get("generatedAt")
    except (json.JSONDecodeError, OSError):
        pass

payload = {
    "bundleVersion": now.strftime("%Y-%m-%d"),
    "updatedAt": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
    "sourceDoc": "explorer-monorepo/docs/CHAIN138_VISUAL_TOPOLOGY_SOURCE.md",
    "routeMatrixUpdated": route_updated,
}
meta_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
print(f"Updated {meta_path}")
PY
