"""建卡後補工作坊四欄（母卡 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-163.1": (1, "sonnet", "medium", "一支 SQL 加六欄、一處 dict 加鍵、一行既有 helper enrich，首腦已給行號；機械性，sonnet。"),
    "FR-163.2": (2, "opus", "high",   "新子元件三支＋composable 攤平去重＋Splitter＋DataTable 分段列，依定案雛形刻畫面、要組織多檔與處理去重邊界；opus。"),
    "FR-163.3": (3, "sonnet", "low",  "切換鈕從頁首搬到導航區上方：搬一行＋加一個容器 div，首腦已給行號；純機械，sonnet 低強度。"),
    "FR-163.4": (3, "opus", "medium", "攤平延後一格＋讀取狀態＋DataTable 虛擬捲動（分段模式不開）：要判斷 ref/computed 改法與虛擬捲動列高，規格已定但有取捨；opus 中強度。"),
    "FR-163.5": (4, "opus", "medium", "八欄縮五欄、證據格兩行、位置欄數量優先、任務移進操作欄：版面取捨多但規格已給到欄寬；與 .4 同檔故等它；opus 中強度。"),
    "FR-163.6": (5, "sonnet", "medium", "切換鈕併進左欄標題列、證據視圖補同款標題列並透傳 v-model：三支檔小改，首腦已定做法；sonnet 中強度。"),
}
# 改主 repo 以外的卡才列；名稱＝BE .claude/workshop.toml [repos] 的鍵
REPO = {"FR-163.2": "fe", "FR-163.3": "fe", "FR-163.4": "fe", "FR-163.5": "fe", "FR-163.6": "fe"}


def main(path: str, parent_id: str | None = None) -> None:
    """made.json 第 0 筆是母卡；追加子卡時母卡已存在，用 --parent-id 指定、made.json 全是子卡。"""
    made = json.load(open(path, encoding="utf-8"))
    if parent_id:
        parent = {"id": parent_id, "no": "(既有母卡)"}
        children = made
    else:
        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}},
        }
        if req in REPO:  # 沒列的＝主 repo，Repo 留空
            props["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()
    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：FR-163.1（BE 補欄位）。批 2：FR-163.2（FE 畫面，等 .1 合入並重啟 BE）。以各子卡 Stage 欄位為準；"
             "FR-163.2 的 Repo 欄＝fe。"}}]}},
    ]
    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__":
    args = sys.argv[1:]
    pid = args[args.index("--parent-id") + 1] if "--parent-id" in args else None
    main(args[0], pid)
