from __future__ import annotations

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

from openpyxl import load_workbook


ROOT = Path(__file__).resolve().parents[1]
FLOW_WORKBOOK = ROOT / "测试用例" / "订单状态流转_链路流程线整理.xlsx"
BACKUP_DIR = ROOT / "runtime" / "excel_backups"


def find_row(ws, key: str) -> int | None:
    for row in range(2, ws.max_row + 1):
        if str(ws.cell(row, 1).value or "").strip() == key:
            return row
    return None


def copy_row_style(ws, source: int, target: int) -> None:
    for column in range(1, ws.max_column + 1):
        src = ws.cell(source, column)
        dst = ws.cell(target, column)
        if src.has_style:
            dst._style = copy(src._style)
        dst.font = copy(src.font)
        dst.fill = copy(src.fill)
        dst.border = copy(src.border)
        dst.alignment = copy(src.alignment)
        dst.number_format = src.number_format
    ws.row_dimensions[target].height = ws.row_dimensions[source].height


def move_row_after(ws, key: str, anchor: str) -> None:
    source = find_row(ws, key)
    anchor_row = find_row(ws, anchor)
    if source is None or anchor_row is None:
        raise AssertionError(f"missing row: key={key} source={source}; anchor={anchor} anchor_row={anchor_row}")
    if source == anchor_row + 1:
        return

    values = [ws.cell(source, column).value for column in range(1, ws.max_column + 1)]
    style_source = source
    ws.delete_rows(source)
    if source < anchor_row:
        anchor_row -= 1
    target = anchor_row + 1
    ws.insert_rows(target)
    style_row = min(style_source, ws.max_row)
    copy_row_style(ws, style_row, target)
    for column, value in enumerate(values, start=1):
        ws.cell(target, column).value = value


def main() -> None:
    BACKUP_DIR.mkdir(parents=True, exist_ok=True)
    backup = BACKUP_DIR / f"{FLOW_WORKBOOK.stem}.before_move_flow_046_after_012_{datetime.now():%Y%m%d-%H%M%S}{FLOW_WORKBOOK.suffix}"
    shutil.copy2(FLOW_WORKBOOK, backup)
    workbook = load_workbook(FLOW_WORKBOOK)
    move_row_after(workbook["链路流程线"], "FLOW-046", "FLOW-012")
    workbook.save(FLOW_WORKBOOK)
    print(f"backup {backup}")
    print(f"updated {FLOW_WORKBOOK}")


if __name__ == "__main__":
    main()
