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-055": {
        "用例标题": "【已收束】子单申诉/处罚同意赔偿（引用S-FLOW-063）",
        "前置条件": "已执行子单处罚/子单申诉发起用例，丸友集侧出现待处理或处理中的处罚/申诉记录；处理动作统一引用 S-FLOW-063。",
        "执行步骤": "调用 S-FLOW-063【丸友集】通用子单处罚处理-同意赔偿。",
        "预期结果": "同 S-FLOW-063：丸友集侧目标记录已完成/已通过，处罚金额等于申请处罚金额；丸掌柜侧子单处罚单/子单申诉记录同步为已完成。",
        "跨端/状态断言": "不再单独维护子单申诉同意赔偿断言，统一以 S-FLOW-063 为准；查询时按上游单号（丸掌柜主单号）定位目标记录。",
        "可组合/被引用关系": "不再作为独立处理逻辑；链路中统一引用 S-FLOW-063。",
        "备注": "2026-06-24 收束：子单申诉/处罚同意赔偿统一由 S-FLOW-063 覆盖。",
    },
    "S-FLOW-056": {
        "用例标题": "【已收束】子单申诉/处罚驳回（引用S-FLOW-064）",
        "前置条件": "已执行子单处罚/子单申诉发起用例，丸友集侧出现待处理或处理中的处罚/申诉记录；处理动作统一引用 S-FLOW-064。",
        "执行步骤": "调用 S-FLOW-064【丸友集】通用子单处罚处理-驳回处罚。",
        "预期结果": "同 S-FLOW-064：丸友集侧目标记录已拒绝，处罚金额为0；丸掌柜侧子单处罚单/子单申诉记录同步为已拒绝。",
        "跨端/状态断言": "不再单独维护子单申诉驳回断言，统一以 S-FLOW-064 为准；查询时按上游单号（丸掌柜主单号）定位目标记录。",
        "可组合/被引用关系": "不再作为独立处理逻辑；链路中统一引用 S-FLOW-064。",
        "备注": "2026-06-24 收束：子单申诉/处罚驳回统一由 S-FLOW-064 覆盖。",
    },
}


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
                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 replace_refs(value: str) -> str:
    result = value
    replacements = {
        "S-FLOW-055": "S-FLOW-063",
        "S-FLOW-056": "S-FLOW-064",
        "【丸友集】同意赔偿后【丸掌柜】子单申诉处理完成": "【丸友集】通用子单处罚处理-同意赔偿",
        "【丸友集】驳回申诉后【丸掌柜】子单申诉被驳回": "【丸友集】通用子单处罚处理-驳回处罚",
    }
    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()
