"""提现对账(#4 孤儿单兜底)。

扫描超过 N 分钟仍 pending 的提现单,逐单查微信归一化:
  - 微信 SUCCESS               → 置 success
  - 微信失败/取消/关闭/无此单    → 退回现金 + 置 failed
  - WAIT_USER_CONFIRM(久未确认)→ 撤销 + 退款
防止"扣了款但转账没发起/没确认"的单永久锁住用户余额。

用法(建议 cron / systemd timer 每 5~10 分钟跑一次):
    python -m scripts.reconcile_withdraws            # 默认处理 >15 分钟的 pending
    python -m scripts.reconcile_withdraws 30         # 处理 >30 分钟的 pending
"""
from __future__ import annotations

import sys

# Windows 控制台按 UTF-8 输出中文/¥
try:
    sys.stdout.reconfigure(encoding="utf-8")  # type: ignore[attr-defined]
except Exception:  # noqa: BLE001
    pass

from app.repositories import wallet as crud_wallet
from app.db.session import SessionLocal


def main() -> None:
    minutes = int(sys.argv[1]) if len(sys.argv) > 1 else 15
    db = SessionLocal()
    try:
        result = crud_wallet.reconcile_pending_withdraws(db, older_than_minutes=minutes)
        print(f"对账完成: 检查 {result['checked']} 笔 pending(>{minutes}分钟), 归结 {result['resolved']} 笔")
    finally:
        db.close()


if __name__ == "__main__":
    main()
