"""Build six-chapter manuscript JSON, economic figures and complete S11 fragment.

No Word, network, Git, or physical model execution. All writes stay in this task.
"""
from __future__ import annotations
import copy
import csv
import hashlib
import json
import os
import re
from datetime import datetime, timezone
from pathlib import Path

HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[3]
REL = HERE.relative_to(ROOT).as_posix()
os.environ["MPLCONFIGDIR"] = str(HERE / ".local" / "matplotlib")
(HERE / ".local" / "matplotlib").mkdir(parents=True, exist_ok=True)


def sha(p):
    return hashlib.sha256(p.read_bytes()).hexdigest()


def dump(p, d):
    p.write_text(json.dumps(d, ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8")


def loadcsv(name):
    return list(csv.DictReader((HERE / "results" / name).open(encoding="utf-8-sig", newline="")))


def f(x):
    if x is None or x == "":
        return "—"
    if isinstance(x, bool):
        return "是" if x else "否"
    try:
        v = float(x)
        return f"{v:.2f}"
    except (ValueError, TypeError):
        return str(x)


def P(text):
    return {"type": "paragraph", "text": text}


def T(caption, columns, rows):
    return {"type": "table", "caption": caption, "columns": columns, "rows": rows}


def figures(results):
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    from matplotlib.font_manager import FontProperties
    font = FontProperties(fname=str(Path(os.environ["WINDIR"]) / "Fonts" / "msyh.ttc"))
    plt.rcParams.update({"font.family": font.get_name(), "axes.unicode_minus": False, "font.size": 10,
                         "axes.spines.top": False, "axes.spines.right": False, "savefig.facecolor": "white"})
    assets = HERE / "assets"
    assets.mkdir(exist_ok=True)
    vals = [x["qualified_km"] for x in results["capacity"]]
    fig, ax = plt.subplots(figsize=(7.2, 3.6), layout="constrained")
    bars = ax.bar(["常温氢 CG", "未来储氢 B", "参考换电 LI"], vals, color=["#346B9C", "#258772", "#7F8B99"], width=0.52)
    ax.set_ylabel("合格公里 / 单机八小时班次")
    ax.set_ylim(0, max(vals) * 1.2)
    ax.set_title("相同工作窗口下的有效作业产出")
    ax.bar_label(bars, labels=[f(x) for x in vals], padding=4)
    ax.grid(axis="y", alpha=0.16)
    ax.set_axisbelow(True)
    fig.savefig(assets / "shift-capacity.png", dpi=190)
    fig.savefig(assets / "shift-capacity.svg")
    plt.close(fig)
    rows = results["five_year_summary"]
    names = ["保守", "基准", "加速"]
    fig, axes = plt.subplots(1, 2, figsize=(8, 3.55), layout="constrained")
    for ax, key, title in [(axes[0], "service_revenue_cny", "五年服务收入"), (axes[1], "operator_economic_profit_cny", "五年运营收益")]:
        y = [s[key] / 10000 for s in rows]
        colors = ["#346B9C" if v >= 0 else "#B8584C" for v in y]
        bars = ax.bar(names, y, color=colors, width=0.52)
        ax.axhline(0, color="#6D7580", linewidth=0.7)
        ax.set_ylabel("万元（2026年不变价）")
        ax.set_title(title)
        ax.margins(y=0.2)
        ax.bar_label(bars, labels=[f(v) for v in y], padding=3, fontsize=9)
        ax.grid(axis="y", alpha=0.15)
        ax.set_axisbelow(True)
    fig.savefig(assets / "five-year-scenarios.png", dpi=190)
    fig.savefig(assets / "five-year-scenarios.svg")
    plt.close(fig)


def parse_markdown(text):
    lines = text.splitlines()
    doc = {"schema_version": 1, "document_kind": "main", "academic_hierarchy": True,
           "title": lines[0].removeprefix("# "), "abstract": "", "keywords": [],
           "sections": [], "references": [], "supporting_materials": [], "acknowledgments": "",
           "appendices": [], "ready_for_final_Word_layout": False}
    i, current, mode = 1, None, None
    while i < len(lines):
        line = lines[i].strip()
        if not line:
            i += 1
            continue
        if line == "## 摘要":
            mode, i = "abstract", i + 1
            continue
        if line.startswith("关键词："):
            doc["keywords"] = [x.strip() for x in line.removeprefix("关键词：").split("；")]
            mode, i = None, i + 1
            continue
        if line == "## 支撑材料":
            mode, i = "support", i + 1
            continue
        if re.match(r"## \d+ ", line):
            current = {"heading": line[3:], "level": 1, "blocks": []}
            doc["sections"].append(current)
            mode, i = "section", i + 1
            continue
        if line.startswith("### "):
            current["blocks"].append({"type": "heading", "level": 2, "text": line[4:]})
            i += 1
            continue
        if line == "$$":
            j = i + 1
            while j < len(lines) and lines[j].strip() != "$$":
                j += 1
            eq = "\n".join(lines[i + 1:j])
            number = re.search(r"\\tag\{([^}]+)\}", eq)
            current["blocks"].append({"type": "equation", "latex": re.sub(r"\\tag\{[^}]+\}", "", eq), "number": number.group(1) if number else ""})
            i = j + 1
            continue
        image = re.match(r"!\[([^]]+)\]\(([^)]+)\)", line)
        if image:
            caption, path = image.groups()
            number = re.search(r"图(\d+-\d+)", caption)
            current["blocks"].append({"type": "figure", "path": REL + "/" + path,
                                      "number": number.group(1), "caption": caption})
            i += 1
            continue
        if line.startswith("表") and i + 2 < len(lines) and lines[i + 2].startswith("|"):
            caption, i = line, i + 2
            cols = [x.strip() for x in lines[i].strip().strip("|").split("|")]
            i += 2
            rows = []
            while i < len(lines) and lines[i].strip().startswith("|"):
                rows.append([x.strip() for x in lines[i].strip().strip("|").split("|")])
                i += 1
            current["blocks"].append(T(caption, cols, rows))
            continue
        j = i + 1
        while j < len(lines) and lines[j].strip() and not lines[j].startswith("##"):
            j += 1
        paragraph = "\n".join(lines[i:j])
        if mode == "abstract":
            doc["abstract"] += paragraph
        elif mode == "support":
            doc["supporting_materials"].append(paragraph)
        elif current is not None:
            current["blocks"].append(P(paragraph))
        i = j
    return doc


def strings(data):
    if isinstance(data, str):
        yield data
    elif isinstance(data, dict):
        for key in ["heading", "text", "caption", "columns", "rows", "blocks"]:
            if key in data:
                yield from strings(data[key])
    elif isinstance(data, list):
        for value in data:
            yield from strings(value)


def param_display(row):
    val, unit = float(row["value"]) if row["value"] not in ["True", "False"] else row["value"], row["unit"]
    path = row["path"]
    if isinstance(val, str):
        return ("是" if val == "True" else "否"), "布尔"
    if "grid_kg_co2_kwh" in path:
        return f(val * 1000), "gCO₂/kWh"
    if unit == "kWh" and 0 < val < 1:
        return f(val * 1000), "Wh"
    if unit == "h" and 0 < val < 1:
        return f(val * 60), "min"
    if unit.startswith("kg") and 0 < val < 1 and "co2" not in unit.lower():
        return f(val * 1000), unit.replace("kg", "g", 1)
    if unit in ["fraction", "ratio"] or any(x in path for x in ["fraction", "share_new_sites", "discount_rate", "charging_efficiency"]):
        return f(val * 100), "%"
    return f(val), unit


def build_supplement(doc, references, source_db, results):
    sections = []

    def section(anchor, title, blocks):
        for i, block in enumerate(blocks):
            block["stable_id"] = anchor.replace(".", "_") + "_B" + str(i + 1).zfill(3)
        sections.append({"anchor": anchor, "stable_id": "R4_" + anchor.replace(".", "_"), "heading": title,
                         "reference_namespace": "R4", "blocks": blocks})

    refmap = {r["source_id"]: r["id"] for r in references}
    section("S11.1", "S11.1 来源场景与采用边界", [
        P("本节为商业与应用支撑。公开案例说明需求、工具和运行条件；数值成本、规划站点和采用率按经济假设登记。完整引文、实际读取层级和适用边界分别列明。"),
        T("表S11-01 本篇完整来源及实际读取层级", ["R4引用", "source_id", "完整文献", "核查位置/层级", "支持范围及限制"],
          [[str(refmap.get(s["source_id"], "附件专用")), s["source_id"], s["full_citation"], str(s["checked_location"]).replace("0.5306kgCO2/kWh", "530.60gCO₂/kWh") + "；" + str(s["retrieval_status"]), str(s["supports"]).replace("0.5264kWh", "526.40Wh") + "；不支持：" + str(s["does_not_support"])] for s in source_db]),
        T("表S11-02 场景、客户和替代工具矩阵", ["任务", "使用/付款/受益", "指标与基准", "替代工具与组织", "来源/身份"], SCENE_ROWS)
    ])
    params = loadcsv("parameters.csv")
    narrative = list(csv.DictReader((HERE / "narrative-parameters.csv").open(encoding="utf-8-sig")))
    displayed_params = []
    for row in params:
        value, unit = param_display(row)
        displayed_params.append([row["parameter_id"], row["path"], value, unit, row["identity"], row["source"]])
    for row in narrative:
        displayed_params.append([row["parameter_id"], row["definition"], f(row["value"]), row["unit"], row["identity"], row["source"] + "；" + row["scope"]])
    section("S11.2", "S11.2 全部经济参数单位与身份", [
        P("机器原精度保留在economic-inputs.json与results/parameters.csv；下表为176项模型输入及1项人口摊分假设的完整可读显示。小量用分钟、Wh、g等换单位，源值不改。年度站点数为规划等效值，可包含期望采用份额。正价、零纳入和未知各有身份，不以0代替未知。"),
        T("表S11-03 全部经济输入", ["parameter_id", "定义/JSON路径", "显示值", "单位", "身份", "来源与条件"], displayed_params),
        P("FC1000h借保修尺度作更换预算而非实测报废；2000次启停为作者假设。LI厂商cycles按每架次一次充电循环记账，不等于FEC。高电量长期存放按正确存储管理避免，若发生须提前执行厂家规则。缓冲电池500EFC/2年同样是假设，未套用单体论文的老化数值。")
    ])
    inherited = json.loads((HERE / "inherited-inputs.json").read_text(encoding="utf-8"))
    phy_rows = []
    for key in ["CG", "B", "A"]:
        s = inherited["adopted_values"][key]
        phy_rows.append([key, f(s["work_s"] / 3600), f(s["flight_s"] / 3600), f(s["H2_FC_used_kg"] * 1000), f(s["H2_final_kg"] * 1000), f(s["SOC_final"] * 100), "R23-HE2.1.0已验原任务"])
    section("S11.3", "S11.3 技术继承寿命与换装运营", [
        T("表S11-04 重复作业科学输入原值的单位换算", ["方案", "有效作业/h", "飞行/h", "FC用氢/g", "末氢/g", "末SOC/%", "身份"], phy_rows),
        P("B9.22h属于5m/s重复作业，不用于外推20m/s的218.40km。配送采用常温range原任务的平均燃料账本与固定阶段时间做经济近似，不解动力方程；实际路线需试点。A只作辅助物理解释，不参与B销售情景。原铝壳35MPa负收益、SOC/功率失败与低压LH₂/5MPa研究路线仍见R3原表5-2、S09，未被B假设覆盖。"),
        T("表S11-05 同服务排班与资源", ["服务/工具", "在用机", "架次/次服务", "飞行h/次", "墙钟h/次", "人员h/次", "接续"],
          [[k, f(v["schedule"]["active_aircraft"]), f(v["schedule"]["sorties"]), f(v["schedule"]["flight_h"]), f(v["schedule"]["wall_h"]), f(v["schedule"]["staff_person_h"]), "需双机连续交接" if v["schedule"].get("continuous_handover_required") else "不要求双机交接"] for k,v in results["cases"].items()]),
        P("CG/B每在用机2只备瓶，另分摊25%共享备机上的主瓶，合3.25只/在用机等效。公共CG两架在用机相应6.50只。B库存可随少换装再优化；当前固定库存不构成9.22h物理条件。换瓶检查、换电检查、离线补能与机队交接分开；充电不强制计为飞机落地等待。"),
        P("能源系统比能定义为可交付净电量/完整能源装机质量，厂商的氢本体热值、模块功率密度、目录系统比能和电池包比能分开。正文仅用完整同质量/任务结果与服务成本评价；TB65263.2Wh/1.35kg约194.96Wh/kg为包级参照，1kg载荷45min仍为运营假设。")
    ])
    costrows, assetrows = [], []
    for key, c in results["cases"].items():
        for name, value in c["cost_parts_cny_year"].items():
            costrows.append([key, name, f(value), "CNY/year", "包含在总成本一次"])
    for row in loadcsv("lifecycle-assets.csv"):
        times = json.loads(row["replacement_years"])
        assetrows.append([row["case"], row["asset"], f(row["price_cny"]), f(row["quantity"]), f(row["life_years"]), "；".join(f(t) for t in times) or "评价期内无", f(row["residual_cny"]), f(row["annual_equivalent_cny"])])
    unitrows = [[k, f(c["annual_attempts"]), f(c["successful_units_year"]), c["unit"], f(c["annual_cost_cny"]), f(c["cost_cny_successful_unit"]), f(c["annual_revenue_cny"]), f(c["annual_economic_profit_cny"])] for k,c in results["cases"].items()]
    section("S11.4", "S11.4 九个单位任务与生命周期成本", [
        P("公式：PV资产=初购+各次更换折现−期末剩余使用价值折现；等额年资产成本=PV资产/五年年金现值因子。完整年成本=资产年成本+人员+值守+能源+维护+保险+管理通信；单位成本=完整年成本/成功且合格产出。每类初购已含堆/电池/气瓶，寿命更换只在资产现金事件中计一次。备机按池化均匀轮用分摊磨损，期末残值是未消耗服务能力的线性假设，不是已有回购合同。"),
        T("表S11-06 九个服务算例", ["算例", "年尝试", "年合格产出", "单位", "年成本/元", "单位成本/元", "年收入/元", "年收益/元"], unitrows),
        T("表S11-07 完整年成本分项", ["算例", "分项", "年金额", "单位", "包含关系"], costrows),
        T("表S11-08 全部资产、寿命与更换", ["算例", "资产", "单价/元", "数量", "预算寿命/年", "更换年点", "期末残值/元", "等额年成本/元"], assetrows),
        P("配送路线：1kg，空中单程40km；CG巡航72km/h，阶段时间沿range任务取265s空中及90s地面启动；送达/返程按调度估计。ROAD单程80km、40km/h；VTOL用90km/h和0.10h固定阶段假设、1.20kWh/架次。参考VTOL厂家最大航程与载荷并非同工况实测，本表不构成其具体型号的性能或报价承诺。价格假设同列比较，地面组批结果另见S11.6。"),
        P("公共保障为限定窗口每组600h/年的值守，并非全天全年。每年20次任务、40h训练；每组2人。3h连续任务需要交接时，CG/LI在用机为2，B为1；人员减半情景已另算。风险判断相对9万元现有地面巡查预算，属于新增预警服务的价值阈值，不冒称原地面手段能提供同样空中连续画面。")
    ])
    annual = loadcsv("five-year-annual.csv")
    section("S11.5", "S11.5 五年三情景完整年度账", [
        P("200候选站点按观测50%、配送30%、公共20%分组。新站年中部署，当年按0.50站年运营；既有站按1站年。新增B先进入公共连续任务，再进入观测，不用于配送航程外推。B采用份额针对当年新增站点；跨年累计分别保留。初装装备销售为资产采购，另列服务收入；现金OPEX不再扣资产年金，实际更换现金按cohort事件计，终期残值独立显示。未来规模、价格、寿命、利用率均为情景假设。"),
        T("表S11-09 各年度采用与任务量", ["情景/年", "年末站", "新增站", "新增B站", "有效站年", "观测合格km", "成功配送单", "公共响应"],
          [[r["scenario"]+"/"+r["year"], f(r["sites_eoy"]), f(r["new_sites"]), f(r["new_B_sites"]), f(r["active_site_years"]), f(r["observation_qualified_km"]), f(r["delivered_orders"]), f(r["public_responses"])] for r in annual]),
        T("表S11-10 年度收入、完整成本和资源节约，万元", ["情景/年", "初装销售", "服务收入", "等额年成本", "运营收益", "净资源节约"],
          [[r["scenario"]+"/"+r["year"]]+[f(float(r[k])/10000) for k in ["initial_equipment_sales_cny","service_revenue_cny","annual_equivalent_cost_cny","operator_economic_profit_cny","net_resource_gain_vs_alternative_cny"]] for r in annual]),
        T("表S11-11 cohort现金流，万元", ["情景/年", "现金OPEX", "更换现金", "未含残值净现金", "期末残值", "折现净现金"],
          [[r["scenario"]+"/"+r["year"]]+[f(float(r[k])/10000) for k in ["cash_opex_cny","replacement_cash_cny","operator_cash_before_salvage_cny","salvage_cny","discounted_operator_cash_cny"]] for r in annual]),
        T("表S11-12 先进瓶年度增量，万元", ["情景/年", "B有效站年", "瓶溢价收入", "间接资源节约", "运营增量"],
          [[r["scenario"]+"/"+r["year"],f(r["B_active_site_years"])]+[f(float(r[k])/10000) for k in ["B_direct_vessel_premium_sales_cny","B_indirect_resource_increment_cny","B_operator_increment_cny"]] for r in annual]),
        T("表S11-13 先进瓶供应商现金账，万元", ["情景/年", "溢价收入", "增量毛利", "研发支持", "初始研发", "净现金"],
          [[r["scenario"]+"/"+r["year"]]+[f(float(r[k])/10000) for k in ["incremental_vessel_sales_cny","supplier_incremental_margin_cny","RnD_support_cny","RnD_initial_cny","supplier_incremental_cash_cny"]] for r in loadcsv("advanced-supplier.csv")])
    ])
    sensitivity = loadcsv("sensitivity.csv")
    envrows = [[k, f(c["annual_H2_kg"]), f(c["annual_grid_kwh"]), f(c["annual_external_ground_conditioning_kwh"]), f(c["energy_chain_co2_kg_year"]), f(c["renewable_supply_scenario_co2_kg_year"])] for k,c in results["cases"].items()]
    section("S11.6", "S11.6 敏感性环境与不重复价值账", [
        P("单因素敏感性使用相同调度和会计边界，改变价格、寿命、利用率或组织条件；无新物理求解。空格/横线表示该行不适用该指标，不等于零。道路组批保持原年送达需求，实际车次减少，固定资产年成本仍保留；不是把全部成本直接除以货物数。"),
        T("表S11-14 全部敏感性算例", ["参数", "值", "CG观测元/km", "LI观测元/km", "B观测元/km", "CG配送元/单", "B−CG公共年成本/元", "组批陆运元/单"],
          [[r["parameter"],f(r["value"]),f(r.get("CG_observation_cny_km")),f(r.get("LI_observation_cny_km")),f(r.get("B_observation_cny_km")),f(r.get("CG_delivery_cny_order")),f(r.get("B_minus_CG_public_annual_cost_cny")),f(r.get("road_cny_order"))] for r in sensitivity]),
        T("表S11-15 环境能源链筛查", ["算例", "年到站氢/kg", "年本地电/kWh", "供应商调质电/kWh", "参考供氢排放/kg", "低碳供应情景/kg"], envrows),
        P("环境假设：常温供氢12kgCO₂e/kg，低碳供氢3kgCO₂e/kg；B另加11kWh/kg地面调质参考量，普通电力用530.60gCO₂/kWh，低碳调质用50.00g/kWh假设。11kWh/kg取SG09特定液化规模作为敏感性尺度，非B工艺实测或机载电耗。调质电费已经包含到站B氢价，不二次计费，碳项只加一次。制造、设施和非CO₂电力排放未完整纳入，不能称全面LCA。"),
        T("表S11-16 价值口径与去重", ["账目", "受益方", "计量", "不重复相加对象", "原因"], [[r["account"],r["beneficiary"],r["measure"],r["do_not_add_to"],r["reason"]] for r in loadcsv("value-ledger.csv")]),
        P("风险式V=λLΔp。例：λ=0.50次/年，L=100万元资产停运/抢险损失，Δp=15.00%，期望避免7.50万元/年。以9万元原地面预算为基线，CG/B新增服务阈值分别39.32%/20.25%；这些事件及降损率为假设，不计医疗死亡价值，不进收入/五年总量。人口1万人只用于第6章公共年成本摊分，不影响经济模型。")
    ])
    website_path = ROOT / "reports/09_reviews/WEBSITE-TEST-001/cases.json"
    website = json.loads(website_path.read_text(encoding="utf-8-sig"))
    wr = []
    for ci, c in enumerate(website["cases"]):
        wr.append([c["id"], c.get("title", "").replace("装氢0.284→0.20kg", "装氢284.00g→200.00g"), "已实际执行" if c.get("executed") else "未执行", "cases.json#/cases/" + str(ci) + "/observed", "；".join(c.get("evidence", [])[:3])])
    section("S11.7", "S11.7 真实网站体验与复现导航", [
        P("采用独立测试者2026-11-11的19个真实UI案例；R4未冒称执行该浏览器任务。线上原生备份自报sourceCommit ed1bfcabff188fba97b39a8724c88c2d2d312558、release2c5063b1093947397742393ba39b06313a961748c6199c2e780b01185b41464e，与报告源基线e7d2a09及历史网站快照7d3d58分别记录。下表路径相对reports/09_reviews/WEBSITE-TEST-001/；完整输入、输出和图像以该目录原件为准。"),
        T("表S11-17 网站实际案例导航", ["案例", "任务", "执行", "实际观察指针", "原证据"], wr),
        P("R23同21字段M1得到212.74min/1268.23W；这不是完整任务。M3另用100Wh、FC净情景2400W、800W充电等默认补充量，在37.50s因surplus_unhandled停止，保留失败；不能拿它与218.40km判断误差。四项改进为网格说明、公式源码阅读、量名提示和拒绝步功率诊断。成功功能、失败和未测均保留：付费模型、真手机、成本/M4和实飞未测。无真实客户访谈、支付意愿或节省工时测量。"),
        P("经济复现：先python -B reports/06_reports/04_business_plan/BUSINESS-R4-001/model.py，再运行同目录collect_sources.py和build_publication.py。前者标准库运算，后者仅使用已安装matplotlib生成经济图；不会运行MATLAB或Word。输入/输出哈希和随机种子不适用说明见run-receipt.json；内容检查见publication-checks.json；既有292项独立经济检查见reports/09_reviews/BUSINESS-R4-001-economic-review/。")
    ])
    resource_index = []
    for p in sorted(HERE.rglob("*")):
        if p.is_file() and ".local" not in p.parts and p.name not in ["supplement-fragment.json", "worker.json", "publication-checks.json", "migration.json", "reference-map.json"]:
            resource_index.append({"anchor": "S11.7", "report_owner": "R4", "repo_relative_path": p.relative_to(ROOT).as_posix(), "sha256": sha(p), "byte_count": p.stat().st_size, "evidence_role": "R4 economic/publication source or result;not new physics"})
    original = [{"id": r["id"], "source_id": r["source_id"], "full_citation": r["full_citation"], "publication_type": next(s["identity"] for s in source_db if s["source_id"] == r["source_id"])} for r in references]
    return {"schema_version": 1, "document_kind": "supplement_fragment", "report_owner": "R4", "reference_namespace": "R4", "version": "R4-BUSINESS-1.0.0",
            "sections": sections, "source_master": REL + "/main-content.json", "source_master_sha256": sha(HERE / "main-content.json"),
            "original_datasets": [{"repo_relative_path": path, "sha256": results_hash} for path,results_hash in json.loads((HERE / "run-receipt.json").read_text(encoding="utf-8"))["input_hashes"].items() if path.startswith("reports/")],
            "resource_index": resource_index, "original_reference_registry": original,
            "reference_namespace_registry": {"R4-BUSINESS-1.0.0": {"source_file": REL + "/main-content.json", "references": original}},
            "supplement_parameters": params + narrative, "primary_merge_owner": "supervisor",
            "deduplication_rule": "New R4 parameter IDs and source namespace;shared physics stays authoritative in S02/S03/S07/S09,no overwritten source blocks",
            "numbering_rule": "Stable S11.1–S11.7;S11_TAB_01–17;supervisor assigns global SREF IDs", "ready_for_supervisor_merge": True,
            "already_merged_into_shared_supplement": False, "publication_display_policy": "At most two decimals;raw precision retained in machine files"}


SCENE_ROWS = [
    ["电网/管线巡检", "业主和运营商使用并付费；沿线居民受益", "合格公里、异常定位、复核时间", "换电机巢成熟；固定/复合翼适合长廊道；地面近看灵活；氢关注连续和少返场", "R1；SG01；本篇作业率是假设"],
    ["测绘/生态和灾害成像", "测绘与管理单位付费；土地/生态管理受益", "合格公顷、精度、图像连续", "固定翼适合大范围；多旋翼适合局部悬停；固定监测适合长期同点", "R1；R2定位边界；传感器/作业率待任务勘验"],
    ["偏远邮政/单件备件", "邮政/物流运营商付费，偏远居民受益", "成功送达、时窗、货重、每单成本", "地面可组批低单价；垂起固定翼具现实航线经验；1kg氢平台只覆盖轻量任务", "SG02；Wingcopter；40km为经济例"],
    ["样本和药品配送", "卫生网络/医院付费，患者和基层机构受益", "时效、温控、成功交付和库存损失", "道路网络灵活、可批量；无人机跨水绕山；航空药械温控另需配置", "Nisingizwe2022；非本项目医疗效果"],
    ["极地/冰川观察", "科研机构/公共项目采购", "连续影像、可达性、减少人员暴露", "已有固定翼科学平台与电池近程多旋翼；氢需低温系统适配", "Jordan2025；SG04环境条件"],
    ["高海拔冰瀑补给", "登山/救援及保障运营方付费，人员受益", "安全送达、载重、跨越次数", "FlyCart电池试验已有；人力和直升机有不同保障；本机1kg不扩成15kg", "SG03；5300–6000m他平台实验"],
    ["应急快速冷启动", "应急/救援单位采购", "待命到起飞时间、启动成功率", "预热电池或保温设施与氢堆预热均需对比", "SG04启动5–40°C；研发任务"],
    ["电力抢修/灾害中继", "电网/公共保障预算", "三小时连续在岗、响应和覆盖人口", "地面人员、固定设施、双机换电；B减少接续资源为目标情景", "SG01、R2/R3；本篇连续服务假设"],
]


def run():
    raw_path = HERE / "manuscript-source.md"
    if not raw_path.exists():
        raw_path.write_bytes((HERE / "main.md").read_bytes())
    raw = raw_path.read_text(encoding="utf-8")
    source_db = json.loads((HERE / "sources.json").read_text(encoding="utf-8"))["sources"]
    source_map = {s["source_id"]: s for s in source_db}
    order = list(dict.fromkeys(re.findall(r"\[@([A-Z0-9_-]+)\]", raw)))
    assert all(s in source_map for s in order)
    references = [{"id": i + 1, "source_id": sid, "full_citation": source_map[sid]["full_citation"]} for i,sid in enumerate(order)]
    mapping = {r["source_id"]: r["id"] for r in references}
    text = re.sub(r"\[@([A-Z0-9_-]+)\]", lambda m: "[" + str(mapping[m.group(1)]) + "]", raw)
    doc = parse_markdown(text)
    doc["references"] = references
    assert len(doc["sections"]) == 6
    assert all(any(b["type"] == "heading" and b["level"] == 2 for b in s["blocks"]) for s in doc["sections"])
    doc["ready_for_final_Word_layout"] = True
    doc["task_id"] = "BUSINESS-R4-001"
    doc["content_version"] = "R4-BUSINESS-1.0.0"
    doc["model_version"] = "R4-ECON-1.0.0"
    doc["content_only_readiness"] = "Complete content;common Word layout,signatures,acknowledgments,page QA and final peer review remain with supervisor"
    dump(HERE / "main-content.json", doc)
    bibliography = "\n\n## 参考文献\n\n" + "\n\n".join("[" + str(r["id"]) + "] " + r["full_citation"] for r in references) + "\n"
    (HERE / "main.md").write_text(text.rstrip() + bibliography, encoding="utf-8")
    dump(HERE / "references.json", references)
    (HERE / "references.md").write_text("# 本篇完整参考文献\n\n" + "\n\n".join("["+str(r["id"])+"] "+r["full_citation"] for r in references) + "\n", encoding="utf-8")
    results = json.loads((HERE / "results/results.json").read_text(encoding="utf-8"))
    figures(results)
    dump(HERE / "supplement-fragment.json", build_supplement(doc, references, source_db, results))
    with (HERE / "scenario-matrix.csv").open("w", newline="", encoding="utf-8-sig") as w:
        writer = csv.writer(w)
        writer.writerow(["task", "user_payer_beneficiary", "service_metric", "alternatives_and_tradeoff", "source_and_identity"])
        writer.writerows(SCENE_ROWS)
    parameter_count = len(loadcsv("parameters.csv")) + 1
    citation_locs = {}
    for si, s in enumerate(doc["sections"]):
        for bi, b in enumerate(s["blocks"]):
            for txt in strings(b):
                for ref in re.findall(r"\[(\d+)\]", txt):
                    citation_locs.setdefault(int(ref), []).append(f"/sections/{si}/blocks/{bi}")
    ref_map = {"version": "R4-BUSINESS-1.0.0", "original_namespace": "R4", "main_reference_count": len(references),
               "ordering": "first appearance in main manuscript", "main_source_sha256": sha(HERE / "main-content.json"),
               "SREF_assignment": "pending supervisor merge;no invented global IDs", "references": []}
    for r in references:
        ref_map["references"].append({"report_id": "R4", "old_ref_id": None, "source_id": r["source_id"], "new_ref_id": r["id"],
                                      "SREF_id": None, "SREF_key": "R4::" + r["source_id"], "DOI_or_source_id": source_map[r["source_id"]].get("doi") or r["source_id"],
                                      "status": "new_main_and_S11_source", "main_pointers": list(dict.fromkeys(citation_locs.get(r["id"], []))), "supplement_anchors": ["S11.1"]})
    dump(HERE / "reference-map.json", ref_map)
    migrations = []
    for si, section in enumerate(doc["sections"]):
        for bi, block in enumerate(section["blocks"]):
            migrations.append({"source_file": REL + "/manuscript-source.md", "source_role": "new_R4_authored_business_content",
                               "action": "new_main_argument_with_support_in_S11", "destination": f"/sections/{si}/blocks/{bi}", "type": block["type"],
                               "stable_id": "R4_MAIN_" + str(si+1) + "_" + str(bi+1).zfill(3),
                               "supplement_anchors": ["S11.1", "S11.2"] if si < 2 else ["S11.3", "S11.4"] if si < 4 else ["S11.5", "S11.6", "S11.7"],
                               "block_sha256": hashlib.sha256(json.dumps(block,ensure_ascii=False,sort_keys=True,separators=(",", ":")).encode()).hexdigest()})
    dump(HERE / "migration.json", {"version": "R4-BUSINESS-1.0.0", "new_authoring": True, "historical_PREP_unchanged": True,
                                   "source_master_sha256": sha(raw_path), "current_main_sha256": sha(HERE / "main-content.json"),
                                   "source_block_count": len(migrations), "all_source_blocks_accounted_for": True,
                                   "migrations": migrations, "long_material_locations": {"full_sources": "S11.1", "all_economic_parameters": "S11.2", "mission_life_turnaround": "S11.3", "full_assets_and_costs": "S11.4", "all_annual_scenarios": "S11.5", "sensitivity_and_value_ledger": "S11.6", "website_and_reproduction": "S11.7"},
                                   "unchanged_scientific_inputs": json.loads((HERE / "inherited-inputs.json").read_text(encoding="utf-8"))["source_hashes"]})
    manifest_paths = list(json.loads((HERE / "run-receipt.json").read_text(encoding="utf-8"))["input_hashes"])
    manifest_paths = [p if p.startswith("reports/") else REL + "/" + p for p in manifest_paths]
    manifest_paths += [".agent-team/inputs/BUSINESS-R4-001/spec.md", ".agent-team/inputs/BUSINESS-R4-001/knowledge.md", "reports/NORTH-STAR.md",
                       "reports/09_reviews/BUSINESS-R4-001-source-guide/source-guide.md", "reports/09_reviews/BUSINESS-R4-001-source-guide/sources.json",
                       "reports/09_reviews/WEBSITE-TEST-001/report.md", "reports/09_reviews/WEBSITE-TEST-001/cases.json",
                       "reports/09_reviews/BUSINESS-R4-001-economic-review/review.json"]
    dump(HERE / "input-manifest.json", {"task_id": "BUSINESS-R4-001", "base_commit": "e7d2a09dc3fda8f44f522e0ba0a7d3c3c45e5cf0", "accepted_knowledge": "v7", "north_star_version": "1.0.0",
                                        "inputs": [{"repo_relative_path": p, "sha256": sha(ROOT/p), "byte_count": (ROOT/p).stat().st_size, "read_only": True} for p in dict.fromkeys(manifest_paths)]})
    checks = [{"check": "six_chapters", "pass": len(doc["sections"]) == 6}, {"check": "academic_hierarchy", "pass": doc["academic_hierarchy"]},
              {"check": "no_main_appendices", "pass": doc["appendices"] == []}, {"check": "all_26_cited_sources_exist", "pass": len(references) == len(source_db)},
              {"check": "all_references_cited", "pass": all(citation_locs.get(r["id"]) for r in references)},
              {"check": "figures_exist", "pass": all((ROOT/b["path"]).is_file() for s in doc["sections"] for b in s["blocks"] if b["type"]=="figure")},
              {"check": "economic_model_checks", "pass": json.loads((HERE/"results/checks.json").read_text(encoding="utf-8"))["status"] == "passed"},
              {"check": "website_real_cases_19", "pass": len(json.loads((ROOT/"reports/09_reviews/WEBSITE-TEST-001/cases.json").read_text(encoding="utf-8-sig"))["cases"]) == 19},
              {"check": "no_unresolved_citation_tokens", "pass": "[@" not in (HERE/"main.md").read_text(encoding="utf-8")},
              {"check": "no_windows_absolute_paths_in_publication", "pass": not re.search(r"(?<![A-Za-z0-9])[A-Za-z]:[\\/]", (HERE/"main.md").read_text(encoding="utf-8"))}]
    assert all(x["pass"] for x in checks), checks
    receipt = {"task_id": "BUSINESS-R4-001", "executed_utc": datetime.now(timezone.utc).isoformat(), "status": "passed", "checks": checks,
               "counts": {"chapters": 6, "subsections": sum(b["type"]=="heading" for s in doc["sections"] for b in s["blocks"]), "main_blocks": len(migrations), "references": len(references),
                          "figures": 2, "economic_cases": 9, "scenario_years": 15, "economic_parameters_including_narrative": parameter_count, "S11_sections": 7},
               "not_done": ["Word export","common template/signature/acknowledgment layout","all-page Word QA","final independent nonauthor peer review"],
               "independent_economic_review": "reports/09_reviews/BUSINESS-R4-001-economic-review/review.json", "figure_visual_inspection": "pending actual image inspection"}
    dump(HERE / "publication-checks.json", receipt)
    print(json.dumps({"status":"content_and_S11_written","counts":receipt["counts"],"check_count":len(checks)},ensure_ascii=True))


if __name__ == "__main__":
    run()
