"""
报销全流程编排

将发票提取 → 浏览器填报串联为一条管道，
数据在内存中流转，同时生成 CSV 中间产物。

发票类型区分：
    - 差旅发票（高铁票/酒店住宿）：不生成易耗品出库单，走差旅报销流程
    - 普通发票：生成易耗品出库单，走普通报销流程
"""

from pathlib import Path
from typing import Any

from . import get_logger
from .config import load_config
from .doc.extractor import extract_invoices
from .doc.invoice import (
    classify_invoice_batch,
    load_invoices_from_csv,
    save_invoice_csv,
)
from .doc.invoice import (
    save_csv as save_payment_csv,
)

log = get_logger("pipeline")


def _find_upload_directory(project_dir: Path) -> Path | None:
    """自动发现 uploads 目录下最新且包含 PDF 的会话文件夹"""
    uploads_base = project_dir / "src" / "web" / "uploads"
    if not uploads_base.is_dir():
        return None

    # 只选包含 PDF 的目录
    valid_dirs = [d for d in uploads_base.iterdir() if d.is_dir() and list(d.glob("*.pdf"))]
    if not valid_dirs:
        return None

    # 按修改时间排序，取最新
    session_dirs = sorted(
        valid_dirs,
        key=lambda d: d.stat().st_mtime,
        reverse=True,
    )
    return session_dirs[0]


def _classify_from_csv(csv_path: Path) -> dict[str, list[dict[str, Any]]]:
    """从已生成的 CSV 中读取发票数据并按类型分组"""
    rows = load_invoices_from_csv(csv_path)
    if rows is None:
        return {"travel": [], "general": []}
    return classify_invoice_batch(rows)


def run_pipeline(step: str = "all", username: str | None = None, password: str | None = None) -> int:
    """执行报销流程

    Args:
        step: all | invoice | submit
        username: 覆盖 config.json 中的用户名
        password: 覆盖 config.json 中的密码
    """
    config = load_config()
    if username:
        config["username"] = username
    if password:
        config["password"] = password

    # 工作目录（项目根目录）
    project_dir = Path(__file__).parent.parent

    # --------------------------------------------------
    # Step 1: 发票提取
    # --------------------------------------------------
    payment_records: list[dict[str, str]] | None = None
    groups: dict[str, list[dict[str, str]]] | None = None

    if step in ("all", "invoice"):
        log.info("=" * 60)
        log.info("[1/2] 发票提取")
        log.info("=" * 60)

        payment_records, groups = extract_invoices(str(project_dir))
        if not payment_records:
            log.error("未提取到任何发票数据")
            return 1

        save_payment_csv(payment_records, project_dir / "payment_records.csv")
        save_invoice_csv(payment_records, project_dir / "invoice_summary.csv")

        # 打印分类结果
        log.info(f"发票分类: 差旅 {len(groups['travel'])} 张, 普通 {len(groups['general'])} 张")

        if step == "invoice":
            log.info("[1/2] 发票提取 完成")
            return 0

    # --------------------------------------------------
    # Step 2: 浏览器填报
    # --------------------------------------------------
    if step in ("all", "submit"):
        log.info("=" * 60)
        log.info("[2/2] 报销提交")
        log.info("=" * 60)

        from .bot import load_invoice_data, run_bot

        csv_path = project_dir / "payment_records.csv"
        bot_invoices = load_invoice_data(str(csv_path), config)

        # 根据发票类型选择填报模式
        if groups is None:
            groups = _classify_from_csv(csv_path)

        if groups["travel"] and not groups["general"]:
            log.info("检测到纯差旅发票，使用差旅报销模式")
            # TODO: 差旅报销填报流程
            run_bot(config, bot_invoices)
        else:
            log.info("检测到普通发票，使用普通报销模式")
            run_bot(config, bot_invoices)

        if step == "submit":
            log.info("[2/2] 报销提交 完成")
            return 0

    # --------------------------------------------------
    # 全流程完成
    # --------------------------------------------------
    log.info("=" * 60)
    log.info("全流程执行完毕")
    log.info("=" * 60)
    return 0
