"""Excel utilities for D.intelligence branded spreadsheets."""

from __future__ import annotations

from pathlib import Path

from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side

from dintel.brand import (
    BRAND_NAME,
    HEX_PRIMARY,
    HEX_SECONDARY,
    HEX_ACCENT,
    HEX_TEXT,
)

# ── Style Constants ─────────────────────────────────────────────
HEADER_FILL = PatternFill(start_color=HEX_PRIMARY.lstrip("#"), end_color=HEX_PRIMARY.lstrip("#"), fill_type="solid")
HEADER_FONT = Font(name="Arial", size=10, bold=True, color="FFFFFF")
SUBHEADER_FILL = PatternFill(start_color=HEX_SECONDARY.lstrip("#"), end_color=HEX_SECONDARY.lstrip("#"), fill_type="solid")
SUBHEADER_FONT = Font(name="Arial", size=10, bold=True, color="FFFFFF")
ACCENT_FONT = Font(name="Arial", size=10, bold=True, color=HEX_ACCENT.lstrip("#"))
BODY_FONT = Font(name="Arial", size=10, color=HEX_TEXT.lstrip("#"))
THIN_BORDER = Border(
    left=Side(style="thin"),
    right=Side(style="thin"),
    top=Side(style="thin"),
    bottom=Side(style="thin"),
)
CENTER_ALIGN = Alignment(horizontal="center", vertical="center", wrap_text=True)
LEFT_ALIGN = Alignment(horizontal="left", vertical="center", wrap_text=True)
RIGHT_ALIGN = Alignment(horizontal="right", vertical="center")


def create_branded_workbook(title: str = "D.intelligence") -> Workbook:
    """Create an openpyxl Workbook with brand defaults."""
    wb = Workbook()
    wb.properties.title = title
    wb.properties.creator = BRAND_NAME
    return wb


def style_header_row(ws, row: int = 1, col_start: int = 1, col_end: int = 10) -> None:
    """Apply header styling to a row."""
    for col in range(col_start, col_end + 1):
        cell = ws.cell(row=row, column=col)
        cell.fill = HEADER_FILL
        cell.font = HEADER_FONT
        cell.alignment = CENTER_ALIGN
        cell.border = THIN_BORDER


def style_body_cell(cell, align: str = "left") -> None:
    """Apply body styling to a cell."""
    cell.font = BODY_FONT
    cell.border = THIN_BORDER
    if align == "center":
        cell.alignment = CENTER_ALIGN
    elif align == "right":
        cell.alignment = RIGHT_ALIGN
    else:
        cell.alignment = LEFT_ALIGN


def save_workbook(wb: Workbook, output_path: str | Path) -> Path:
    """Save workbook and return the path."""
    output_path = Path(output_path)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    wb.save(str(output_path))
    return output_path
