#!/usr/bin/env python3
"""一键重建 W07 全部成品（可移植版）。

产物全部由 outputs/data/旅行数据.json 这一份结构化数据派生：
  generate.py      → 旅行数据.json、雨天替代.md、旅行手册.html、stage2 HTML
  html-to-doc      → 行程.docx（由同一 stage2 HTML 转换，保证 Word 与网页同源）
  fix_docx_rows.py → 给所有表格行加 <w:cantSplit/>（防止换页处单元格内容被拆开）
  generate_budget.py → 预算.xlsx（openpyxl 保存时写 core properties）
  restore_cache.py → 回填公式缓存值（复用已重算副本，核对公式一致；不调用 recalc.py）

依赖（均不写死在本机路径，用环境变量或自动发现）：
  - Python 3.11+，标准库；openpyxl（生成与读取 xlsx）
  - WorkBuddy 插件 workbuddy-docx（提供 html-to-doc 转换脚本）

用法：
  python3 outputs/scripts/build_all.py
  DOCX_PLUGIN_DIR=/path/to/workbuddy-docx python3 outputs/scripts/build_all.py

不启动 headless 浏览器或 LibreOffice；不删除任何文件（含临时文件与首稿）。
"""
from __future__ import annotations

import os
import shutil
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
SCRIPTS = ROOT / "outputs" / "scripts"
REQUEST_ID = "70e5e81f-3eac-4ec3-8893-22f0f80d8c01"
STAGE_HTML = ROOT / "outputs" / "_build" / REQUEST_ID / "stage2" / "formatted-青禾市两天随身旅行手册.html"
DOCX = ROOT / "outputs" / "行程.docx"
XLSX = ROOT / "outputs" / "预算.xlsx"
REF = ROOT / "outputs" / ".预算.ref"


def find_plugin_dir(env_name: str, pattern: str, hint: str) -> Path | None:
    """按环境变量 → 插件缓存目录自动发现 → 常见安装位置 依次查找。"""
    explicit = os.environ.get(env_name, "").strip()
    if explicit:
        p = Path(explicit).expanduser()
        return p if p.is_dir() else None
    home = Path.home()
    candidates = sorted(home.glob(pattern), reverse=True)
    for c in candidates:
        if c.is_dir():
            return c
    return None


def find_script(plugin_dir: Path | None, *relative: str) -> Path | None:
    if plugin_dir is None:
        return None
    p = plugin_dir.joinpath(*relative)
    return p if p.is_file() else None


def run(args: list[str]) -> None:
    print("+", " ".join(str(a) for a in args), flush=True)
    subprocess.run([str(a) for a in args], cwd=ROOT, check=True)


def main() -> None:
    REF.mkdir(parents=True, exist_ok=True)
    run([sys.executable, SCRIPTS / "generate.py"])

    docx_plugin = find_plugin_dir("DOCX_PLUGIN_DIR", ".workbuddy/plugins/cache/workbuddy-builtin/workbuddy-docx/*", "workbuddy-docx")
    convert = find_script(docx_plugin, "skills/html-to-doc/scripts/convert_doc.py")
    if convert:
        run([sys.executable, convert, "--html", STAGE_HTML, "--output", DOCX, "--require-page-furniture"])
    else:
        print("[skip] 未找到 html-to-doc 转换脚本，跳过行程.docx 重建（设置 DOCX_PLUGIN_DIR 后可自动补齐）")

    # 转换后的文档再统一加 cantSplit：禁止表格行跨页断裂。
    run([sys.executable, SCRIPTS / "fix_docx_rows.py"])

    run([sys.executable, SCRIPTS / "generate_budget.py"])
    run([sys.executable, SCRIPTS / "restore_cache.py"])
    run([sys.executable, SCRIPTS / "validate_outputs.py"])


if __name__ == "__main__":
    main()
