from __future__ import annotations

import copy
import shutil
from datetime import datetime
from pathlib import Path

from openpyxl import load_workbook
from openpyxl.styles import Alignment


ROOT = Path(__file__).resolve().parents[1]
WORKBOOK = ROOT / "SaaS_E2E测试用例_单Sheet用例测试列表.xlsx"
BACKUP_DIR = ROOT / "runtime" / "excel_backups"
SHEET_NAME = "订单状态流转"
HEADERS = [
    "用例编号",
    "用例层级",
    "来源/组合依据",
    "所属模块",
    "用例标题",
    "登录平台/角色账号",
    "前置条件",
    "测试数据",
    "执行步骤",
    "预期结果",
    "跨端/状态断言",
    "可组合/被引用关系",
    "自动化状态",
    "备注",
]


def renumbered(items: list[str]) -> str:
    return "\n".join(f"{index}. {item}" for index, item in enumerate(items, 1))


def split_numbered(value: str) -> list[str]:
    lines = [line.strip() for line in str(value or "").splitlines() if line.strip()]
    items: list[str] = []
    for line in lines:
        if ". " in line and line.split(". ", 1)[0].isdigit():
            items.append(line.split(". ", 1)[1])
        else:
            items.append(line)
    return items


def read_cases(sheet) -> list[dict[str, str]]:
    rows: list[dict[str, str]] = []
    for values in sheet.iter_rows(min_row=2, max_col=len(HEADERS), values_only=True):
        if not str(values[0] or "").startswith("S-FLOW-"):
            continue
        rows.append({header: str(values[index] or "") for index, header in enumerate(HEADERS)})
    return rows


def normalize_text(value: str) -> str:
    replacements = {
        "丸掌柜视角-": "丸掌柜-",
        "【丸掌柜视角】": "【丸掌柜】",
        "无子单状态": "待接单-待推单状态",
        "无子单": "待接单-待推单",
        "未生成子单": "子单未推单",
        "不存在子单": "子单未推单",
        "仍无子单记录": "子单状态保持待接单-待推单",
        "未生成子单记录": "子单状态为待接单-待推单",
        "无子单记录": "子单状态为待接单-待推单",
        "无子单分支": "待推单分支",
        "无子单状态": "待接单-待推单状态",
    }
    result = str(value or "")
    for source, target in replacements.items():
        result = result.replace(source, target)
    return result


def transform(cases: list[dict[str, str]]) -> list[dict[str, str]]:
    for case in cases:
        for header in HEADERS:
            case[header] = normalize_text(case[header])

    by_old_id = {case["用例编号"]: case for case in cases}

    # S-FLOW-001 is the beginning of the pending-dispatch branch.
    s001 = by_old_id["S-FLOW-001"]
    s001["用例标题"] = "丸掌柜-主单待接单状态/待接单-待推单状态-创建主单未推单"
    s001["前置条件"] = "丸掌柜账号可创建外来订单；手工录单页面选择【不推单】，创建主单并进入待接单-待推单状态。"
    s001["预期结果"] = renumbered(
        [
            "丸掌柜主单订单状态为待接单。",
            "丸掌柜子单状态为待接单-待推单。",
            "丸友集抢单大厅查询不到此单。",
            "打手侧查询不到此单。",
        ]
    )
    s001["跨端/状态断言"] = renumbered(
        [
            "未推单前，福通和丸友集不应出现可接单记录。",
            "主单号、来源单号、订单标题在丸掌柜详情中一致。",
            "待接单-待推单分支不能设计子单撤销用例；只有已创建并推送的子单才可以发起撤销。",
        ]
    )
    s001["备注"] = "待推单分支起点；后续先承接该状态的售后流程。"

    for old_id in ["S-FLOW-003", "S-FLOW-005", "S-FLOW-007"]:
        case = by_old_id[old_id]
        case["用例标题"] = case["用例标题"].replace("阶段", "状态阶段")
        case["前置条件"] = case["前置条件"].replace("子单未推单", "子单处于待接单-待推单状态")
        case["备注"] = case["备注"].replace("待推单分支", "待推单分支")

    by_old_id["S-FLOW-003"]["用例标题"] = "丸掌柜-主单待接单状态/待接单-待推单状态阶段发起售后"
    by_old_id["S-FLOW-005"]["用例标题"] = "丸掌柜-主单待接单状态/待接单-待推单状态阶段处理售后"
    by_old_id["S-FLOW-007"]["用例标题"] = "丸掌柜-主单待接单状态/待接单-待推单状态阶段取消售后"

    by_old_id["S-FLOW-003"]["预期结果"] = renumbered(
        [
            "丸掌柜主单订单状态为售后中。",
            "丸掌柜子单状态为售后中或页面对应售后处理状态。",
            "丸友集抢单大厅查询不到此单。",
            "售后原因、售后金额和凭证在丸掌柜售后记录中保存成功。",
        ]
    )
    by_old_id["S-FLOW-005"]["预期结果"] = renumbered(
        [
            "丸掌柜主单订单状态为已售后。",
            "丸掌柜子单状态为已售后或页面对应售后完成状态。",
            "售后退款或资金处理记录生成并与处理金额一致。",
            "主单已售后后不能继续发子单，但后续仍可按主单流程完单或发起申诉。",
        ]
    )
    by_old_id["S-FLOW-007"]["预期结果"] = renumbered(
        [
            "丸掌柜主单订单状态恢复为待接单。",
            "丸掌柜子单状态恢复为待接单-待推单。",
            "丸友集抢单大厅查询不到此单。",
            "售后取消原因被记录，当前状态不再展示为售后中。",
        ]
    )

    # S-FLOW-002 starts the dispatched branch.
    by_old_id["S-FLOW-002"]["用例标题"] = "丸掌柜-主单待接单状态/子单待接单-已推单状态-推单到丸友集"
    by_old_id["S-FLOW-004"]["用例标题"] = "丸掌柜-主单待接单状态/子单待接单-已推单状态阶段发起售后"
    by_old_id["S-FLOW-006"]["用例标题"] = "丸掌柜-主单待接单状态/子单待接单-已推单状态阶段处理售后"
    by_old_id["S-FLOW-008"]["用例标题"] = "丸掌柜-主单待接单状态/子单待接单-已推单状态阶段取消售后"
    by_old_id["S-FLOW-009"]["用例标题"] = "丸掌柜-主单待接单状态/子单待接单-已推单状态阶段发起撤销"
    by_old_id["S-FLOW-010"]["用例标题"] = "丸掌柜-主单待接单状态/子单取消订单状态-继续发子单"

    front_order = [
        "S-FLOW-001",
        "S-FLOW-003",
        "S-FLOW-005",
        "S-FLOW-007",
        "S-FLOW-002",
        "S-FLOW-004",
        "S-FLOW-006",
        "S-FLOW-008",
        "S-FLOW-009",
        "S-FLOW-010",
    ]
    used = set(front_order)
    ordered = [by_old_id[old_id] for old_id in front_order]
    ordered.extend(case for case in cases if case["用例编号"] not in used)

    for index, case in enumerate(ordered, 1):
        case["用例编号"] = f"S-FLOW-{index:03d}"
    return ordered


def write_cases(workbook, sheet, cases: list[dict[str, str]]) -> None:
    header_styles = [copy.copy(sheet.cell(row=1, column=index)._style) for index in range(1, len(HEADERS) + 1)]
    data_template_row = 2 if sheet.max_row >= 2 else 1
    data_styles = [copy.copy(sheet.cell(row=data_template_row, column=index)._style) for index in range(1, len(HEADERS) + 1)]

    if sheet.max_row > 1:
        sheet.delete_rows(2, sheet.max_row - 1)

    for column, header in enumerate(HEADERS, 1):
        cell = sheet.cell(row=1, column=column, value=header)
        cell._style = copy.copy(header_styles[column - 1])
        cell.alignment = Alignment(wrap_text=True, vertical="top")

    for row_index, case in enumerate(cases, 2):
        for column, header in enumerate(HEADERS, 1):
            cell = sheet.cell(row=row_index, column=column, value=case.get(header, ""))
            cell._style = copy.copy(data_styles[column - 1])
            cell.alignment = Alignment(wrap_text=True, vertical="top")

    sheet.freeze_panes = "A2"
    sheet.column_dimensions["I"].width = 55
    sheet.column_dimensions["J"].width = 45
    sheet.column_dimensions["K"].width = 45
    workbook.save(WORKBOOK)


def main() -> None:
    BACKUP_DIR.mkdir(parents=True, exist_ok=True)
    backup = BACKUP_DIR / f"{WORKBOOK.stem}_before_title_sort_normalize_{datetime.now():%Y%m%d_%H%M%S}.xlsx"
    shutil.copy2(WORKBOOK, backup)

    workbook = load_workbook(WORKBOOK)
    sheet = workbook[SHEET_NAME]
    cases = read_cases(sheet)
    updated = transform(cases)
    write_cases(workbook, sheet, updated)

    print(f"backup={backup}")
    print(f"count={len(updated)}")
    for case in updated[:12]:
        print(f"{case['用例编号']}\t{case['所属模块']}\t{case['用例标题']}")


if __name__ == "__main__":
    main()
