"""Write leads to a formatted .xlsx file."""
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment
from openpyxl.utils import get_column_letter

COLUMNS = [
    ("Business", "name", 32), ("Phone", "phone", 20), ("Email", "email", 30),
    ("Website", "website", 36), ("Address", "address", 50), ("Map", "maps_url", 40),
]


def export_xlsx(leads: list[dict], path: str) -> str:
    wb = Workbook()
    ws = wb.active
    ws.title = "Leads"
    head_font = Font(name="Arial", bold=True, color="FFFFFF")
    body_font = Font(name="Arial")
    fill = PatternFill("solid", fgColor="1F4E78")
    for c, (label, _, width) in enumerate(COLUMNS, 1):
        cell = ws.cell(row=1, column=c, value=label)
        cell.font, cell.fill = head_font, fill
        cell.alignment = Alignment(horizontal="center", vertical="center")
        ws.column_dimensions[get_column_letter(c)].width = width
    for r, lead in enumerate(leads, 2):
        for c, (_, key, _) in enumerate(COLUMNS, 1):
            cell = ws.cell(row=r, column=c, value=lead.get(key, ""))
            cell.font = body_font
            cell.alignment = Alignment(vertical="top", wrap_text=(key == "address"))
    ws.freeze_panes = "A2"
    ws.auto_filter.ref = ws.dimensions
    wb.save(path)
    return path
