from __future__ import annotations

from io import BytesIO
from typing import Any

from openpyxl import Workbook
from openpyxl.styles import Alignment, Font

HEADERS = {
    "perechen": ["Поз. обозначение", "Наименование", "Кол.", "Примечание"],
    "specification_pcb": ["Формат", "Зона", "Поз.", "Обозначение", "Наименование", "Кол.", "Примечание"],
    "specification": ["Формат", "Зона", "Поз.", "Обозначение", "Наименование", "Кол.", "Примечание"],
    "vedomost": [
        "Наименование",
        "Код продукции",
        "Обозн. документа на поставку",
        "Поставщик",
        "Куда входит",
        "Кол. на изделие",
        "Кол. в комплекте",
        "Кол. на регулир.",
        "Всего",
        "Примечание",
    ],
    "simple_list": ["Поз. обозначение", "Наименование", "Кол."],
}

FIELDS = {
    "perechen": ["position", "designation", "quantity", "note"],
    "specification_pcb": ["format", "zone", "position", "designation", "name", "quantity", "note"],
    "specification": ["format", "zone", "position", "designation", "name", "quantity", "note"],
    "vedomost": [
        "name",
        "product_code",
        "document_code",
        "supplier",
        "where_used",
        "quantity_per_item",
        "quantity_in_set",
        "quantity_for_reg",
        "total_quantity",
        "note",
    ],
    "simple_list": ["designator", "name", "quantity"],
}


def export_xlsx(table_type: str, rows: list[dict[str, Any]], title: str = "") -> bytes:
    wb = Workbook()
    ws = wb.active
    ws.title = table_type[:31]
    headers = HEADERS[table_type]
    fields = FIELDS[table_type]
    if title:
        ws.append([title])
        ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=len(headers))
        ws["A1"].font = Font(bold=True, size=14)
    ws.append(headers)
    for cell in ws[ws.max_row]:
        cell.font = Font(bold=True)
        cell.alignment = Alignment(wrap_text=True)
    for row in rows:
        if row.get("is_empty"):
            ws.append([""] * len(fields))
            continue
        values = [row.get(f, "") or "" for f in fields]
        ws.append(values)
        if row.get("is_header"):
            for cell in ws[ws.max_row]:
                cell.font = Font(bold=True, underline="single")
    buf = BytesIO()
    wb.save(buf)
    return buf.getvalue()
