#!/usr/bin/env python3
"""
一次性备份:三所 .env + 中控 .env / hub_settings.json(不含图片,不含数据库).

用途:删除 gate,清库,全新计划启动前,在仓库根目录执行一次即可:

  python scripts/one_shot_backup_config_before_cleanup.py

输出目录默认:backups/one-shot-YYYYMMDD-HHMMSS/config/
"""
from __future__ import annotations

import shutil
import sys
from datetime import datetime
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]

CONFIG_SOURCES: list[tuple[str, Path]] = [
    ("crypto_monitor_binance.env", REPO_ROOT / "crypto_monitor_binance" / ".env"),
    ("crypto_monitor_okx.env", REPO_ROOT / "crypto_monitor_okx" / ".env"),
    ("crypto_monitor_gate.env", REPO_ROOT / "crypto_monitor_gate" / ".env"),
    ("manual_trading_hub.env", REPO_ROOT / "manual_trading_hub" / ".env"),
    ("hub_settings.json", REPO_ROOT / "manual_trading_hub" / "hub_settings.json"),
]

ENV_BACKUP_GLOBS = (
    REPO_ROOT / "crypto_monitor_binance",
    REPO_ROOT / "crypto_monitor_okx",
    REPO_ROOT / "crypto_monitor_gate",
)


def main() -> int:
    stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
    out_dir = REPO_ROOT / "backups" / f"one-shot-{stamp}" / "config"
    out_dir.mkdir(parents=True, exist_ok=True)

    copied: list[str] = []
    missing: list[str] = []

    for dest_name, src in CONFIG_SOURCES:
        if src.is_file():
            shutil.copy2(src, out_dir / dest_name)
            copied.append(dest_name)
        else:
            missing.append(str(src.relative_to(REPO_ROOT)))

    for inst_dir in ENV_BACKUP_GLOBS:
        for src in sorted(inst_dir.glob(".env.backup.*")):
            dest_name = f"{inst_dir.name}.{src.name}"
            shutil.copy2(src, out_dir / dest_name)
            copied.append(dest_name)

    manifest = out_dir.parent / "manifest.txt"
    lines = [
        f"created_at={stamp}",
        f"repo={REPO_ROOT}",
        "",
        "copied:",
        *[f"  - {name}" for name in copied],
        "",
        "missing (skipped):",
        *[f"  - {p}" for p in missing],
        "",
        "not included: crypto.db, hub *.db, static/images, gate",
    ]
    manifest.write_text("\n".join(lines) + "\n", encoding="utf-8")

    print(f"Backup written to: {out_dir}")
    if copied:
        print("Copied:", ", ".join(copied))
    if missing:
        print("Missing (ok if fresh install):", ", ".join(missing))
    print(f"Manifest: {manifest}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
