from __future__ import annotations

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

from openpyxl import load_workbook
from openpyxl.styles import Alignment

import split_order_status_initial_branches as split


ROOT = Path(__file__).resolve().parents[1]
WORKBOOK = ROOT / "SaaS_E2E测试用例_单Sheet用例测试列表.xlsx"
BACKUP_DIR = ROOT / "runtime" / "excel_backups"
SHEET_NAME = "订单状态流转"
HEADERS = split.HEADERS


def copy_style(source, target) -> None:
    if source.has_style:
        target._style = copy.copy(source._style)
    if source.number_format:
        target.number_format = source.number_format
    if source.alignment:
        target.alignment = copy.copy(source.alignment)


def load_current_status_rows() -> list[dict[str, str]]:
    with zipfile.ZipFile(WORKBOOK, "r") as archive:
        _, rows, _ = split.load_rows(archive)
    return rows


def write_cases(cases: list[dict[str, str]]) -> None:
    workbook = load_workbook(WORKBOOK)
    if SHEET_NAME not in workbook.sheetnames:
        raise RuntimeError(f"Sheet not found: {SHEET_NAME}")
    sheet = workbook[SHEET_NAME]

    header_styles = [copy.copy(sheet.cell(row=1, column=index)._style) for index in range(1, len(HEADERS) + 1)]
    data_template_row = 2 if sheet.max_row >= 2 else 1
    data_styles = [copy.copy(sheet.cell(row=data_template_row, column=index)._style) for index in range(1, len(HEADERS) + 1)]

    if sheet.max_row > 1:
        sheet.delete_rows(2, sheet.max_row - 1)

    for column, header in enumerate(HEADERS, 1):
        cell = sheet.cell(row=1, column=column, value=header)
        cell._style = copy.copy(header_styles[column - 1])
        cell.alignment = Alignment(wrap_text=True, vertical="top")

    for row_index, case in enumerate(cases, 2):
        for column, header in enumerate(HEADERS, 1):
            cell = sheet.cell(row=row_index, column=column, value=case.get(header, ""))
            cell._style = copy.copy(data_styles[column - 1])
            cell.alignment = Alignment(wrap_text=True, vertical="top")

    sheet.freeze_panes = "A2"
    sheet.column_dimensions["I"].width = 55
    sheet.column_dimensions["J"].width = 45
    sheet.column_dimensions["K"].width = 45
    for row_index in range(2, len(cases) + 2):
        sheet.row_dimensions[row_index].height = None

    workbook.save(WORKBOOK)


def main() -> None:
    BACKUP_DIR.mkdir(parents=True, exist_ok=True)
    backup = BACKUP_DIR / f"{WORKBOOK.stem}_before_openpyxl_branch_split_{datetime.now():%Y%m%d_%H%M%S}.xlsx"
    shutil.copy2(WORKBOOK, backup)

    rows = load_current_status_rows()
    updated = split.transform(rows)
    write_cases(updated)

    print(f"backup={backup}")
    print(f"old_count={len(rows)}")
    print(f"new_count={len(updated)}")
    for item in updated[:10]:
        print(f"{item['用例编号']}\t{item['所属模块']}\t{item['用例标题']}")


if __name__ == "__main__":
    main()
