from __future__ import annotations

import json
from pathlib import Path

from openpyxl import load_workbook


ROOT = Path(__file__).resolve().parents[1]

CASE_UPDATES = {
    "S-FLOW-024": {
        "用例标题": "【已收束】打手未接单阶段主单售后中-处理售后（引用S-FLOW-003）",
        "前置条件": "已执行打手未接单阶段主单发起售后用例，目标主单进入售后中；确认/处理主单售后动作统一引用 S-FLOW-003。",
        "执行步骤": "调用 S-FLOW-003【丸掌柜】主单售后中状态-确认主单售后。",
        "预期结果": "同 S-FLOW-003：主单售后处理成功，主单由售后中变为已售后，售后信息展示已完成或页面对应售后完成结果。",
        "跨端/状态断言": "不再单独维护打手未接单阶段主单处理售后断言，统一以 S-FLOW-003 为准。",
        "可组合/被引用关系": "不再作为独立链路节点；链路中统一引用 S-FLOW-003。",
        "备注": "2026-06-24 收束：主单售后处理统一由 S-FLOW-003 覆盖。",
    },
    "S-FLOW-047": {
        "用例标题": "【已收束】待验收阶段主单售后中-处理售后（引用S-FLOW-003）",
        "前置条件": "已执行待验收阶段主单发起售后用例，目标主单进入售后中；确认/处理主单售后动作统一引用 S-FLOW-003。",
        "执行步骤": "调用 S-FLOW-003【丸掌柜】主单售后中状态-确认主单售后。",
        "预期结果": "同 S-FLOW-003：主单售后处理成功，主单由售后中变为已售后，售后信息展示已完成或页面对应售后完成结果。",
        "跨端/状态断言": "不再单独维护待验收阶段主单处理售后断言，统一以 S-FLOW-003 为准。",
        "可组合/被引用关系": "不再作为独立链路节点；链路中统一引用 S-FLOW-003。",
        "备注": "2026-06-24 收束：主单售后处理统一由 S-FLOW-003 覆盖。",
    },
}


def update_json(path: Path) -> None:
    if not path.exists():
        return
    data = json.loads(path.read_text(encoding="utf-8-sig"))
    for item in data:
        case_id = item.get("用例编号")
        if case_id in CASE_UPDATES:
            item.update(CASE_UPDATES[case_id])
        for key in ["用例编号序列", "用例链路（编号+标题）", "可组合/被引用关系", "备注"]:
            value = item.get(key)
            if isinstance(value, str):
                item[key] = replace_refs(value)
    path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def update_workbook(path: Path) -> None:
    wb = load_workbook(path)
    for ws in wb.worksheets:
        headers = {str(ws.cell(1, col).value or ""): col for col in range(1, ws.max_column + 1)}
        case_col = headers.get("用例编号")
        if case_col:
            for row in range(2, ws.max_row + 1):
                case_id = str(ws.cell(row, case_col).value or "")
                updates = CASE_UPDATES.get(case_id)
                if updates:
                    for header, value in updates.items():
                        col = headers.get(header)
                        if col:
                            ws.cell(row, col).value = value
                elif case_id in {"S-FLOW-024", "S-FLOW-047"}:
                    ws.cell(row, case_col).value = "S-FLOW-003"
                    set_step_as_s_flow_003(ws, headers, row)
        for row in range(2, ws.max_row + 1):
            for header in ["用例编号序列", "用例链路（编号+标题）", "可组合/被引用关系", "备注"]:
                col = headers.get(header)
                if col and isinstance(ws.cell(row, col).value, str):
                    ws.cell(row, col).value = replace_refs(ws.cell(row, col).value)
    wb.save(path)


def set_step_as_s_flow_003(ws, headers: dict[str, int], row: int) -> None:
    values = {
        "所属模块": "丸掌柜主单售后处理",
        "用例标题": "【丸掌柜】主单售后中状态-确认主单售后",
        "前置条件": "已执行主单发起售后用例，目标主单进入售后中。",
        "预期结果": "主单售后处理完成，主单状态变为已售后；售后信息展示已完成或页面对应售后完成结果。",
    }
    for header, value in values.items():
        col = headers.get(header)
        if col:
            ws.cell(row, col).value = value


def replace_refs(value: str) -> str:
    result = value
    replacements = {
        "S-FLOW-024": "S-FLOW-003",
        "S-FLOW-047": "S-FLOW-003",
        "丸友集已发单到打手抢单大厅/打手未接单阶段&&丸掌柜主单服务中状态/子单代练中状态-丸掌柜处理售后": "【丸掌柜】主单售后中状态-确认主单售后",
        "【丸掌柜】主单待验收状态/子单待验收状态阶段处理售后": "【丸掌柜】主单售后中状态-确认主单售后",
    }
    for old, new in replacements.items():
        result = result.replace(old, new)
    return result


def main() -> None:
    for name in [
        "scripts/order_status_flow_cases.json",
        "runtime/order_status_flow_cases_for_excel.json",
        "runtime/order_status_flow_cases_for_sheet.json",
        "runtime/order_status_branch_split_cases.json",
    ]:
        update_json(ROOT / name)
    for name in [
        "订单状态流转_链路流程线整理.xlsx",
        "SaaS_E2E测试用例_单Sheet用例测试列表.xlsx",
    ]:
        update_workbook(ROOT / name)


if __name__ == "__main__":
    main()
