from __future__ import annotations

import json
import shutil
from datetime import datetime
from pathlib import Path

from openpyxl import load_workbook


ROOT = Path(__file__).resolve().parents[1]
BACKUP_DIR = ROOT / "runtime" / "excel_backups"
FLOW_EXCEL_PATH = ROOT / "订单状态流转_链路流程线整理.xlsx"
SINGLE_SHEET_EXCEL_PATH = ROOT / "SaaS_E2E测试用例_单Sheet用例测试列表.xlsx"
JSON_PATHS = [
    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",
]


CASE_ID = "S-FLOW-034"
CASE_TEXT = {
    "所属模块": "丸掌柜发起售后",
    "用例标题": "【丸掌柜】子单异常中状态-子单发起售后",
    "前置条件": (
        "丸掌柜订单详情子单列表中存在订单状态为异常中的目标子单，且该子单行内存在【发起售后】入口；"
        "丸掌柜详情顶部主单状态/子单汇总状态不作为本用例硬性前置，只记录实际展示。"
    ),
    "执行步骤": "\n".join(
        [
            "1. 登录丸掌柜主账号或客服账号。",
            "2. 进入商家管理-订单管理。",
            "3. 按主单号、来源单号或订单标题查询目标订单。",
            "4. 打开订单详情，记录顶部主单状态和子单汇总状态，仅作为实际展示回读。",
            "5. 定位子单列表中订单状态为异常中的目标子单。",
            "6. 在该异常中子单行内点击【发起售后】。",
            "7. 填写售后申请类型、售后金额、售后原因和凭证后提交。",
            "8. 回到丸掌柜订单详情，回读该目标子单行内售后状态及售后信息。",
            "9. 登录丸友集主账号或客服账号。",
            "10. 进入工作室履约应用-订单列表。",
            "11. 按来源单号或上游单号查询目标订单，回读丸友集侧订单状态和后续售后处理入口。",
        ]
    ),
    "预期结果": "\n".join(
        [
            "1. 丸掌柜侧目标异常中子单的行内售后申请提交成功。",
            "2. 丸掌柜侧售后信息保存售后金额、原因和凭证。",
            "3. 丸友集订单列表可查询到该订单，订单状态展示为售后中或页面对应的待处理售后状态。",
            "4. 后续售后处理入口在丸友集订单列表【主单售后】中操作，不在丸掌柜侧处理。",
            "5. 丸掌柜详情顶部主单状态/子单汇总状态按页面实际展示记录，不作为本用例通过/失败的硬性判断。",
        ]
    ),
    "跨端/状态断言": "\n".join(
        [
            "1. 本用例验证子单列表行内【发起售后】，不等同于订单详情右下角或主单操作区的主单售后。",
            "2. 前置判断以目标子单行状态为异常中且存在行内【发起售后】入口为准。",
            "3. 丸掌柜详情顶部主单状态、子单汇总状态只回读记录，不限制为固定状态。",
            "4. 丸掌柜负责发起子单售后；丸友集负责后续同意/拒绝售后。",
            "5. 发起后以目标子单售后信息和丸友集侧售后中/待处理售后状态作为预期验证重点。",
        ]
    ),
    "自动化状态": "已自动化",
}


def backup(path: Path, suffix: str) -> None:
    BACKUP_DIR.mkdir(parents=True, exist_ok=True)
    target = BACKUP_DIR / f"{path.stem}.before_{suffix}_{datetime.now():%Y%m%d-%H%M%S}{path.suffix}"
    shutil.copy2(path, target)
    print(f"backup: {target}")


def update_json_files() -> None:
    for path in JSON_PATHS:
        if not path.exists():
            continue
        data = json.loads(path.read_text(encoding="utf-8"))
        changed = False
        for item in data:
            if item.get("用例编号") == CASE_ID:
                item.update(CASE_TEXT)
                changed = True
        if changed:
            path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
            print(f"updated: {path}")


def update_case_rows(path: Path) -> None:
    if not path.exists():
        return
    backup(path, "s_flow_034_row_level_aftersale")
    wb = load_workbook(path)
    for ws in wb.worksheets:
        headers = {str(cell.value): cell.column for cell in ws[1] if cell.value}
        id_col = headers.get("用例编号")
        if not id_col:
            continue
        for row in range(2, ws.max_row + 1):
            if ws.cell(row, id_col).value != CASE_ID:
                continue
            for field, value in CASE_TEXT.items():
                col = headers.get(field)
                if col:
                    ws.cell(row, col).value = value
    wb.save(path)
    print(f"updated: {path}")


def main() -> None:
    update_json_files()
    update_case_rows(FLOW_EXCEL_PATH)
    update_case_rows(SINGLE_SHEET_EXCEL_PATH)


if __name__ == "__main__":
    main()
