#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：fix_step12.py
模块描述：把用例「新建会议」step 12 从「预定会议」改为保持「立即开始」。

根因（2026-08-19 确认）：
- step 12 切到「预定会议」→ 会议为「未开始」→ 详情页无「结束会议」按钮 → step 17 必然失败。
- 保持「立即开始」→ 会议为「进行中」→ 详情页有「结束会议」→ step 17 可用。

改动：
- step 12 name: 时间切换为：预定会议 → 时间保持为：立即开始
- params.selector / locator_value: `.time_btn > div:last-child .btns` → `.time_btn > div:first-child`
  （立即开始 tab 就是 first-child div 自身（class `btns button_active`），不能用 `.time_btn > div:first-child .btns`
  ——那要求 first-child 的子孙，匹配 0 个元素。直接用 `.time_btn > div:first-child` 命中该 tab div）

用法：
    python scripts/fix_step12.py --base http://localhost:8001 --case case_xxx [--dry]
作者：czj
创建日期：2026-08-19
"""
import argparse
import json
import sys
import urllib.request

try:
    sys.stdout.reconfigure(encoding="utf-8")
except Exception:
    pass

STEP12_SELECTOR_OLD = ".time_btn > div:last-child .btns"
STEP12_SELECTOR_NEW = ".time_btn > div:first-child"


def api(base: str, path: str, method: str = "GET", body: dict = None, timeout: int = 60):
    url = base + path
    data = json.dumps(body).encode("utf-8") if body is not None else None
    req = urllib.request.Request(url, data=data, method=method, headers={
        "Accept": "application/json",
        "Content-Type": "application/json" if body is not None else "text/plain",
    })
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        raw = resp.read().decode("utf-8")
        return json.loads(raw) if raw else {}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--base", default="http://localhost:8001")
    parser.add_argument("--case", required=True)
    parser.add_argument("--dry", action="store_true", help="只打印不提交")
    args = parser.parse_args()

    base = args.base.rstrip("/")
    cid = args.case

    case = api(base, f"/api/cases/{cid}")
    if not case or "steps" not in case:
        print(f"!! 获取用例失败: {cid}")
        sys.exit(1)

    steps = case.get("steps", [])
    changed = False
    for s in steps:
        if s.get("order") == 12:
            old_name = s.get("name", "")
            p = s.get("params", {}) or {}
            old_sel = p.get("selector", "")
            print(f"step12 当前: name={old_name} | selector={old_sel}")
            s["name"] = "时间保持为：立即开始"
            p["selector"] = STEP12_SELECTOR_NEW
            s["params"] = p
            s["locator_value"] = STEP12_SELECTOR_NEW
            changed = True
            print(f"step12 改为: name={s['name']} | selector={p['selector']}")
            print(f"            (选择器已修正：`.time_btn > div:first-child .btns` 是零匹配，改为 `.time_btn > div:first-child`)")
            break

    if not changed:
        print("!! 未找到 step 12，用例结构可能不同")
        sys.exit(2)

    if args.dry:
        print("[dry] 未提交")
        return 0

    # PUT 提交（传整个 case 对象）
    resp = api(base, f"/api/cases/{cid}", method="PUT", body=case, timeout=30)
    if resp.get("id") or resp.get("case_id"):
        print(f"[OK] 已更新 {cid}")
    else:
        print(f"[?] 响应: {json.dumps(resp, ensure_ascii=False)[:300]}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
