from __future__ import annotations

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"
FILES = [
    ROOT / "SaaS_E2E测试用例_单Sheet用例测试列表.xlsx",
    ROOT / "订单状态流转_链路流程线整理.xlsx",
]
OLD = "【丸掌柜】主单待验收状态/子单待验收状态-同意验收"
NEW = "【丸掌柜】主单待验收状态/子单待验收状态-同意验收完结主单"
OLD_GENERATED = "丸掌柜视角-主单待验收状态/子单待验收状态-同意验收"
NEW_GENERATED = "丸掌柜视角-主单待验收状态/子单待验收状态-同意验收完结主单"


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


def main() -> None:
    tag = datetime.now().strftime("%Y%m%d_%H%M%S")
    BACKUP_DIR.mkdir(parents=True, exist_ok=True)
    for path in FILES:
        shutil.copy2(path, BACKUP_DIR / f"{path.stem}.before_s_flow_049_title_{tag}{path.suffix}")
        wb = load_workbook(path)
        changed = 0
        for ws in wb.worksheets:
            hs = headers(ws)
            id_col = hs.get("用例编号")
            title_col = hs.get("用例标题")
            if id_col and title_col:
                for row in range(2, ws.max_row + 1):
                    if ws.cell(row, id_col).value == "S-FLOW-049":
                        if ws.cell(row, title_col).value != NEW:
                            ws.cell(row, title_col).value = NEW
                            changed += 1
            for row in ws.iter_rows():
                for cell in row:
                    if not isinstance(cell.value, str):
                        continue
                    value = cell.value
                    while f"{NEW}完结主单" in value:
                        value = value.replace(f"{NEW}完结主单", NEW)
                    while f"{NEW_GENERATED}完结主单" in value:
                        value = value.replace(f"{NEW_GENERATED}完结主单", NEW_GENERATED)
                    if NEW not in value and OLD in value:
                        value = value.replace(OLD, NEW)
                    if NEW_GENERATED not in value and OLD_GENERATED in value:
                        value = value.replace(OLD_GENERATED, NEW_GENERATED)
                    if value != cell.value:
                        cell.value = value
                        changed += 1
        wb.save(path)
        wb.close()
        print(f"{path.name}: changed {changed}")


if __name__ == "__main__":
    main()
