from __future__ import annotations

import json
from pathlib import Path

from openpyxl import load_workbook


ROOT = Path(__file__).resolve().parents[1]
CASES_JSON = ROOT / "scripts" / "order_status_flow_cases.json"
CASE_WORKBOOK = ROOT / "测试用例" / "SaaS_E2E测试用例_单Sheet用例测试列表.xlsx"
FLOW_WORKBOOK = ROOT / "测试用例" / "订单状态流转_链路流程线整理.xlsx"

S037_PRECONDITION = (
    "已执行 S-FLOW-079，丸友集已按指派打手方式发单给目标打手；指派单会直接进入被指派打手的我的订单，"
    "不需要再执行 S-FLOW-026 去抢单大厅接单。"
)
S037_ASSERTION = (
    "1. 打手取消订单需要工作室审核。\n"
    "2. 打手取消订单不同于丸掌柜向下取消订单。\n"
    "3. S-FLOW-037 不能单独作为 FLOW-021 起点，必须承接 S-FLOW-079；指派单不需要再执行 S-FLOW-026。"
)
FLOW_021_SEQUENCE = "S-FLOW-007 -> S-FLOW-014 -> S-FLOW-079 -> S-FLOW-037 -> S-FLOW-038"
FLOW_022_SEQUENCE = "S-FLOW-007 -> S-FLOW-014 -> S-FLOW-079 -> S-FLOW-037 -> S-FLOW-039 -> S-FLOW-032"
FLOW_021_CHAIN = (
    "S-FLOW-007(创建主单已推单) -> S-FLOW-014(丸友集确认接单) -> "
    "S-FLOW-079(丸友集指派打手发单；无打手则先邀请打手) -> "
    "S-FLOW-037(打手代练中状态发起取消订单) -> "
    "S-FLOW-038(打手取消中状态-丸友集拒绝取消)"
)
FLOW_022_CHAIN = (
    "S-FLOW-007(创建主单已推单) -> S-FLOW-014(丸友集确认接单) -> "
    "S-FLOW-079(丸友集指派打手发单；无打手则先邀请打手) -> "
    "S-FLOW-037(打手代练中状态发起取消订单) -> "
    "S-FLOW-039(打手取消中状态-丸友集同意取消) -> "
    "S-FLOW-032(前一子单已撤销/已取消状态-续发下一子单)"
)
FLOW_START = (
    "丸掌柜已创建主单并推给丸友集；丸友集已确认接单；丸友集已指派打手发单；"
    "指派单已进入被指派打手我的订单；打手提交取消订单后进入取消中"
)


def sync_json() -> None:
    cases = json.loads(CASES_JSON.read_text(encoding="utf-8"))
    for item in cases:
        if item.get("用例编号") == "S-FLOW-037":
            item["前置条件"] = S037_PRECONDITION
            item["跨端/状态断言"] = S037_ASSERTION
            item["备注"] = "2026-07-01修正：FLOW-021/022 中 S-FLOW-037 前只承接 S-FLOW-079 指派发单；指派单不接 S-FLOW-026。"
    CASES_JSON.write_text(json.dumps(cases, ensure_ascii=False, indent=2), encoding="utf-8")
    print(f"updated json: {CASES_JSON}")


def headers(ws) -> dict[str, int]:
    return {str(cell.value).strip(): cell.column for cell in ws[1] if cell.value}


def find_row_by_id(ws, id_header: str, target_id: str) -> int | None:
    hs = headers(ws)
    col = hs[id_header]
    for row in range(2, ws.max_row + 1):
        if str(ws.cell(row, col).value or "").strip() == target_id:
            return row
    return None


def set_by_header(ws, row: int, values: dict[str, str]) -> None:
    hs = headers(ws)
    for header, value in values.items():
        col = hs.get(header)
        if not col:
            continue
        ws.cell(row, col).value = value


def sync_case_workbook() -> None:
    wb = load_workbook(CASE_WORKBOOK)
    ws = wb["订单状态流转"]
    row = find_row_by_id(ws, "用例编号", "S-FLOW-037")
    if row is None:
        raise RuntimeError("S-FLOW-037 not found")
    set_by_header(
        ws,
        row,
        {
            "前置条件": S037_PRECONDITION,
            "跨端/状态断言": S037_ASSERTION,
            "备注": "2026-07-01修正：FLOW-021/022 中 S-FLOW-037 前只承接 S-FLOW-079 指派发单；指派单不接 S-FLOW-026。",
        },
    )
    wb.save(CASE_WORKBOOK)
    print(f"updated case workbook S-FLOW-037 row={row}")


def sync_flow_workbook() -> None:
    wb = load_workbook(FLOW_WORKBOOK)
    flow_ws = wb["链路流程线"]
    detail_ws = wb["链路步骤明细"]

    for flow_id, sequence, chain, terminal, note in [
        (
            "FLOW-021",
            FLOW_021_SEQUENCE,
            FLOW_021_CHAIN,
            "打手代练中",
            "S-FLOW-037 前必须先执行 S-FLOW-079 指派打手发单；指派单直接进入打手我的订单，不接 S-FLOW-026。",
        ),
        (
            "FLOW-022",
            FLOW_022_SEQUENCE,
            FLOW_022_CHAIN,
            "旧子单已取消；下一子单待接单/代练中",
            "S-FLOW-037 前必须先执行 S-FLOW-079 指派打手发单；指派单直接进入打手我的订单，同意取消后需校验旧子单与新子单互不覆盖。",
        ),
    ]:
        row = find_row_by_id(flow_ws, "链路编号", flow_id)
        if row is None:
            raise RuntimeError(f"{flow_id} not found")
        set_by_header(
            flow_ws,
            row,
            {
                "起点状态": FLOW_START,
                "终点状态": terminal,
                "用例编号序列": sequence,
                "用例链路（编号+标题）": chain,
                "注意事项/缺口": note,
            },
        )

    detail_headers = headers(detail_ws)
    flow_col = detail_headers["链路编号"]
    case_col = detail_headers["用例编号"]
    pre_col = detail_headers.get("前置条件")
    assertion_col = detail_headers.get("预期结果")
    for row in range(2, detail_ws.max_row + 1):
        flow_id = str(detail_ws.cell(row, flow_col).value or "").strip()
        case_id = str(detail_ws.cell(row, case_col).value or "").strip()
        if flow_id in {"FLOW-021", "FLOW-022"} and case_id == "S-FLOW-037":
            if pre_col:
                detail_ws.cell(row, pre_col).value = S037_PRECONDITION
            if assertion_col:
                detail_ws.cell(row, assertion_col).value = (
                    "1. 打手订单状态为取消中。\n"
                    "2. 丸友集可见取消申请。\n"
                    "3. 丸掌柜订单状态和子单状态不因打手单独取消而进入已取消终态。\n"
                    "4. 本步骤必须承接 S-FLOW-079 后执行，指派单不需要 S-FLOW-026。"
                )

    wb.save(FLOW_WORKBOOK)
    print(f"updated flow workbook: {FLOW_WORKBOOK}")


def main() -> None:
    sync_json()
    sync_case_workbook()
    sync_flow_workbook()


if __name__ == "__main__":
    main()
