from __future__ import annotations

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

from openpyxl import load_workbook
from openpyxl.utils import get_column_letter


ROOT = Path(__file__).resolve().parents[1]
TARGET = ROOT / "SaaS_E2E测试用例_单Sheet用例测试列表.xlsx"
FORMAT_SOURCE = ROOT / "runtime" / "excel_backups" / "SaaS_E2E测试用例_单Sheet用例测试列表.20260622_113454.xlsx"
BACKUP_DIR = ROOT / "runtime" / "excel_backups"


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 = BACKUP_DIR / f"{TARGET.stem}.before_format_restore_{tag}{TARGET.suffix}"
    shutil.copy2(TARGET, backup)

    target_wb = load_workbook(TARGET)
    source_wb = load_workbook(FORMAT_SOURCE)

    for ws in target_wb.worksheets:
        if ws.title not in source_wb.sheetnames:
            continue
        src_ws = source_wb[ws.title]
        target_headers = headers(ws)
        source_headers = headers(src_ws)

        for header, target_col in target_headers.items():
            if header not in source_headers:
                continue
            source_col = source_headers[header]
            target_letter = get_column_letter(target_col)
            source_letter = get_column_letter(source_col)
            ws.column_dimensions[target_letter].width = src_ws.column_dimensions[source_letter].width

            source_header_cell = src_ws.cell(1, source_col)
            target_header_cell = ws.cell(1, target_col)
            target_header_cell.font = copy(source_header_cell.font)
            target_header_cell.fill = copy(source_header_cell.fill)
            target_header_cell.border = copy(source_header_cell.border)
            target_header_cell.alignment = copy(source_header_cell.alignment)
            target_header_cell.number_format = source_header_cell.number_format

        step_col = target_headers.get("执行步骤")
        expected_col = target_headers.get("预期结果")
        if step_col and expected_col:
            step_letter = get_column_letter(step_col)
            expected_letter = get_column_letter(expected_col)
            width = max(
                ws.column_dimensions[step_letter].width or 0,
                ws.column_dimensions[expected_letter].width or 0,
                45,
            )
            ws.column_dimensions[step_letter].width = width
            ws.column_dimensions[expected_letter].width = width

        ws.freeze_panes = "A2"
        for row in ws.iter_rows():
            for cell in row:
                cell.alignment = copy(cell.alignment)
                cell.alignment = cell.alignment.copy(wrap_text=True, vertical="top")
        for row_index in range(2, ws.max_row + 1):
            ws.row_dimensions[row_index].height = None

    target_wb.save(TARGET)
    target_wb.close()
    source_wb.close()
    print(f"backup: {backup}")
    print("restored column widths by header; 执行步骤/预期结果 widths unified")


if __name__ == "__main__":
    main()
