from __future__ import annotations

import json
import runpy
import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

PHONE = "19617449572"
MAIN_LEDGER = ROOT / "runtime" / "e2e_accounts.json"
TEST_LEDGER = ROOT / "runtime" / "e2e_accounts.test.json"
EXPORT_SCRIPT = ROOT / "scripts" / "export_e2e_accounts_excel.py"


def load_payload(path: Path) -> dict:
    if not path.exists():
        return {"accounts": [], "dispatched_orders": []}
    payload = json.loads(path.read_text(encoding="utf-8"))
    payload.setdefault("accounts", [])
    payload.setdefault("dispatched_orders", [])
    return payload


def main() -> None:
    main_payload = load_payload(MAIN_LEDGER)
    test_payload = load_payload(TEST_LEDGER)

    source = next(
        (
            item
            for item in main_payload["accounts"]
            if item.get("phone") == PHONE and item.get("account_type", "main") == "main"
        ),
        None,
    )
    if source is None:
        raise SystemExit(f"主台账未找到账号：{PHONE}")

    replaced = False
    for index, item in enumerate(test_payload["accounts"]):
        if item.get("phone") == PHONE and item.get("account_type", "main") == "main":
            test_payload["accounts"][index] = dict(source)
            replaced = True
            break
    if not replaced:
        test_payload["accounts"].append(dict(source))

    TEST_LEDGER.parent.mkdir(parents=True, exist_ok=True)
    TEST_LEDGER.write_text(json.dumps(test_payload, ensure_ascii=False, indent=2), encoding="utf-8")

    runpy.run_path(
        str(EXPORT_SCRIPT),
        init_globals={"SOURCE": TEST_LEDGER, "OUTPUT": TEST_LEDGER.with_suffix(".xlsx")},
        run_name="__main__",
    )
    print(f"synced_phone={PHONE}")
    print(f"main_ledger={MAIN_LEDGER}")
    print(f"test_ledger={TEST_LEDGER}")
    print(f"test_excel={TEST_LEDGER.with_suffix('.xlsx')}")


if __name__ == "__main__":
    main()
