from __future__ import annotations

import re
from datetime import datetime, timedelta


def resolve_application_time_label(facts: dict[str, str]) -> str:
    application_type = str(facts.get("application_type") or "").strip()
    if "差旅" in application_type or "出差" in application_type:
        return "出发时间"
    if "招待" in application_type or "宴请" in application_type or "餐饮" in application_type:
        return "招待时间"
    return "申请时间"


def _is_travel_application(facts: dict[str, str]) -> bool:
    application_type = str(facts.get("application_type") or "").strip()
    return "差旅" in application_type or "出差" in application_type


def _extract_application_day_count(value: str) -> int:
    match = re.search(r"(\d{1,2})\s*天", str(value or ""))
    if not match:
        return 0
    try:
        return max(0, int(match.group(1)))
    except ValueError:
        return 0


def _add_application_days(start_date: str, days: int) -> str:
    if not start_date or days <= 1:
        return start_date
    try:
        value = datetime.fromisoformat(start_date)
    except ValueError:
        return start_date
    return (value + timedelta(days=days - 1)).date().isoformat()


def _resolve_application_trip_dates(facts: dict[str, str]) -> tuple[str, str]:
    time_text = str(facts.get("time") or "").strip()
    matched_dates = re.findall(r"\d{4}-\d{2}-\d{2}", time_text)
    start_date = matched_dates[0] if matched_dates else time_text
    end_date = matched_dates[-1] if len(matched_dates) >= 2 else ""
    if not end_date or end_date == start_date:
        end_date = _add_application_days(start_date, _extract_application_day_count(facts.get("days", "")))
    return start_date, end_date or start_date


def build_application_time_rows(facts: dict[str, str]) -> list[tuple[str, str]]:
    if _is_travel_application(facts):
        start_date, end_date = _resolve_application_trip_dates(facts)
        return [
            ("出发时间", start_date),
            ("返回时间", end_date),
        ]
    return [(resolve_application_time_label(facts), facts.get("time", ""))]


def build_application_summary_rows(facts: dict[str, str]) -> list[tuple[str, str]]:
    return [
        ("申请类型", facts.get("application_type", "")),
        ("姓名", facts.get("applicant", "")),
        ("部门", facts.get("department", "")),
        ("岗位", facts.get("position", "")),
        ("职级", facts.get("grade", "")),
        ("直属领导", facts.get("manager_name", "")),
        *build_application_time_rows(facts),
        ("地点", facts.get("location", "")),
        ("事由", facts.get("reason", "")),
        ("天数", facts.get("days", "")),
        ("出行方式", facts.get("transport_mode", "")),
        ("住宿上限/天", facts.get("lodging_daily_cap", "")),
        ("补贴标准/天", facts.get("subsidy_daily_cap", "")),
        ("交通费用口径", facts.get("transport_policy", "")),
        ("规则测算参考", facts.get("policy_estimate", "")),
        ("系统预估费用", facts.get("amount", "")),
    ]


def build_application_summary(facts: dict[str, str]) -> str:
    return "\n".join(
        f"{label}：{value or '待补充'}"
        for label, value in build_application_summary_rows(facts)
    )


def build_application_summary_table(
    facts: dict[str, str],
    *,
    include_empty: bool = True,
) -> str:
    rows = build_application_summary_rows(facts)
    visible_rows = rows if include_empty else [(label, value) for label, value in rows if str(value or "").strip()]
    if not visible_rows:
        visible_rows = [("申请描述", "已收到，正在按费用申请上下文继续整理")]
    lines = ["| 字段 | 内容 |", "| --- | --- |"]
    lines.extend(f"| {label} | {value or '待补充'} |" for label, value in visible_rows)
    return "\n".join(lines)
