"""建卡後補工作坊四欄（母卡 relation／Stage／Model／Effort／Repo）並在卡尾 append 模型理由、母卡 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-164.1": (1, "opus", "medium", "既有三層樹加模式：七個 prop、列尾換法、三種徽章、我的待辦過濾、圖例，且證據模式一像素不能變；要在既有元件裡做取捨但規格已給到 class 名；opus 中強度。"),
    "FR-164.2": (1, "opus", "high",   "四支新檔：只讀面板三層級內容、任務平表的攤平／分群／篩選 composable＋單測、DataTable 分群小標列、審閱鈕規則整套搬；要組織多檔與處理邊界（預設分群記憶、空列、去重）；opus 高強度。"),
    "FR-164.3": (2, "opus", "medium", "容器＋Splitter 兩層＋provide 接線＋刪六百行舊面板＋ i18n＋十四條實機驗；刪碼要判斷哪些 state 還有人用，規格已定；opus 中強度。"),
}
REPO = {"FR-164.1": "fe", "FR-164.2": "fe", "FR-164.3": "fe"}


def main(path: str) -> None:
    made = json.load(open(path, encoding="utf-8"))
    parent, children = made[0], made[1:]
    print(f"母卡 {parent['no']} {parent['id']}")
    for card in children:
        req = card["title"].split(" ", 1)[0]
        if req not in PLAN:
            print(f"  跳過（PLAN 無此卡）：{card['title'][:40]}")
            continue
        stage, model, effort, why = PLAN[req]
        props = {
            "母卡": {"relation": [{"id": parent["id"]}]},
            "Stage": {"number": stage},
            "Model": {"select": {"name": model}},
            "Effort": {"select": {"name": effort}},
            "Repo": {"select": {"name": REPO[req]}},
        }
        nc.notion_request("PATCH", f"/pages/{card['id']}", {"properties": props})
        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 children:
        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()
    blocks = [
        {"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：FR-164.1（左樹加模式）＋ FR-164.2（右側兩塊）可平行，不撞檔。批 2：FR-164.3（接線、刪舊面板、實機驗），等批 1 全驗完。三張 Repo 欄＝fe。"}}]}},
    ]
    for r in rows:
        blocks.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": blocks})
    print("母卡子卡清單已 append")


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