#!/usr/bin/env python3
"""
三所 .env 一次性同步:计仓模式 + 自动划转(调用子脚本,不覆盖已有自定义值).

用法(仓库根目录):
  python scripts/sync_four_exchange_env.py
  python scripts/sync_four_exchange_env.py --dry-run
  python scripts/sync_four_exchange_env.py --set-transfer-amount 50 --enable-auto-transfer

子脚本可单独运行:
  python scripts/sync_four_exchange_position_sizing_env.py
  python scripts/sync_four_exchange_transfer_env.py

完整说明见 docs/env-sync-scripts.md
"""
from __future__ import annotations

import argparse
import subprocess
import sys
from pathlib import Path

REPO = Path(__file__).resolve().parent.parent
PY = sys.executable


def _run(script: str, extra: list[str]) -> int:
    cmd = [PY, str(REPO / "scripts" / script)] + extra
    print(f"\n>>> {' '.join(cmd)}")
    return subprocess.call(cmd, cwd=str(REPO))


def main():
    ap = argparse.ArgumentParser(description="三所 .env 统一同步(计仓 + 划转)")
    ap.add_argument("--dry-run", action="store_true")
    ap.add_argument("--set-mode", choices=("risk", "full_margin"), metavar="MODE")
    ap.add_argument("--set-transfer-amount", metavar="U")
    ap.add_argument("--enable-auto-transfer", action="store_true")
    args = ap.parse_args()

    dry = ["--dry-run"] if args.dry_run else []
    code = 0

    ps_args = list(dry)
    if args.set_mode:
        ps_args.extend(["--set-mode", args.set_mode])
    code |= _run("sync_four_exchange_position_sizing_env.py", ps_args)

    tr_args = list(dry)
    if args.set_transfer_amount:
        tr_args.extend(["--set-amount", args.set_transfer_amount])
    if args.enable_auto_transfer:
        tr_args.append("--enable-auto-transfer")
    code |= _run("sync_four_exchange_transfer_env.py", tr_args)

    sys.exit(code)


if __name__ == "__main__":
    main()
