from __future__ import annotations

from pathlib import Path

from openpyxl import load_workbook


ROOT = Path(__file__).resolve().parents[1]
FILES = [
    "订单状态流转_链路流程线整理.xlsx",
    "SaaS_E2E测试用例_单Sheet用例测试列表.xlsx",
]


def norm(value) -> str:
    return str(value or "").replace("\n", " ").strip()


def main() -> None:
    rows = []
    for filename in FILES:
        wb = load_workbook(ROOT / filename, read_only=True, data_only=True)
        for ws in wb.worksheets:
            headers = {str(ws.cell(1, col).value or ""): col for col in range(1, ws.max_column + 1)}
            id_col = headers.get("用例编号")
            if not id_col:
                continue
            title_col = headers.get("用例标题")
            pre_col = headers.get("前置条件")
            step_col = headers.get("执行步骤")
            expect_col = headers.get("预期结果")
            relation_col = headers.get("可组合/被引用关系")
            remark_col = headers.get("备注")
            for row in range(2, ws.max_row + 1):
                case_id = norm(ws.cell(row, id_col).value)
                if not case_id.startswith("S-FLOW-"):
                    continue
                title = norm(ws.cell(row, title_col).value if title_col else "")
                pre = norm(ws.cell(row, pre_col).value if pre_col else "")
                steps = norm(ws.cell(row, step_col).value if step_col else "")
                expected = norm(ws.cell(row, expect_col).value if expect_col else "")
                relation = norm(ws.cell(row, relation_col).value if relation_col else "")
                remark = norm(ws.cell(row, remark_col).value if remark_col else "")
                text = " ".join([title, pre, steps, expected, relation, remark])
                decision, reason = classify(text)
                if decision:
                    rows.append((filename, ws.title, row, case_id, title, decision, reason))
    for item in rows:
        print("\t".join(str(part) for part in item))


def classify(text: str) -> tuple[str, str]:
    if "S-FLOW-003" in text and ("已收束" in text or "统一引用" in text or "调用 S-FLOW-003" in text):
        return "已收束", "文本已明确引用 S-FLOW-003"
    if "子单" in text and ("行内" in text or "子单售后" in text or "S-FLOW-034" in text or "S-FLOW-058" in text):
        return "", ""
    if "处罚" in text or "申诉" in text or "撤销" in text or "取消售后" in text:
        return "", ""
    has_main_aftersale_pending = "主单" in text and "售后中" in text
    has_process = any(key in text for key in ["处理售后", "确认售后", "确认主单售后"])
    has_done = any(key in text for key in ["已售后", "售后完成", "售后处理完成"])
    if has_main_aftersale_pending and has_process and has_done:
        return "候选", "主单售后中处理/确认售后到已售后，疑似可收束到 S-FLOW-003"
    return "", ""


if __name__ == "__main__":
    main()
