from __future__ import annotations

from pathlib import Path
from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side


INPUT_PATH = Path("/home/fred/Downloads/Definição Ranking_ATUACAPES - Aba1 a Aba4(7).xlsx")
OUTPUT_PATH = Path("/home/fred/projetos/ranking/docs/Definicao_Ranking_ATUACAPES_estilizada.xlsx")


def apply_styles() -> None:
    wb = load_workbook(INPUT_PATH)

    header_fill = PatternFill("solid", fgColor="E6F0FF")
    header_font = Font(bold=True, color="102A43")
    alt_fill = PatternFill("solid", fgColor="F7FAFC")
    thin = Side(style="thin", color="CBD5E0")
    border = Border(left=thin, right=thin, top=thin, bottom=thin)

    for ws in wb.worksheets:
        max_col = ws.max_column
        max_row = ws.max_row

        # Header styling
        for col in range(1, max_col + 1):
            cell = ws.cell(row=1, column=col)
            cell.fill = header_fill
            cell.font = header_font
            cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
            cell.border = border

        # Data rows styling
        for row in range(2, max_row + 1):
            row_fill = alt_fill if row % 2 == 0 else None
            for col in range(1, max_col + 1):
                cell = ws.cell(row=row, column=col)
                cell.border = border
                cell.alignment = Alignment(vertical="top", wrap_text=True)
                if row_fill:
                    cell.fill = row_fill

        # Freeze header row
        ws.freeze_panes = "A2"

        # Auto-filter across the used range
        ws.auto_filter.ref = ws.dimensions

        # Adjust column widths with caps
        for col in ws.columns:
            col_letter = col[0].column_letter
            max_len = 0
            for cell in col[: min(max_row, 200)]:
                if cell.value is None:
                    continue
                text = str(cell.value)
                if len(text) > max_len:
                    max_len = len(text)
            width = max(12, min(45, int(max_len * 0.9)))
            ws.column_dimensions[col_letter].width = width

        # Slightly taller header
        ws.row_dimensions[1].height = 28

    OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)
    wb.save(OUTPUT_PATH)


if __name__ == "__main__":
    apply_styles()
