from __future__ import annotations

import json
from copy import copy
from pathlib import Path

from openpyxl import load_workbook


ROOT = Path(__file__).resolve().parents[1]
CASE_JSONS = [
    ROOT / "scripts" / "order_status_flow_cases.json",
    ROOT / "runtime" / "order_status_flow_cases_for_sheet.json",
    ROOT / "runtime" / "order_status_flow_cases_for_excel.json",
]
MAIN_EXCEL = ROOT / "SaaS_E2E测试用例_单Sheet用例测试列表.xlsx"
FLOW_EXCEL = ROOT / "订单状态流转_链路流程线整理.xlsx"


S003_UPDATES = {
    "所属模块": "丸掌柜发起售后",
    "用例标题": "【丸掌柜】主单售后中状态-确认主单售后",
    "前置条件": "任一主单发起售后用例已执行完成，丸掌柜订单管理中目标主单当前状态为售后中；本用例只处理主单售后，不处理 S-FLOW-034~036 的子单行内售后。",
    "执行步骤": "1. 登录丸掌柜主账号或具备售后处理权限的账号。\n2. 进入丸掌柜-商家管理-订单管理。\n3. 按主单号、来源单号或订单标题查询目标主单。\n4. 确认目标主单当前状态为售后中。\n5. 点击目标主单操作列或售后详情中的【处理售后】、【确认售后】或页面对应主单售后处理入口。\n6. 填写处理结果、退款金额和处理备注。\n7. 提交售后处理。\n8. 回到订单管理按主单号、来源单号或订单标题重新查询目标订单。\n9. 打开订单详情，回读主单状态、子单汇总状态和售后信息。",
    "预期结果": "1. 主单售后处理提交成功。\n2. 丸掌柜主单状态由售后中变为已售后。\n3. 订单详情售后信息展示已完成或页面对应售后完成结果。\n4. 处理金额、处理备注和处理结果保存成功。\n5. 该主单售后记录不可重复按售后中状态再次处理。",
    "跨端/状态断言": "1. 本用例是所有主单售后中状态的通用确认售后用例。\n2. 不管主单发起售后的前置来自待接单、已推单、代练中、异常中或待验收，只要当前主单状态为售后中，确认售后统一引用本用例。\n3. 本用例不适用于子单行内售后；S-FLOW-034~036 子单售后仍按丸友集处理分支执行。\n4. 链路中原 S-FLOW-009、S-FLOW-067 等重复主单确认售后动作统一收束到本用例。",
    "可组合/被引用关系": "承接任一主单发起售后用例；作为主单售后中 -> 已售后的唯一确认售后用例；可被 FLOW 链路复用。",
    "自动化状态": "已自动化",
    "备注": "2026-06-24收束：主单确认售后统一由 S-FLOW-003 覆盖，重复主单确认售后用例不再单独执行。",
}

DEPRECATED_CASES = {
    "S-FLOW-009": "已收束到 S-FLOW-003；保留编号仅作历史引用，不再单独执行。",
    "S-FLOW-067": "已收束到 S-FLOW-003；主单异常中发起售后后的确认售后也统一调取 S-FLOW-003。",
}


def update_case_item(item: dict[str, str]) -> None:
    case_id = item.get("用例编号")
    if case_id == "S-FLOW-003":
        item.update(S003_UPDATES)
        return
    if case_id in DEPRECATED_CASES:
        item["自动化状态"] = "已收束"
        item["备注"] = DEPRECATED_CASES[case_id]
        item["可组合/被引用关系"] = "不再作为独立链路节点；链路中统一引用 S-FLOW-003。"
        if case_id == "S-FLOW-067":
            item["所属模块"] = "丸掌柜发起售后"
            item["用例标题"] = "【已收束】主单异常中售后中状态-确认主单售后（引用S-FLOW-003）"
            item["前置条件"] = "已执行 S-FLOW-065，目标主单进入售后中；确认售后动作统一引用 S-FLOW-003。"
            item["执行步骤"] = "调用 S-FLOW-003【丸掌柜】主单售后中状态-确认主单售后。"
            item["预期结果"] = "同 S-FLOW-003：主单由售后中变为已售后。"
            item["跨端/状态断言"] = "不再单独维护断言，统一以 S-FLOW-003 为准。"
        return
    if case_id == "S-FLOW-066":
        relation = item.get("可组合/被引用关系", "")
        relation = relation.replace("与 S-FLOW-067 主单售后处理分支互斥", "与 S-FLOW-003 主单确认售后处理分支互斥")
        item["可组合/被引用关系"] = relation


def update_case_json(path: Path) -> None:
    if not path.exists():
        return
    data = json.loads(path.read_text(encoding="utf-8"))
    for item in data:
        update_case_item(item)
    path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")


def header_map(ws) -> dict[str, int]:
    return {str(ws.cell(1, col).value or "").strip(): col for col in range(1, ws.max_column + 1)}


def clear_row_fill(ws, row: int) -> None:
    for col in range(1, ws.max_column + 1):
        ws.cell(row, col).fill = copy(ws.cell(2, col).fill)


def update_case_sheet(ws) -> None:
    headers = header_map(ws)
    id_col = headers.get("用例编号")
    if not id_col:
        return
    for row in range(2, ws.max_row + 1):
        case_id = ws.cell(row, id_col).value
        if case_id not in {"S-FLOW-003", "S-FLOW-009", "S-FLOW-067"}:
            continue
        values: dict[str, str] = {}
        if case_id == "S-FLOW-003":
            values = S003_UPDATES
        elif case_id in DEPRECATED_CASES:
            values = {
                "自动化状态": "已收束",
                "备注": DEPRECATED_CASES[case_id],
                "可组合/被引用关系": "不再作为独立链路节点；链路中统一引用 S-FLOW-003。",
            }
            if case_id == "S-FLOW-067":
                values.update(
                    {
                        "所属模块": "丸掌柜发起售后",
                        "用例标题": "【已收束】主单异常中售后中状态-确认主单售后（引用S-FLOW-003）",
                        "前置条件": "已执行 S-FLOW-065，目标主单进入售后中；确认售后动作统一引用 S-FLOW-003。",
                        "执行步骤": "调用 S-FLOW-003【丸掌柜】主单售后中状态-确认主单售后。",
                        "预期结果": "同 S-FLOW-003：主单由售后中变为已售后。",
                        "跨端/状态断言": "不再单独维护断言，统一以 S-FLOW-003 为准。",
                    }
                )
        for key, value in values.items():
            col = headers.get(key)
            if col:
                ws.cell(row, col).value = value
        if case_id in {"S-FLOW-009", "S-FLOW-067"}:
            clear_row_fill(ws, row)


def update_flow_sheet(ws) -> None:
    headers = header_map(ws)
    seq_col = headers.get("用例编号序列")
    chain_col = headers.get("用例链路（编号+标题）")
    note_col = headers.get("注意事项/缺口")
    for row in range(2, ws.max_row + 1):
        seq_value = str(ws.cell(row, seq_col).value or "") if seq_col else ""
        chain_value = str(ws.cell(row, chain_col).value or "") if chain_col else ""
        changed = False
        if "S-FLOW-067" in seq_value:
            ws.cell(row, seq_col).value = seq_value.replace("S-FLOW-067", "S-FLOW-003")
            changed = True
        if "S-FLOW-009" in seq_value:
            ws.cell(row, seq_col).value = str(ws.cell(row, seq_col).value).replace("S-FLOW-009", "S-FLOW-003")
            changed = True
        if "S-FLOW-067" in chain_value or "S-FLOW-009" in chain_value:
            chain_value = chain_value.replace("S-FLOW-067", "S-FLOW-003")
            chain_value = chain_value.replace("S-FLOW-009", "S-FLOW-003")
            chain_value = chain_value.replace("【丸友集】主单异常中售后中状态-确认主单售后", "【丸掌柜】主单售后中状态-确认主单售后")
            ws.cell(row, chain_col).value = chain_value
            changed = True
        if changed and note_col:
            note = str(ws.cell(row, note_col).value or "")
            suffix = "主单确认售后已收束为通用 S-FLOW-003。"
            ws.cell(row, note_col).value = f"{note}\n{suffix}".strip() if suffix not in note else note
            clear_row_fill(ws, row)


def update_excel(path: Path) -> None:
    if not path.exists():
        return
    wb = load_workbook(path)
    for ws in wb.worksheets:
        if ws.title in {"订单状态流转", "用例测试列表", "链路步骤明细", "用例覆盖索引", "原始用例索引"}:
            update_case_sheet(ws)
        if ws.title == "链路流程线":
            update_flow_sheet(ws)
    wb.save(path)


def main() -> None:
    for path in CASE_JSONS:
        update_case_json(path)
    update_excel(MAIN_EXCEL)
    update_excel(FLOW_EXCEL)


if __name__ == "__main__":
    main()
