#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
财务报销全流程编排脚本

依次执行:
  1. extract_invoice.py  — 从 PDF 发票提取信息，生成 invoice_summary.csv
  2. extract_image_ocr.py — 从支付截图 OCR 识别刷卡信息，更新 CSV
  3. reimburse.py         — 打开浏览器登录财务系统并自动填报

用法:
  python run_all.py                  # 默认执行全部三步
  python run_all.py --step invoice   # 仅执行第 1 步
  python run_all.py --step ocr       # 仅执行第 2 步
  python run_all.py --step submit    # 仅执行第 3 步
"""

import subprocess
import sys
from pathlib import Path

PROJECT_DIR = Path(__file__).parent.resolve()
PYTHON = sys.executable


def step(name: str, module: str, args: list[str]) -> bool:
    """运行单个步骤，返回是否成功"""
    cmd = [PYTHON, str(PROJECT_DIR / module), *args]
    print(f"\n{'=' * 60}")
    print(f"  [{name}] {module}")
    print(f"{'=' * 60}")

    result = subprocess.run(cmd, cwd=str(PROJECT_DIR))
    ok = result.returncode == 0

    if ok:
        print(f"\n[{name}] 完成")
    else:
        print(f"\n[错误] {name} 失败 (exit code: {result.returncode})")

    return ok


def run_all() -> int:
    print("=" * 60)
    print("  财务报销自动化流程")
    print(f"  工作目录: {PROJECT_DIR}")
    print(f"  Python:    {PYTHON}")
    print("=" * 60)

    if not step("发票提取", "extract_invoice.py", []):
        return 1

    if not step("OCR 识别", "extract_image_ocr.py", []):
        return 1

    if not step("报销提交", "reimburse.py", ["--data", str(PROJECT_DIR / "invoice_summary.csv")]):
        return 1

    print("\n" + "=" * 60)
    print("  全流程执行完毕")
    print("=" * 60)
    return 0


def main() -> int:
    if len(sys.argv) >= 3 and sys.argv[1] == "--step":
        name = sys.argv[2]
        steps = {
            "invoice": ("发票提取", "extract_invoice.py", []),
            "ocr": ("OCR 识别", "extract_image_ocr.py", []),
            "submit": ("报销提交", "reimburse.py", ["--data", str(PROJECT_DIR / "invoice_summary.csv")]),
        }
        if name not in steps:
            print(f"未知步骤: {name}，可选: {', '.join(steps)}")
            return 1
        label, module, args = steps[name]
        return 0 if step(label, module, args) else 1

    return run_all()


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