"""发票提取编排

串联 PDF 读取 → LLM 提取 → 支付截图匹配 → 分类，生成支付记录列表。

对外接口:
    extract_invoices(directory) -> tuple[list[dict], dict]
"""

from .. import get_logger
from .invoice import classify_invoice_batch
from .llm_extractor import extract_invoice_from_text
from .matcher import match_invoices_to_cards
from .pdf import extract_text_from_pdf, find_pdf_files

log = get_logger("extractor")


def extract_invoices(
    directory: str = ".",
) -> tuple[list[dict[str, str]], dict[str, list[dict[str, str]]]]:
    """扫描目录下所有 PDF,提取发票信息并匹配支付记录

    Returns:
        (payment_records, groups): 支付记录列表和按发票类型分组的字典
            groups = {'travel': [差旅发票], 'general': [普通发票]}
    """
    pdf_files = find_pdf_files(directory)
    if not pdf_files:
        log.warning("未找到 PDF 文件")
        return [], {"travel": [], "general": []}

    log.info(f"发现 {len(pdf_files)} 个 PDF 文件")

    all_invoices = []
    for pdf_path in pdf_files:
        text = extract_text_from_pdf(pdf_path)
        if not text:
            log.warning(f"未能提取文本: {pdf_path.name}")
            continue

        invoice = extract_invoice_from_text(text, pdf_path.name)

        if invoice and invoice.get("发票号码"):
            all_invoices.append(invoice)
            log.info(f"[{invoice['发票类型']}] 已解析: {pdf_path.name}")
        else:
            log.warning(f"未能解析: {pdf_path.name}")

    if all_invoices:
        log.info(f"共处理 {len(all_invoices)} 张发票")
    else:
        log.warning("未成功解析任何发票")

    # 将支付截图与发票进行金额匹配，返回以支付记录为主键的列表
    payment_records = match_invoices_to_cards(all_invoices, directory)

    # 从支付记录中还原所有发票用于分类
    all_invoices_restored: list[dict[str, str]] = []
    for record in payment_records:
        all_invoices_restored.extend(record.get("_matched_invoices", []))

    groups = classify_invoice_batch(all_invoices_restored)
    log.info(f"差旅发票: {len(groups['travel'])} 张, 普通发票: {len(groups['general'])} 张")

    return payment_records, groups
