#!/usr/bin/env python3
"""
Re-embed WETH10 runtime bytecode in genesis JSON files from the current
contracts/tokens/WETH10.sol build (Foundry solc 0.8.20 + foundry.toml).

Run from repo:  python3 smom-dbis-138/scripts/sync-weth10-genesis-bytecode.py

Live Chain 138 nodes must NOT replace genesis.json in place (different genesis
= fork). Use this for new networks, templates, and Blockscout verification
alignment with the submodule source.
"""
from __future__ import annotations

import json
import subprocess
import sys
from pathlib import Path

WETH10 = "0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"
SMOM = Path(__file__).resolve().parent.parent
ROOT = SMOM.parent

GENESIS_FILES = [
    SMOM / "config" / "genesis.json",
    ROOT / "smom-dbis-138-proxmox" / "config" / "genesis.json",
    SMOM / "terraform" / "phases" / "phase1" / "config" / "genesis-138.json",
]
TEMPLATE = SMOM / "config" / "genesis-template-for-operator.json"


def forge_deployed_bytecode() -> str:
    out = subprocess.check_output(
        [
            "forge",
            "inspect",
            "contracts/tokens/WETH10.sol:WETH10",
            "deployedBytecode",
        ],
        cwd=str(SMOM),
        text=True,
    ).strip()
    if not out.startswith("0x"):
        raise SystemExit(f"unexpected forge output: {out[:80]}...")
    return out


def patch_alloc(alloc: dict, code: str) -> None:
    key = next((k for k in alloc if k.lower() == WETH10.lower()), None)
    if not key:
        raise SystemExit(f"alloc missing WETH10 ({WETH10})")
    entry = alloc[key]
    entry["code"] = code
    if "storage" not in entry:
        entry["storage"] = {}


def main() -> int:
    code = forge_deployed_bytecode()
    for path in GENESIS_FILES:
        if not path.is_file():
            print(f"skip (missing): {path}", file=sys.stderr)
            continue
        data = json.loads(path.read_text())
        patch_alloc(data["alloc"], code)
        path.write_text(json.dumps(data, indent=2) + "\n")
        print(f"updated {path}")

    if TEMPLATE.is_file():
        data = json.loads(TEMPLATE.read_text())
        g = data.get("genesis") or data
        alloc = g.get("alloc")
        if not alloc:
            raise SystemExit("template: no genesis.alloc")
        patch_alloc(alloc, code)
        TEMPLATE.write_text(json.dumps(data, indent=2) + "\n")
        print(f"updated {TEMPLATE}")

    print(f"WETH10 code length: {len(code)} chars (solc tail matches 0.8.x)")
    return 0


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