from __future__ import annotations

import json
from pathlib import Path

from openpyxl import load_workbook


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

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

FLOW_SUMMARY_UPDATES = {
    "FLOW-010": {
        "链路名称": "丸友集已接单未发打手-主单发起售后-确认售后收尾",
        "链路类型": "已接单未发打手主单售后正向",
        "终点状态": "已售后；主单售后流程收尾",
        "用例编号序列": "S-FLOW-007 -> S-FLOW-014 -> S-FLOW-018 -> S-FLOW-003",
        "用例链路（编号+标题）": "S-FLOW-007(【丸掌柜】主单待接单状态/子单待接单-已推单状态-创建主单已推单) -> S-FLOW-014(丸友集抢单大厅待接单阶段-丸友集确认接单) -> S-FLOW-018(丸友集已接单/未发单到打手抢单大厅阶段-丸掌柜主单发起售后) -> S-FLOW-003(【丸掌柜】主单售后中状态-确认主单售后)",
        "涉及模块": "上游发单 -> 丸掌柜主单发起售后",
        "适用场景": "验证工作室接单但未发打手阶段，丸掌柜发起主单售后并确认售后完成。",
        "数据复用建议": "该链路以已售后收尾，不继续接主单申诉；如需验证已售后申诉，另起独立申诉链路。",
        "注意事项/缺口": "S-FLOW-019 已收束到 S-FLOW-003；本链路不再接 S-FLOW-051 发起申诉。",
    },
    "FLOW-011": {
        "链路名称": "丸友集已接单未发打手-主单发起售后-取消售后-继续立即发单",
        "链路类型": "已接单未发打手主单售后取消",
        "涉及模块": "上游发单 -> 丸掌柜主单发起售后",
        "适用场景": "验证工作室接单但未发打手阶段，丸掌柜发起主单售后后取消售后，并恢复到可继续发打手。",
        "注意事项/缺口": "本链路为主单售后取消分支；与 FLOW-010 的主单确认售后收尾互斥，需分开用数据。",
    },
    "FLOW-032": {
        "链路名称": "丸友集已接单未发打手-子单发起售后-处理售后收尾",
        "链路类型": "已接单未发打手子单售后正向",
        "终点状态": "已完成售后；子单售后流程收尾",
        "用例编号序列": "S-FLOW-007 -> S-FLOW-014 -> S-FLOW-058 -> S-FLOW-035",
        "用例链路（编号+标题）": "S-FLOW-007(【丸掌柜】主单待接单状态/子单待接单-已推单状态-创建主单已推单) -> S-FLOW-014(丸友集抢单大厅待接单阶段-丸友集确认接单) -> S-FLOW-058(丸友集已接单/未发单到打手抢单大厅阶段-丸掌柜子单发起售后) -> S-FLOW-035(【丸友集】子单售后中状态-同意/处理子单售后)",
        "涉及模块": "上游发单 -> 丸掌柜子单发起售后",
        "适用场景": "验证工作室接单但未发打手阶段，丸掌柜从子单列表行内入口发起子单售后并处理完成。",
        "数据复用建议": "该链路以子单售后处理完成收尾，不继续接主单申诉；子单售后取消分支另由取消链路覆盖。",
        "注意事项/缺口": "处理对象必须是 S-FLOW-058 生成的子单售后，不是主单售后；FLOW-032 到已完成售后即收尾，不再接发起申诉。",
    },
}

FLOW_STEPS = {
    "FLOW-010": ["S-FLOW-007", "S-FLOW-014", "S-FLOW-018", "S-FLOW-003"],
    "FLOW-032": ["S-FLOW-007", "S-FLOW-014", "S-FLOW-058", "S-FLOW-035"],
}


def update_json_cases(path: Path) -> None:
    if not path.exists():
        return
    data = json.loads(path.read_text(encoding="utf-8-sig"))
    for item in data:
        if item.get("用例编号") == "S-FLOW-019":
            item.update(S_FLOW_019_UPDATE)
        for key in ["用例编号序列", "用例链路（编号+标题）", "可组合/被引用关系", "备注", "预期结果"]:
            value = item.get(key)
            if isinstance(value, str):
                item[key] = clean_flow_text(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)
    if "链路流程线" in wb.sheetnames:
        update_flow_summary(wb["链路流程线"])
    if "链路步骤明细" in wb.sheetnames:
        update_flow_steps(wb["链路步骤明细"])
    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 "")
                if case_id == "S-FLOW-019":
                    for header, value in S_FLOW_019_UPDATE.items():
                        col = headers.get(header)
                        if col:
                            ws.cell(row, col).value = value
                for header in ["用例编号序列", "用例链路（编号+标题）", "可组合/被引用关系", "备注", "预期结果"]:
                    col = headers.get(header)
                    if col and isinstance(ws.cell(row, col).value, str):
                        ws.cell(row, col).value = clean_flow_text(ws.cell(row, col).value)
    wb.save(path)


def update_flow_summary(ws) -> None:
    headers = {str(ws.cell(1, col).value or ""): col for col in range(1, ws.max_column + 1)}
    flow_col = headers.get("链路编号")
    if not flow_col:
        return
    for row in range(2, ws.max_row + 1):
        flow_id = str(ws.cell(row, flow_col).value or "")
        updates = FLOW_SUMMARY_UPDATES.get(flow_id)
        if not updates:
            continue
        for header, value in updates.items():
            col = headers.get(header)
            if col:
                ws.cell(row, col).value = value


def update_flow_steps(ws) -> None:
    headers = {str(ws.cell(1, col).value or ""): col for col in range(1, ws.max_column + 1)}
    flow_col = headers.get("链路编号")
    step_col = headers.get("步骤序号")
    case_col = headers.get("用例编号")
    if not flow_col or not step_col or not case_col:
        return
    row_by_flow = {}
    for row in range(2, ws.max_row + 1):
        flow_id = str(ws.cell(row, flow_col).value or "")
        row_by_flow.setdefault(flow_id, []).append(row)
    for flow_id, cases in FLOW_STEPS.items():
        rows = row_by_flow.get(flow_id, [])
        for index, row in enumerate(rows, start=1):
            if index <= len(cases):
                case_id = cases[index - 1]
                ws.cell(row, step_col).value = index
                ws.cell(row, case_col).value = case_id
                if case_id == "S-FLOW-003":
                    set_step_text(ws, headers, row, S_FLOW_003_STEP)
                elif case_id == "S-FLOW-035":
                    set_step_text(ws, headers, row, S_FLOW_059_STEP)
            else:
                for col in range(1, ws.max_column + 1):
                    ws.cell(row, col).value = None
    for row in range(2, ws.max_row + 1):
        case_id = str(ws.cell(row, case_col).value or "")
        if case_id == "S-FLOW-019":
            set_step_text(ws, headers, row, S_FLOW_019_STEP)


S_FLOW_003_STEP = {
    "所属模块": "丸掌柜主单售后处理",
    "用例标题": "【丸掌柜】主单售后中状态-确认主单售后",
    "前置条件": "已执行主单发起售后用例，目标主单进入售后中。",
    "预期结果": "主单售后处理完成，主单状态变为已售后；售后信息展示已完成或页面对应售后完成结果。",
}

S_FLOW_019_STEP = {
    "所属模块": "丸掌柜主单售后处理",
    "用例标题": S_FLOW_019_UPDATE["用例标题"],
    "前置条件": S_FLOW_019_UPDATE["前置条件"],
    "预期结果": S_FLOW_019_UPDATE["预期结果"],
}

S_FLOW_059_STEP = {
    "所属模块": "丸掌柜子单售后处理",
    "用例标题": "丸友集已接单/未发单到打手抢单大厅阶段-丸掌柜处理子单售后",
    "前置条件": "已执行 S-FLOW-058，通过子单列表行内入口发起子单售后，当前目标子单处于售后中或页面对应待处理售后状态。",
    "预期结果": "目标子单售后处理完成，目标子单状态为已售后或页面对应售后完成状态；FLOW-032 到已完成售后即收尾。",
}


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


def clean_flow_text(value: str) -> str:
    return (
        value.replace("S-FLOW-018 -> S-FLOW-019 -> S-FLOW-051", "S-FLOW-018 -> S-FLOW-003")
        .replace("S-FLOW-019", "S-FLOW-003")
        .replace(" -> S-FLOW-051", "")
        .replace("可发起已售后申诉", "主单售后流程收尾")
        .replace("主单申诉", "主单售后收尾")
    )


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_cases(ROOT / name)
    for name in [
        "订单状态流转_链路流程线整理.xlsx",
        "SaaS_E2E测试用例_单Sheet用例测试列表.xlsx",
    ]:
        update_workbook(ROOT / name)


if __name__ == "__main__":
    main()
