#!/usr/bin/env python3
"""
管理会计OS — 每日自动同步入口

由 cron 每天 01:00 调用：
  0 1 * * * cd /root/cma-management/backend && python3 scripts/daily_sync.py >> /var/log/cma-daily-sync.log 2>&1

手动执行：
  python3 scripts/daily_sync.py
"""

import sys
import os

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)

from app.database import get_session_local

if __name__ == "__main__":
    db = get_session_local()()

    # 1. ERP数据同步
    print("=" * 50)
    print("1/3 ERP数据同步")
    try:
        from scripts.erp_sync import run_sync
        run_sync(dry_run=False, use_api=True)
        print("  ✅ ERP同步完成")
    except Exception as e:
        print(f"  ❌ ERP同步异常: {e}")

    # 2. 预警生成
    print("\n" + "=" * 50)
    print("2/3 预警检查")
    try:
        from scripts.alert_generator import run_alert_check
        new_count = run_alert_check(db)
        print(f"  ✅ 预警检查完成: 新增 {new_count} 条")
    except Exception as e:
        print(f"  ❌ 预警生成异常: {e}")

    # 3. 预警推送
    print("\n" + "=" * 50)
    print("3/3 预警推送")
    try:
        from app.utils.notifier import push_pending_alerts
        pushed = push_pending_alerts(db)
        print(f"  ✅ 预警推送完成: {pushed} 条")
    except Exception as e:
        print(f"  ❌ 预警推送异常: {e}")

    # 4. 差异预警（实际vs预算）
    print("\n" + "=" * 50)
    print("4/4 差异预警检查")
    try:
        from app.utils.deviation_engine import run_deviation_check
        new_alerts = run_deviation_check(db)
        print(f"  ✅ 差异预警检查完成: 新增 {new_alerts} 条")
    except Exception as e:
        print(f"  ❌ 差异预警异常: {e}")

    db.close()
    print("\n" + "=" * 50)
    print("✅ 全部完成")
