#!/usr/bin/env python3
"""Build the canonical one-project-one-picture selection table."""

from __future__ import annotations

import csv
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "data"


def read_csv(name: str) -> list[dict[str, str]]:
    with (DATA / name).open(encoding="utf-8-sig", newline="") as handle:
        return list(csv.DictReader(handle))


def text(value: str | None) -> str:
    return (value or "").strip()


def main() -> None:
    projects = read_csv("project-case-base.csv")
    p1 = {row["项目ID"]: row for row in read_csv("photo-evidence-P001-P009.csv")}
    p2 = {row["project_id"]: row for row in read_csv("photo-evidence-P010-P019.csv")}
    late_rows = read_csv("photo-evidence-P020-P028.csv")
    late: dict[str, list[dict[str, str]]] = {}
    for row in late_rows:
        late.setdefault(row["project_id"], []).append(row)

    overall = {
        "P001": ("C", "否"), "P002": ("C", "否"), "P003": ("C", "否"),
        "P004": ("C", "否"), "P005": ("B", "否"), "P006": ("C", "否"),
        "P007": ("C", "否"), "P008": ("C", "否"), "P009": ("B", "否"),
        "P010": ("C", "否"), "P011": ("B", "否"), "P012": ("B", "否"),
        "P013": ("D", "否"), "P014": ("A", "部分"), "P015": ("C", "否"),
        "P016": ("B", "部分"), "P017": ("B", "否"), "P018": ("D", "否"),
        "P019": ("B", "部分"), "P020": ("C", "否"), "P021": ("C", "否"),
        "P022": ("C", "否"), "P023": ("C", "否"), "P024": ("C", "否"),
        "P025": ("C", "否"), "P026": ("C", "否"), "P027": ("C", "否"),
        "P028": ("C", "否"),
    }
    scene_override = {
        "P001": "assets/scenes/P001-三全-evidence-draft-v2.png",
        "P002": "assets/scenes/P002-产业园-evidence-draft-v2.png",
        "P003": "assets/scenes/P003-人大附中-site-grounded-v2.png",
        "P004": "assets/scenes/P004-射洪-evidence-draft-v2.png",
        "P005": "assets/scenes/P005-城市副中心-site-grounded-v2.png",
        "P006": "assets/scenes/P006-营养支持-evidence-draft-v2.png",
        "P007": "assets/scenes/P007-山西焦煤-evidence-draft-v2.png",
        "P008": "assets/scenes/P008-无锡新吴区-product-grounded-v2.png",
        "P009": "assets/scenes/P009-机场-site-grounded-v2.png",
        "P021": "assets/scenes/P021-guokang-hospital-solution-simulation.png",
        "P022": "assets/scenes/P022-sifangda-solution-simulation.png",
        "P023": "assets/scenes/P023-cac-solution-simulation.png",
        "P024": "assets/scenes/P024-daxing-three-school-solution-simulation.png",
    }
    for pid in range(10, 20):
        project_id = f"P{pid:03d}"
        scene_override[project_id] = text(p2[project_id].get("scene_file"))

    rows: list[dict[str, str]] = []
    for project in projects:
        pid = project["项目ID"]
        grade, one_to_one = overall[pid]
        scene = scene_override.get(pid, "")
        if pid in p1:
            source = p1[pid]
            space = text(source.get("空间参考"))
            hardware = text(source.get("硬件照片来源"))
            quantity = text(source.get("数量证据"))
            blocker = text(source.get("未还原原因"))
            status = "候选图-需显示证据等级" if scene else "待补证-无正式图"
            source_file = "photo-evidence-P001-P009.csv"
        elif pid in p2:
            source = p2[pid]
            space = text(source.get("space_reference"))
            hardware = text(source.get("hardware_photo_source"))
            quantity = text(source.get("quantity_evidence"))
            blocker = text(source.get("unrestored_reason"))
            status = text(source.get("final_status"))
            source_file = "photo-evidence-P010-P019.csv"
        else:
            sources = late.get(pid, [])
            space = "；".join(dict.fromkeys(text(x.get("space_reference")) for x in sources if text(x.get("space_reference"))))
            hardware = "；".join(dict.fromkeys(text(x.get("hardware_photo_source")) for x in sources if text(x.get("hardware_photo_source"))))
            quantity = "；".join(dict.fromkeys(text(x.get("quantity_evidence")) for x in sources if text(x.get("quantity_evidence"))))
            blocker = "；".join(dict.fromkeys(text(x.get("non_restoration_reason")) for x in sources if text(x.get("non_restoration_reason"))))
            status = "候选图-解决方案模拟" if scene else "待补证-无正式图"
            source_file = "photo-evidence-P020-P028.csv"

        correction = ""
        if pid == "P005":
            correction = "用户明确提供的4张城市副中心现场照片只归P005；56台为图纸/BOM口径，实际安装仍待验收闭环。"
        if pid == "P028":
            scene = ""
            space = "城市副中心4张照片已撤销，不得用于P028；P028现场照片待补证。"
            hardware = "只有型号与数量基表，可作产品/文档校准。"
            blocker = "缺P028/C08同一项目点位的真实现场照片、点位图、型号铭牌/SN与验收数量。"
            status = "错配已隔离-待补证-无正式图"
            correction = "原P028图片误用了P005照片，已移入assets/quarantine/misattributed-v1。"

        rows.append({
            "项目ID": pid,
            "项目名称": project["项目名称"],
            "场景类型": project["场景类型"],
            "总体证据等级": grade,
            "是否可1比1": one_to_one,
            "唯一主图": scene,
            "主图状态": status,
            "空间证据": space or "待补证",
            "硬件外观证据": hardware or "待补证",
            "数量证据": quantity or "待补证",
            "正式出图阻断": blocker or "待补证",
            "源证据表": source_file,
            "纠偏说明": correction,
        })

    output = DATA / "project-image-selection.csv"
    with output.open("w", encoding="utf-8-sig", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)
    print(f"rows={len(rows)} selected={sum(bool(x['唯一主图']) for x in rows)} output={output}")


if __name__ == "__main__":
    main()
