#!/usr/bin/env python3
"""Generate the Qinghe fictional travel handbook from the supplied inputs.

Only standard-library modules are used. The same trip JSON drives the full HTML,
the DOCX source HTML copy, the rain alternative Markdown, and the budget workbook.
"""
from __future__ import annotations

import csv
import json
from copy import deepcopy
from datetime import datetime
from html import escape
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
INPUTS = ROOT / "inputs"
OUTPUTS = ROOT / "outputs"
DATA_DIR = OUTPUTS / "data"
BUILD_DIR = OUTPUTS / "_build" / "70e5e81f-3eac-4ec3-8893-22f0f80d8c01"
TRAVELERS = 2
BUDGET_CAP = 1200
DAY_ONE = "2026-11-30"
DAY_TWO = "2026-12-01"


def read_locations() -> dict[str, dict]:
    with (INPUTS / "地点资料.csv").open("r", encoding="utf-8-sig", newline="") as f:
        rows = list(csv.DictReader(f))
    result = {}
    for row in rows:
        result[row["地点"]] = {
            **row,
            "停留分钟": int(row["停留分钟"]),
            "门票每人元": int(row["门票每人元"]),
        }
    if len(result) != 5:
        raise ValueError("地点资料应包含 5 个不重复地点")
    return result


def read_packing_list() -> list[dict]:
    """Merge duplicate items by max per-person quantity, then multiply by 2."""
    path = INPUTS / "打包清单-补充.csv"
    with path.open("r", encoding="utf-8-sig", newline="") as f:
        rows = [(line_no, row) for line_no, row in enumerate(csv.DictReader(f), start=2)
                if any((v or "").strip() for v in row.values())]
    groups: dict[str, list[tuple[int, dict]]] = {}
    for line_no, row in rows:
        groups.setdefault(row["物品"].strip(), []).append((line_no, row))
    merged = []
    for item, entries in groups.items():
        units = {row["单位"].strip() for _line, row in entries}
        if len(units) != 1:
            raise ValueError(f"{item} 的单位不一致，不能自动合并")
        per_person = max(int(row["每人数量"]) for _line, row in entries)
        scenarios = "、".join(dict.fromkeys(row["场景"].strip() for _line, row in entries))
        lines = "、".join(str(line) for line, _row in entries)
        merged.append({
            "item": item,
            "per_person": per_person,
            "per_person_text": f"{per_person} {next(iter(units))}",
            "quantity": per_person * TRAVELERS,
            "quantity_text": f"{per_person * TRAVELERS} {next(iter(units))}",
            "unit": next(iter(units)),
            "scenario": scenarios,
            "status": "已合并",
            "note": f"来源：inputs/打包清单-补充.csv 第 {lines} 行；每人数量取最大值 {per_person}，再按 2 人计算，不累加重复场景。",
        })
    if len(merged) != 5:
        raise ValueError("补充清单合并后应为 5 项")
    return merged


def segment(seg_id: str, start: str, end: str, kind: str, title: str,
            place: str, transport: str, buffer_note: str, check: str,
            location: str | None = None, cost_per_person: int | None = None) -> dict:
    return {
        "id": seg_id,
        "start": start,
        "end": end,
        "kind": kind,
        "title": title,
        "place": place,
        "location": location,
        "transport": transport,
        "buffer": buffer_note,
        "check": check,
        "cost_per_person": cost_per_person,
    }


def day_one() -> dict:
    rows = [
        segment("D1-01", "09:00", "09:20", "交通", "酒店 → 艺术馆", "酒店 → 艺术馆",
                "公交，20 分钟，2 元/人", "到达后另加 10 分钟，见 D1-02",
                "旅行要求.md：每天 09:00 出发、地点间 20 分钟；公交 2 元/人", cost_per_person=2),
        segment("D1-02", "09:20", "09:30", "缓冲", "艺术馆交通后缓冲", "艺术馆（尚未入馆）",
                "无新增交通", "原地缓冲 10 分钟", "旅行要求.md：每次交通后另加 10 分钟缓冲"),
        segment("D1-03", "09:30", "10:00", "空闲", "开馆前等待", "艺术馆（尚未入馆）",
                "无新增交通", "不另加缓冲", "地点资料.csv：艺术馆周一 10:00 开放；不提前入场"),
        segment("D1-04", "10:00", "11:30", "参观", "艺术馆参观", "艺术馆",
                "无（原地活动）", "前序交通缓冲已完成", "地点资料.csv：周一 10:00-17:00；停留 90 分钟", location="艺术馆"),
        segment("D1-05", "11:30", "11:50", "交通", "艺术馆 → 老街", "艺术馆 → 老街",
                "公交，20 分钟，2 元/人", "到达后另加 10 分钟，见 D1-06",
                "旅行要求.md：地点间 20 分钟；公交 2 元/人", cost_per_person=2),
        segment("D1-06", "11:50", "12:00", "缓冲", "老街交通后缓冲", "老街",
                "无新增交通", "原地缓冲 10 分钟", "旅行要求.md：每次交通后另加 10 分钟缓冲"),
        segment("D1-07", "12:00", "13:00", "午餐", "老街内午餐", "老街",
                "无（当前地点内）", "不另加缓冲", "旅行要求.md：12:00-13:30 间至少 60 分钟；40 元/人"),
        segment("D1-08", "13:00", "14:00", "游览", "老街慢走", "老街",
                "无（原地活动）", "前序交通缓冲已完成", "地点资料.csv：周一 09:00-18:00；停留 60 分钟；有顶步道", location="老街"),
        segment("D1-09", "14:00", "14:20", "交通", "老街 → 酒店", "老街 → 酒店",
                "公交，20 分钟，2 元/人", "到达后另加 10 分钟，见 D1-10",
                "旅行要求.md：地点间 20 分钟；公交 2 元/人", cost_per_person=2),
        segment("D1-10", "14:20", "14:30", "缓冲", "回酒店后缓冲", "酒店",
                "无新增交通", "原地缓冲 10 分钟", "已在 18:00 前返回酒店"),
        segment("D1-11", "14:30", "18:00", "空闲", "酒店内自由安排", "酒店",
                "无新增交通", "不另加缓冲", "18:00 为日间时间轴终点，不再安排移动"),
    ]
    return {"id": "day1", "scenario": "晴雨相同", "date": DAY_ONE, "weekday": "周一",
            "title": "第一天｜艺术馆与老街", "segments": rows,
            "dinner": "回酒店后晚餐，50 元/人；具体起止时间待确认，不计入日间路线。"}


def day_two(scenario: str) -> dict:
    rainy = scenario == "雨天"
    target = "室内书店" if rainy else "公园"
    prefix = "D2R" if rainy else "D2S"
    suffix = "书店基础门票 0 元；可选消费 X 待确认" if rainy else "雨天不可用，晴天安排"
    rows = [
        segment(f"{prefix}-01", "09:00", "09:20", "交通", "酒店 → 博物馆", "酒店 → 博物馆",
                "公交，20 分钟，2 元/人", "到达后另加 10 分钟，见下一段",
                "旅行要求.md：每天 09:00 出发、地点间 20 分钟；公交 2 元/人", cost_per_person=2),
        segment(f"{prefix}-02", "09:20", "09:30", "缓冲", "博物馆交通后缓冲", "博物馆",
                "无新增交通", "原地缓冲 10 分钟", "旅行要求.md：每次交通后另加 10 分钟缓冲"),
        segment(f"{prefix}-03", "09:30", "11:30", "参观", "博物馆参观", "博物馆",
                "无（原地活动）", "前序交通缓冲已完成", "地点资料.csv：周一关闭，周二 09:00-17:00；停留 120 分钟", location="博物馆"),
        segment(f"{prefix}-04", "11:30", "11:50", "交通", f"博物馆 → {target}", f"博物馆 → {target}",
                "公交，20 分钟，2 元/人", "到达后另加 10 分钟，见下一段",
                "旅行要求.md：地点间 20 分钟；公交 2 元/人", cost_per_person=2),
        segment(f"{prefix}-05", "11:50", "12:00", "缓冲", f"{target}交通后缓冲", target,
                "无新增交通", "原地缓冲 10 分钟", "旅行要求.md：每次交通后另加 10 分钟缓冲"),
        segment(f"{prefix}-06", "12:00", "13:00", "午餐", f"{target}内午餐", target,
                "无（当前地点内）", "不另加缓冲", "旅行要求.md：12:00-13:30 间至少 60 分钟；40 元/人；餐饮供应待确认"),
        segment(f"{prefix}-07", "13:00", "14:00", "游览" if not rainy else "停留", f"{target}停留", target,
                "无（原地活动）", "前序交通缓冲已完成", f"地点资料.csv：周二 09:00-18:00；停留 60 分钟；{suffix}", location=target),
        segment(f"{prefix}-08", "14:00", "14:20", "交通", f"{target} → 酒店", f"{target} → 酒店",
                "公交，20 分钟，2 元/人", "到达后另加 10 分钟，见下一段",
                "旅行要求.md：地点间 20 分钟；公交 2 元/人", cost_per_person=2),
        segment(f"{prefix}-09", "14:20", "14:30", "缓冲", "回酒店后缓冲", "酒店",
                "无新增交通", "原地缓冲 10 分钟", "已在 18:00 前返回酒店"),
        segment(f"{prefix}-10", "14:30", "18:00", "空闲", "酒店内自由安排", "酒店",
                "无新增交通", "不另加缓冲", "18:00 为日间时间轴终点，不再安排移动"),
    ]
    return {"id": "day2_rain" if rainy else "day2_sunny", "scenario": scenario,
            "date": DAY_TWO, "weekday": "周二", "title": f"第二天{scenario}｜博物馆与{target}",
            "segments": rows,
            "dinner": "回酒店后晚餐，50 元/人；具体起止时间待确认，不计入日间路线。"}


def budget_item(category: str, item: str, quantity: int, unit: str,
                unit_price: int | None, factor: int, factor_label: str,
                included: bool, source: str, input_key: str | None = None,
                note: str = "") -> dict:
    amount = quantity * unit_price * factor if included and unit_price is not None else None
    return {"category": category, "item": item, "quantity": quantity, "unit": unit,
            "unit_price": unit_price, "factor": factor, "factor_label": factor_label,
            "included": included, "amount": amount, "source": source,
            "input_key": input_key, "note": note}


def common_budget() -> list[dict]:
    return [
        budget_item("住宿", "酒店", 1, "晚", 240, 1, "1 间", True,
                    "旅行要求.md：一间一晚 240 元", "hotel_night_price"),
        budget_item("餐饮", "早餐（含于房价）", 1, "间夜", 0, 1, "不另收费", True,
                    "旅行要求.md：早餐含于酒店价格", None),
        budget_item("餐饮", "午餐", 2, "天", 40, 2, "2 人", True,
                    "旅行要求.md：每天午餐 40 元/人", "lunch_per_person_day"),
        budget_item("餐饮", "晚餐", 2, "天", 50, 2, "2 人", True,
                    "旅行要求.md：每天晚餐 50 元/人", "dinner_per_person_day"),
        budget_item("门票", "博物馆", 1, "次", 30, 2, "2 人", True,
                    "地点资料.csv：博物馆 30 元/人", "museum_ticket"),
        budget_item("门票", "艺术馆", 1, "次", 20, 2, "2 人", True,
                    "地点资料.csv：艺术馆 20 元/人", "art_ticket"),
        budget_item("门票", "老街", 1, "次", 0, 2, "2 人", True,
                    "地点资料.csv：老街 0 元/人", "old_street_ticket"),
        budget_item("交通", "公交（每天 3 次/人，共 2 天）", 6, "次/人", 2, 2, "2 人", True,
                    "旅行要求.md：每次实际地点间移动 2 元/人；行程每天 3 次", "bus_per_person_trip"),
    ]


def make_budgets() -> dict:
    sunny = common_budget()
    sunny.insert(7, budget_item("门票", "公园", 1, "次", 0, 2, "2 人", True,
                                "地点资料.csv：公园 0 元/人", "park_ticket"))
    rain = common_budget()
    rain.insert(7, budget_item("门票", "室内书店基础门票", 1, "次", 0, 2, "2 人", True,
                               "地点资料.csv：室内书店基础门票 0 元/人", "bookstore_base_ticket",
                               "仅基础门票为 0；可选消费不能写成免费"))
    rain.append(budget_item("可选消费", "室内书店可选消费 X", 1, "项", None, 1, "两人合计", False,
                            "旅行要求.md：书店消费可选、未知，不纳入确定金额", "bookstore_optional_total",
                            "待确认；X 未提供，不计入 724 元"))
    budgets = {}
    for scenario, items in (("晴天", sunny), ("雨天", rain)):
        total = sum(x["amount"] for x in items if x["included"] and x["amount"] is not None)
        budgets[scenario] = {
            "items": items,
            "known_total": total,
            "known_per_person": total / TRAVELERS,
            "cap": BUDGET_CAP,
            "remaining": BUDGET_CAP - total,
            "formula": "240 + 0 + 160 + 200 + 60 + 40 + 0 + 24 = 724 元",
            "per_person_formula": "724 ÷ 2 = 362 元/人",
        }
    budgets["雨天"]["optional_formula"] = "若书店可选消费为 X：总额 724 + X；人均 (724 + X) ÷ 2；不增加其他支出时 X ≤ 476 元可不超上限。"
    return budgets


def minutes(hhmm: str) -> int:
    h, m = hhmm.split(":")
    return int(h) * 60 + int(m)


def validate(data: dict) -> list[str]:
    checks: list[str] = []
    all_days = data["itinerary"]
    for day in all_days:
        rows = day["segments"]
        if rows[0]["start"] != "09:00" or rows[-1]["end"] != "18:00":
            raise ValueError(f"{day['id']} 日间边界不符")
        for prev, curr in zip(rows, rows[1:]):
            if prev["end"] != curr["start"]:
                raise ValueError(f"{day['id']} 时间不连续：{prev['id']} / {curr['id']}")
        for idx, row in enumerate(rows):
            duration = minutes(row["end"]) - minutes(row["start"])
            if duration <= 0:
                raise ValueError(f"{row['id']} 时长无效")
            if row["kind"] == "交通":
                if duration != 20 or idx + 1 >= len(rows) or rows[idx + 1]["kind"] != "缓冲":
                    raise ValueError(f"{row['id']} 交通或后接缓冲不符")
                if minutes(rows[idx + 1]["end"]) - minutes(rows[idx + 1]["start"]) != 10:
                    raise ValueError(f"{row['id']} 后接缓冲不是 10 分钟")
            if row["location"]:
                loc = data["locations"][row["location"]]
                if row["kind"] in {"参观", "游览", "停留"}:
                    if duration != loc["停留分钟"] or duration > 120:
                        raise ValueError(f"{row['id']} 停留分钟不符")
                    opening = loc[f"{day['weekday']}开放"]
                    if opening == "关闭":
                        raise ValueError(f"{row['id']} 遇闭馆")
                    op, cl = opening.split("-")
                    if minutes(row["start"]) < minutes(op) or minutes(row["end"]) > minutes(cl):
                        raise ValueError(f"{row['id']} 超出开放时间")
            if row["kind"] == "午餐":
                if duration < 60 or not (minutes("12:00") <= minutes(row["start"]) <= minutes("13:30")):
                    raise ValueError(f"{row['id']} 午餐窗口或时长不符")
        checks.append(f"{day['title']}：{len(rows)} 段连续覆盖 09:00-18:00；交通、缓冲、停留与开放核对通过")
    sunny = next(x for x in all_days if x["id"] == "day2_sunny")["segments"]
    rainy = next(x for x in all_days if x["id"] == "day2_rain")["segments"]
    if [(x["start"], x["end"]) for x in sunny] != [(x["start"], x["end"]) for x in rainy]:
        raise ValueError("第二天晴雨起止时间轴应保持一致")
    checks.append("第二天雨天仅将公园替换为室内书店，其他起止时间、交通和缓冲不变")
    for scenario, budget in data["budgets"].items():
        if budget["known_total"] != 724 or budget["known_per_person"] != 362 or budget["remaining"] != 476:
            raise ValueError(f"{scenario} 预算复算失败")
        checks.append(f"{scenario}预算：确定总额 724 元，人均 362 元，余量 476 元；复算通过")
    return checks


def build_data() -> dict:
    data = {
        "meta": {
            "title": "虚构青禾市两天随身旅行手册",
            "label": "虚构练习",
            "travelers": TRAVELERS,
            "dates": [DAY_ONE, DAY_TWO],
            "budget_cap": BUDGET_CAP,
            "sources": ["inputs/旅行要求.md", "inputs/地点资料.csv", "inputs/打包清单-补充.csv"],
            "disclaimer": "全部地点、开放时间、价格和交通均为虚构教学数据，不可当真实旅行信息；不预订、不付款。",
        },
        "rules": {
            "daily_departure": "09:00", "return_by": "18:00", "transit_minutes": 20,
            "buffer_after_transit_minutes": 10, "max_continuous_stay_minutes": 120,
            "lunch_window": "12:00-13:30", "lunch_min_minutes": 60,
        },
        "locations": read_locations(),
        "itinerary": [day_one(), day_two("晴天"), day_two("雨天")],
        "budgets": make_budgets(),
        "rain_alternative": {
            "day1": "第一天无需改动：艺术馆雨天可用，老街有顶步道。",
            "day2": "第二天仅将公园替换为室内书店；其他安排、全部起止时间、交通与缓冲不变。",
        },
        "packing_list": read_packing_list(),
        "pending": [
            "实际天气：用于选择第二天晴天或雨天版本，待确认。",
            "酒店名称、地址、入住及退房规则：待确认；本手册不预订、不付款。",
            "各地点地址、公交线路、上下车站和乘车方向：待确认；仅采用每次 20 分钟、2 元/人的练习口径。",
            "预约要求、最后入场时间、临时闭馆或节假日调整：待确认；不据此虚构开放时间。",
            "具体餐厅、菜单及公园内餐饮供应：待确认；餐费仅按练习标准计算。",
            "室内书店可选消费 X：待确认，不纳入确定金额，不能写成免费。",
            "晚餐具体起止时间：待确认；回酒店后安排，不计入日间路线。",
            "打包物品规格（如容量、接口、尺寸）：待确认；不影响本次按每人最大数量合并。", 
        ],
    }
    data["validation"] = validate(data)
    return data


def md_table(headers: list[str], rows: list[list[str]]) -> str:
    def clean(v: object) -> str:
        return str(v).replace("|", "\\|").replace("\n", " ")
    return "\n".join(["| " + " | ".join(headers) + " |",
                      "|" + "|".join(["---"] * len(headers)) + "|",
                      *["| " + " | ".join(clean(v) for v in row) + " |" for row in rows]])


def itinerary_md(day: dict) -> str:
    rows = [[s["id"], s["start"], s["end"], s["title"], s["transport"], s["buffer"], s["check"]]
            for s in day["segments"]]
    return md_table(["编号", "开始", "结束", "安排", "交通", "缓冲", "核对与来源"], rows)


def budget_md(budget: dict, scenario: str) -> str:
    rows = []
    for x in budget["items"]:
        amount = f"{x['amount']} 元" if x["amount"] is not None else "待确认（X，不计入）"
        rows.append([x["category"], x["item"], f"{x['quantity']} {x['unit']}",
                     "待确认" if x["unit_price"] is None else f"{x['unit_price']} 元",
                     x["factor_label"], amount, x["source"]])
    parts = [md_table(["类别", "项目", "数量", "单价", "人数/间数", "金额", "来源"], rows),
             f"**{scenario}确定总额：{budget['known_total']} 元；人均：{budget['known_per_person']:.0f} 元；预算上限：{budget['cap']} 元；确定金额余量：{budget['remaining']} 元。**",
             f"复算：{budget['formula']}；{budget['per_person_formula']}。"]
    if "optional_formula" in budget:
        parts.append(budget["optional_formula"])
    return "\n\n".join(parts)


def render_markdown(data: dict, rain_only: bool = False) -> str:
    m = data["meta"]
    if rain_only:
        day2 = next(x for x in data["itinerary"] if x["id"] == "day2_rain")
        sections = [
            "# 虚构青禾市｜雨天替代",
            f"**{m['label']}｜2 位成人｜2026-11-30 至 2026-12-01**",
            m["disclaimer"],
            "## 一、替换原则",
            data["rain_alternative"]["day1"] + "\n\n" + data["rain_alternative"]["day2"],
            "## 二、第二天雨天完整时间轴（2026-12-01 周二）",
            itinerary_md(day2),
            day2["dinner"],
            "## 三、雨天预算",
            budget_md(data["budgets"]["雨天"], "雨天"),
            "## 四、合并打包清单",
            md_table(["物品", "每人数量", "两人合计", "适用场景", "状态", "说明"],
                     [[x["item"], x["per_person_text"], x["quantity_text"], x["scenario"], x["status"], x["note"]]
                      for x in data["packing_list"]]),
            "## 五、待确认项",
            "\n".join(f"- {x}" for x in data["pending"]),
            "## 六、资料来源",
            "- inputs/旅行要求.md\n- inputs/地点资料.csv\n- inputs/打包清单-补充.csv",
        ]
        return "\n\n".join(sections) + "\n"
    days = {x["id"]: x for x in data["itinerary"]}
    sections = [
        f"# {m['title']}",
        f"**{m['label']}｜2 位成人｜2026-11-30 周一至 2026-12-01 周二**",
        m["disclaimer"],
        "## 一、使用说明",
        "每天 09:00 从酒店出发，18:00 前返回；每次公交 20 分钟后单列 10 分钟缓冲。午餐在当前地点内，不另计交通。偏好慢走和展览，所有单次连续停留均不超过 120 分钟。",
        "## 二、第一天完整时间轴（2026-11-30 周一，晴雨相同）",
        itinerary_md(days["day1"]), days["day1"]["dinner"],
        "## 三、第二天晴天完整时间轴（2026-12-01 周二）",
        itinerary_md(days["day2_sunny"]), days["day2_sunny"]["dinner"],
        "## 四、第二天雨天完整时间轴（2026-12-01 周二）",
        data["rain_alternative"]["day1"] + "\n\n" + data["rain_alternative"]["day2"],
        itinerary_md(days["day2_rain"]), days["day2_rain"]["dinner"],
        "## 五、晴天预算", budget_md(data["budgets"]["晴天"], "晴天"),
        "## 六、雨天预算", budget_md(data["budgets"]["雨天"], "雨天"),
        "## 七、合并打包清单",
        md_table(["物品", "每人数量", "两人合计", "适用场景", "状态", "说明"],
                 [[x["item"], x["per_person_text"], x["quantity_text"], x["scenario"], x["status"], x["note"]]
                  for x in data["packing_list"]]),
        "## 八、待确认项", "\n".join(f"- {x}" for x in data["pending"]),
        "## 九、结构化核对与资料来源",
        "\n".join(f"- {x}" for x in data["validation"]),
        "- 完整结构化数据：outputs/data/旅行数据.json\n- 资料来源：inputs/旅行要求.md；inputs/地点资料.csv；inputs/打包清单-补充.csv",
    ]
    return "\n\n".join(sections) + "\n"


def html_table(headers: list[str], rows: list[list[object]], caption: str = "",
               widths: list[int] | None = None) -> str:
    """渲染表格；widths 为各列百分比宽度之和 100，用于 Word 端按内容分配列宽防挤压。"""
    cap = f"<caption>{escape(caption)}</caption>" if caption else ""
    if widths and len(widths) != len(headers):
        raise ValueError("列宽数量与表头数量不一致")
    style = lambda i: f' style="width:{widths[i]}%"' if widths else ""
    head = "".join(f'<th scope="col"{style(i)}>{escape(str(h))}</th>'
                    for i, h in enumerate(headers))
    body = []
    for row in rows:
        body.append("<tr>" + "".join(f"<td>{escape(str(v))}</td>" for v in row) + "</tr>")
    return f'<div class="table-wrap"><table>{cap}<thead><tr>{head}</tr></thead><tbody>{"".join(body)}</tbody></table></div>'


# 各表的列宽百分比：合计 100。Word 端表格总宽锁定为可打印宽度，
# 百分比决定列的分配，避免等分列把长文本列压成一条而裁切。
W_ITINERARY = [7, 8, 8, 18, 16, 15, 28]
W_BUDGET = [10, 20, 10, 11, 12, 11, 26]
W_SUMMARY = [22, 16, 62]
W_PACKING = [12, 12, 12, 16, 10, 38]


def itinerary_html(day: dict) -> str:
    return html_table(["编号", "开始", "结束", "安排", "交通", "缓冲", "核对与来源"],
                      [[s["id"], s["start"], s["end"], s["title"], s["transport"], s["buffer"], s["check"]]
                       for s in day["segments"]], f"{day['date']} {day['weekday']}｜{day['scenario']}",
                      W_ITINERARY)


def budget_html(budget: dict, scenario: str) -> str:
    rows = []
    for x in budget["items"]:
        amount = f"{x['amount']} 元" if x["amount"] is not None else "待确认（X，不计入）"
        price = "待确认" if x["unit_price"] is None else f"{x['unit_price']} 元"
        rows.append([x["category"], x["item"], f"{x['quantity']} {x['unit']}", price,
                     x["factor_label"], amount, x["source"]])
    parts = [html_table(["类别", "项目", "数量", "单价", "人数/间数", "金额", "来源"], rows,
                        f"{scenario}预算明细（2 人）", W_BUDGET)]
    parts.append(html_table(["指标", "数值", "复算口径"], [
        ["确定总额", f"{budget['known_total']} 元", budget["formula"]],
        ["确定金额人均", f"{budget['known_per_person']:.0f} 元/人", budget["per_person_formula"]],
        ["两人预算上限", f"{budget['cap']} 元", "旅行要求.md"],
        ["确定金额余量", f"{budget['remaining']} 元", f"{budget['cap']} − {budget['known_total']} = {budget['remaining']} 元"],
    ], f"{scenario}预算汇总", W_SUMMARY))
    if "optional_formula" in budget:
        parts.append(f'<p class="warning">&nbsp;&nbsp;{escape(budget["optional_formula"])}</p>')
    return "".join(parts)


CSS = r"""
:root {
  --ff-body: "Microsoft YaHei", "PingFang SC", sans-serif;
  --ff-heading: "SimHei", "Microsoft YaHei", sans-serif;
  --fs-body: 12pt;
  --fs-small: 10.5pt;
  --fs-title: 24pt;
  --fs-h1: 17pt;
  --fs-h2: 14pt;
  --fw-bold: 700;
  --fw-normal: 400;
  --lh-body: 1.65;
  --color-text: #1F2933;
  --color-muted: #52606D;
  --color-primary: #166534;
  --color-border: #B8C4BC;
  --color-bg: #FFFFFF;
  --color-soft: #F1F7F2;
  --color-header: #E2EFDA;
  --color-warning: #FFF4E5;
  --color-print: #000000;
  --spacing-page: 18px;
  --spacing-block: 14px;
  --spacing-title: 8px;
  --page-content-width: 20cm;
  --margin-page: 14mm;
  --table-width: 100%;
  --border-thin: 1px;
  --radius-none: 0;
}
* { box-sizing: border-box; }
html { background: var(--color-bg); }
body {
  max-width: var(--page-content-width);
  margin-left: auto;
  margin-right: auto;
  padding: var(--spacing-page);
  background: var(--color-bg);
  color: var(--color-text);
  font-family: var(--ff-body);
  font-size: var(--fs-body);
  line-height: var(--lh-body);
}
.doc-title {
  color: var(--color-primary); font-family: var(--ff-heading); font-size: var(--fs-title);
  font-weight: var(--fw-bold); text-align: center; text-indent: 0; margin: var(--spacing-block);
}
.subtitle { color: var(--color-muted); text-align: center; text-indent: 0; font-size: var(--fs-body); }
.notice { background: var(--color-soft); color: var(--color-text); text-indent: 0; padding: var(--spacing-page); }
h1 { color: var(--color-primary); font-family: var(--ff-heading); font-size: var(--fs-h1); font-weight: var(--fw-bold); }
h2 { color: var(--color-text); font-family: var(--ff-heading); font-size: var(--fs-h2); font-weight: var(--fw-bold); }
p { font-family: var(--ff-body); font-size: var(--fs-body); text-indent: 2em; line-height: var(--lh-body); }
li { font-family: var(--ff-body); font-size: var(--fs-body); color: var(--color-text); }
.warning { background: var(--color-warning); color: var(--color-text); padding: var(--spacing-page); }
.table-wrap {
  width: var(--table-width);
  max-width: 100%;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  margin-bottom: var(--spacing-block);
}
table {
  width: var(--table-width);
  min-width: 720px;  /* 窄屏下由 .table-wrap 横向滚动，避免 7 列表格挤成单字竖列 */
  border-collapse: collapse;
  color: var(--color-text);
  font-size: var(--fs-small);
}
caption { color: var(--color-primary); font-weight: var(--fw-bold); text-align: left; padding: var(--spacing-title); }
th { background: var(--color-header); color: var(--color-text); font-weight: var(--fw-bold); text-align: left; }
th, td { border: var(--border-thin) solid var(--color-border); padding: var(--spacing-title); vertical-align: top; }
td { color: var(--color-text); font-family: var(--ff-body); }
.source { color: var(--color-muted); font-size: var(--fs-small); text-indent: 0; }
@page { margin: var(--margin-page); @bottom-center { content: counter(page); } }
@media (max-width: 680px) {
  body { padding: var(--spacing-page); max-width: var(--table-width); }
  .table-wrap { overflow-x: auto; }
  table { table-layout: auto; }
  .doc-title { font-size: var(--fs-h1); }
}
@media print {
  html, body { background: var(--color-bg) !important; color: var(--color-print) !important; }
  body { max-width: var(--table-width); margin: 0; padding: 0; }
  * { animation: none !important; transition: none !important; box-shadow: none !important; }
  .table-wrap { overflow: visible !important; max-width: 100% !important; }
  table { display: table; width: var(--table-width) !important; min-width: 0 !important;
          color: var(--color-print) !important; table-layout: fixed; word-wrap: break-word; }
  th, td { background: var(--color-bg) !important; color: var(--color-print) !important;
           word-break: break-word; vertical-align: top; }
  tr, td { page-break-inside: avoid; }
  .notice, .warning { background: var(--color-bg) !important; color: var(--color-print) !important; }
  a { color: var(--color-print) !important; text-decoration: none; }
}
"""


def render_html(data: dict) -> str:
    m = data["meta"]
    days = {x["id"]: x for x in data["itinerary"]}
    packing_rows = [[x["item"], x["per_person_text"], x["quantity_text"], x["scenario"], x["status"], x["note"]]
                    for x in data["packing_list"]]
    pending = "".join(f"<li>{escape(x)}</li>" for x in data["pending"])
    checks = "".join(f"<li>{escape(x)}</li>" for x in data["validation"])
    parts = [
        '<p class="doc-title">虚构青禾市｜两天随身旅行手册</p>',
        f'<p class="subtitle">{m["label"]}｜2 位成人｜2026-11-30 周一至 2026-12-01 周二</p>',
        f'<p class="notice">{escape(m["disclaimer"])}</p>',
        '<h1>一、使用说明</h1>',
        '<p>每天 09:00 从酒店出发，18:00 前返回；每次公交 20 分钟后单列 10 分钟缓冲。午餐在当前地点内，不另计交通。偏好慢走和展览，所有单次连续停留均不超过 120 分钟。</p>',
        '<h1>二、第一天完整时间轴</h1><h2>2026-11-30 周一｜晴雨相同</h2>',
        itinerary_html(days["day1"]), f'<p>{escape(days["day1"]["dinner"])}</p>',
        '<h1>三、第二天晴天完整时间轴</h1><h2>2026-12-01 周二｜博物馆与公园</h2>',
        itinerary_html(days["day2_sunny"]), f'<p>{escape(days["day2_sunny"]["dinner"])}</p>',
        '<h1>四、第二天雨天完整时间轴</h1><h2>仅替换公园，其他安排不变</h2>',
        f'<p>{escape(data["rain_alternative"]["day1"])}</p><p>{escape(data["rain_alternative"]["day2"])}</p>',
        itinerary_html(days["day2_rain"]), f'<p>{escape(days["day2_rain"]["dinner"])}</p>',
        '<h1>五、晴天预算</h1>', budget_html(data["budgets"]["晴天"], "晴天"),
        '<h1>六、雨天预算</h1>', budget_html(data["budgets"]["雨天"], "雨天"),
        '<h1>七、合并打包清单</h1>',
        html_table(["物品", "每人数量", "两人合计", "适用场景", "状态", "说明"], packing_rows,
                   "晴雨合并结果（同名取每人最大数量，再按 2 人计算）", W_PACKING),
        '<h1>八、待确认项</h1>', f'<ul>{pending}</ul>',
        '<h1>九、结构化核对与资料来源</h1>', f'<ul>{checks}</ul>',
        '<p class="source">结构化数据：outputs/data/旅行数据.json。资料来源：inputs/旅行要求.md；inputs/地点资料.csv；inputs/打包清单-补充.csv。</p>',
    ]
    return "<!DOCTYPE html>\n<html lang=\"zh-CN\"><head><meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><meta name=\"docx-page-size\" content=\"A4\"><title>虚构青禾市两天随身旅行手册</title><style>" + CSS + "</style></head><body><section role=\"body\" data-page-restart=\"1\">" + "".join(parts) + '<p class="source">本页无动画、无暗色背景；打印样式强制白底黑字并取消滚动容器。</p></section></body></html>\n'


def write_supporting_sources(data: dict) -> None:
    sources = BUILD_DIR / "sources"
    location_rows = [[k, v["周一开放"], v["周二开放"], v["停留分钟"], v["门票每人元"], v["雨天可用"]]
                     for k, v in data["locations"].items()]
    digest = [
        "# 资料摘要（仅用于本次虚构练习）",
        "## inputs/旅行要求.md",
        "- 2 位成人；2026-11-30 周一、2026-12-01 周二；每天 09:00 出发，18:00 前回酒店。",
        "- 每次地点间移动 20 分钟，公交 2 元/人；交通后另加 10 分钟缓冲；单次连续停留最多 120 分钟。",
        "- 午餐 12:00-13:30 间至少 60 分钟，40 元/人/天；晚餐 50 元/人/天，回酒店后不计入日间路线。",
        "- 酒店一间一晚 240 元，早餐含于房价；两人总预算上限 1200 元。",
        "- 两天必须包含博物馆、艺术馆、老街；晴天安排公园，雨天以室内书店替代公园，其他安排不变。",
        "- 书店可选消费未知，不纳入确定金额；不得查询或混入真实城市信息。",
        "## inputs/地点资料.csv",
        md_table(["地点", "周一开放", "周二开放", "停留分钟", "门票每人元", "雨天可用"], location_rows),
        "## 资料缺口",
        "\n".join(f"- {x}" for x in data["pending"]),
    ]
    (sources / "materials_digest.md").write_text("\n\n".join(digest) + "\n", encoding="utf-8")
    amount_rows = []
    for scenario, budget in data["budgets"].items():
        for item in budget["items"]:
            if item["included"] and item["amount"] is not None:
                amount_rows.append({"场景": scenario, "项目": item["item"], "金额元": item["amount"]})
    (sources / "budget_amounts.json").write_text(json.dumps(amount_rows, ensure_ascii=False, indent=2), encoding="utf-8")
    calc_lines = ["# 计算与核对记录", ""]
    for scenario, budget in data["budgets"].items():
        calc_lines.extend([f"## {scenario}", f"- {budget['formula']}", f"- {budget['per_person_formula']}",
                           f"- 余量：{budget['cap']} − {budget['known_total']} = {budget['remaining']} 元"])
        if "optional_formula" in budget:
            calc_lines.append(f"- {budget['optional_formula']}")
    calc_lines.extend(["## 时间轴与营业核对", *[f"- {x}" for x in data["validation"]]])
    (sources / "calc_log.md").write_text("\n".join(calc_lines) + "\n", encoding="utf-8")


def main() -> None:
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    (BUILD_DIR / "stage1").mkdir(parents=True, exist_ok=True)
    (BUILD_DIR / "stage2").mkdir(parents=True, exist_ok=True)
    data = build_data()
    data_path = DATA_DIR / "旅行数据.json"
    data_path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    (DATA_DIR / "核对报告.json").write_text(json.dumps({"status": "pass", "checks": data["validation"]}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    (BUILD_DIR / "stage1" / "organized_draft.md").write_text(render_markdown(data), encoding="utf-8")
    (OUTPUTS / "雨天替代.md").write_text(render_markdown(data, rain_only=True), encoding="utf-8")
    html = render_html(data)
    (OUTPUTS / "旅行手册.html").write_text(html, encoding="utf-8")
    (BUILD_DIR / "stage2" / "formatted-青禾市两天随身旅行手册.html").write_text(html, encoding="utf-8")
    write_supporting_sources(data)
    print(json.dumps({"status": "success", "data": str(data_path), "html": str(OUTPUTS / "旅行手册.html"),
                      "rain": str(OUTPUTS / "雨天替代.md"), "checks": len(data["validation"])}, ensure_ascii=False))


if __name__ == "__main__":
    main()
