from __future__ import annotations

from pathlib import Path

from openpyxl import load_workbook
from openpyxl.styles import Alignment


ROOT = Path(__file__).resolve().parents[1]
EXCEL_PATH = ROOT / "测试用例" / "SaaS_订阅邀请登录_测试功能点.xlsx"
FALLBACK_PATH = ROOT / "测试用例" / "SaaS_订阅邀请登录_测试功能点_含操作日志收尾.xlsx"


def append_unique_block(value: str | None, block: str) -> str:
    text = value or ""
    if block in text:
        return text
    return f"{text}\n{block}".strip()


def update_row(ws, case_id: str, step_tail: str, expected_tail: str, automation_tail: str) -> bool:
    for row_index in range(2, ws.max_row + 1):
        if ws.cell(row_index, 1).value != case_id:
            continue
        ws.cell(row_index, 8).value = append_unique_block(ws.cell(row_index, 8).value, step_tail)
        ws.cell(row_index, 9).value = append_unique_block(ws.cell(row_index, 9).value, expected_tail)
        ws.cell(row_index, 10).value = append_unique_block(ws.cell(row_index, 10).value, automation_tail)
        for cell in ws[row_index]:
            cell.alignment = Alignment(vertical="top", wrap_text=True)
        return True
    return False


def main() -> None:
    wb = load_workbook(EXCEL_PATH)

    app_ws = wb["流程用例-应用版本管理"]
    app_updates = {
        "APPVER-FLOW-001": ("新建应用版本", "应用"),
        "APPVER-FLOW-002": ("编辑应用版本", "应用"),
        "APPVER-FLOW-003": ("保存应用版本菜单", "应用"),
        "APPVER-FLOW-004": ("保存应用版本菜单", "应用"),
    }
    updated: list[str] = []
    for case_id, (operation_info, target_type) in app_updates.items():
        step_tail = (
            "操作日志收尾：进入产品管理-操作日志，目标类型选择"
            f"“{target_type}”，目标编码输入当前应用编码，点击查询。"
        )
        expected_tail = (
            f"操作日志收尾：列表存在操作信息为“{operation_info}”的成功记录；"
            "目标编码与当前应用编码一致，操作人和提交时间有值。"
        )
        automation_tail = (
            "操作日志作为落库动作的最终断言；建议封装 assert_operation_log("
            f"target_type='{target_type}', target_code=app_code, operation_info='{operation_info}')。"
        )
        if update_row(app_ws, case_id, step_tail, expected_tail, automation_tail):
            updated.append(case_id)

    product_ws = wb["流程用例-产品解决方案"]
    product_step_tail = (
        "操作日志收尾：进入产品管理-操作日志，目标类型选择“产品”，"
        "目标编码输入本次新建产品的产品编号，点击查询。"
    )
    product_expected_tail = (
        "操作日志收尾：列表存在操作信息为“新建产品”的成功记录；"
        "目标编码与新建产品编号一致，目标名称与新建产品名称一致，操作人和提交时间有值。"
    )
    product_automation_tail = (
        "新建产品流程以操作日志作为最终落库断言；建议保存列表回读到的产品编号，"
        "再调用 assert_operation_log(target_type='产品', target_code=product_code, operation_info='新建产品')。"
    )
    if update_row(
        product_ws,
        "PRODSOL-FLOW-001",
        product_step_tail,
        product_expected_tail,
        product_automation_tail,
    ):
        updated.append("PRODSOL-FLOW-001")

    try:
        wb.save(EXCEL_PATH)
        print(f"updated={EXCEL_PATH}")
    except PermissionError:
        wb.save(FALLBACK_PATH)
        print(f"locked={EXCEL_PATH}")
        print(f"fallback={FALLBACK_PATH}")
    print("cases=" + ",".join(updated))


if __name__ == "__main__":
    main()
