"""建卡後補工作坊四欄（母卡 relation／Stage／Model／Effort）並在卡尾 append 模型理由。

用法：python patch_workshop_fields.py notion-cards-made.json
made.json 是 notion_create_case.py --out 的產物（第 0 筆是母卡）。
Notion API 走 agent-workshop 的 notion_case.notion_request（token 由它從 .env 讀）。
"""
import json
import sys

sys.path.insert(0, "/Users/chouraymond/Projects/Jedicogy/agent-workshop/scripts")
import notion_case as nc  # noqa: E402

# 子卡依 requirement 後綴對應：(Stage, Model, Effort, 理由)
PLAN = {
    "FR-162.1a": (1, "opus", "high",   "套件新模組＋解析演算法＋兩種匯入匯出，規格已定但要組織多檔與寫測試；跨層判斷不多，opus 足夠。"),
    "FR-162.5":  (1, "sonnet", "medium", "一行改值＋一支 UPDATE migration，機械性。"),
    "FR-162.1b": (2, "opus", "high",   "三份官方 Excel 清洗與代號正規化要取捨（Clause 列、enhancement 寫法），DI 接線機械；opus。"),
    "FR-162.2a": (3, "opus", "high",   "依 design 寫 app service＋route＋能力點 migration，規格已定；覆寫層語意要小心，opus。"),
    "FR-162.3a": (3, "opus", "xhigh",  "跨專案配對讀模型要走多張表的鏈（module_frame→fv→resolve→wecm→evidences）、scope 紀律、唯一索引撞擊處理，最重的一張；opus 拉高 effort。"),
    "FR-162.2b": (4, "opus", "high",   "可展開 DataTable＋四個 dialog＋匯入匯出，依契約刻畫面；opus。"),
    "FR-162.3b": (4, "opus", "high",   "三步 dialog＋橫幅＋預覽表分組與預設勾選，決策者最在意的畫面；opus。"),
    "FR-162.3c": (4, "sonnet", "high", "一個新子元件＋mapper 加欄＋多處 Tag，照既有 inherited Tag 複製，機械性高；sonnet 拉 effort 補清點。"),
    "FR-162.4":  (5, "opus", "high",   "背景工作＋AI 閘道呼叫照既有範式，prompt 設計與回傳驗證要取捨；opus。"),
}


def main(path: str) -> None:
    made = json.load(open(path, encoding="utf-8"))
    parent = made[0]
    print(f"母卡 {parent['no']} {parent['id']}")
    for card in made[1:]:
        req = card["title"].split(" ", 1)[0]  # "FR-162.1a ..."
        if req not in PLAN:
            print(f"  跳過（PLAN 無此卡）：{card['title'][:40]}")
            continue
        stage, model, effort, why = PLAN[req]
        nc.notion_request("PATCH", f"/pages/{card['id']}", {"properties": {
            "母卡": {"relation": [{"id": parent["id"]}]},
            "Stage": {"number": stage},
            "Model": {"select": {"name": model}},
            "Effort": {"select": {"name": effort}},
        }})
        nc.notion_request("PATCH", f"/blocks/{card['id']}/children", {"children": [
            {"object": "block", "type": "heading_2",
             "heading_2": {"rich_text": [{"type": "text", "text": {"content": "建議模型與思考強度（首腦判斷）"}}]}},
            {"object": "block", "type": "paragraph",
             "paragraph": {"rich_text": [{"type": "text", "text": {"content": f"Stage {stage}／Model {model}／Effort {effort}。{why}"}}]}},
        ]})
        print(f"  {card['no']} {req}: Stage {stage} / {model} / {effort}")

    # 母卡尾段：子卡清單表 + 批次說明
    rows = []
    for card in made[1:]:
        req = card["title"].split(" ", 1)[0]
        if req in PLAN:
            stage, model, effort, _ = PLAN[req]
            rows.append(f"批 {stage}｜{card['no']}｜{card['title']}｜{model}/{effort}｜{card['url']}")
    rows.sort()
    children = [
        {"object": "block", "type": "heading_2",
         "heading_2": {"rich_text": [{"type": "text", "text": {"content": "子卡清單與工作坊批次"}}]}},
        {"object": "block", "type": "paragraph",
         "paragraph": {"rich_text": [{"type": "text", "text": {"content":
             "同一批可同時做；有先後的在下一批。批 1：1a、5（套件，不同檔）。批 2：1b（等 1a）。批 3：2a、3a（BE，不同模組）。"
             "批 4：2b、3b、3c（FE，不同檔，各等自己的 BE 卡）。批 5：4（等 2b）。以各子卡 Stage 欄位為準。"}}]}},
    ]
    for r in rows:
        children.append({"object": "block", "type": "bulleted_list_item",
                         "bulleted_list_item": {"rich_text": [{"type": "text", "text": {"content": r[:1900]}}]}})
    nc.notion_request("PATCH", f"/blocks/{parent['id']}/children", {"children": children})
    print("母卡子卡清單已 append")


if __name__ == "__main__":
    main(sys.argv[1])
