from __future__ import annotations

import colorsys
import hashlib
from pathlib import Path

from openpyxl import Workbook
from openpyxl.styles import Alignment, Font, PatternFill
from openpyxl.utils import get_column_letter

from models import InventoryItem, level_label, norm
from rules import RuleBook


def _argb(rgb: str) -> str:
    rgb = rgb.strip().lstrip("#").upper()
    return rgb if len(rgb) == 8 else "FF" + rgb


def _color(value: str, kind: str) -> str:
    digest = hashlib.sha256((kind + ":" + norm(value)).encode("utf-8")).digest()
    hue = int.from_bytes(digest[:2], "big") / 65535.0
    lightness, saturation = ((0.89, 0.58) if kind == "prefix" else (0.80, 0.62))
    r, g, b = colorsys.hls_to_rgb(hue, lightness, saturation)
    return _argb(f"{round(r*255):02X}{round(g*255):02X}{round(b*255):02X}")


def export_inventory(path: Path, items: list[InventoryItem], rules: RuleBook) -> None:
    wb = Workbook()
    ws = wb.active
    ws.title = "Ekwipunek"
    headers = ["Nazwa pełna", "Kategoria", "Legendarny", "Jakość", "Ulepszenie", "Poziom", "Prefix", "Baza", "Suffix", "Półka", "Item ID", "Uwagi"]
    ws.append(headers)
    header_fill = PatternFill("solid", fgColor=_argb("111827"))
    for cell in ws[1]:
        cell.fill = header_fill
        cell.font = Font(color="FFFFFFFF", bold=True)
        cell.alignment = Alignment(horizontal="center")
    for item in items:
        ident = item.identity
        ws.append([
            item.full_name,
            rules.category_label(ident.category),
            "TAK" if ident.legendary else "NIE",
            item.quality,
            f"+{item.upgrade}" if item.upgrade else "",
            level_label(item.level),
            rules.prefix_display(ident.prefix, ident.base) if ident.prefix else "",
            rules.display(ident.base),
            rules.display(ident.suffix) if ident.suffix else "",
            item.shelf,
            item.item_id,
            item.parser_notes,
        ])
        row = ws.max_row
        if ident.legendary:
            ws.cell(row, 3).fill = PatternFill("solid", fgColor=_argb("FDE68A"))
            ws.cell(row, 3).font = Font(bold=True)
        if ident.prefix:
            ws.cell(row, 7).fill = PatternFill("solid", fgColor=_color(rules.prefix_semantic_key(ident.prefix), "prefix"))
        if ident.suffix:
            ws.cell(row, 9).fill = PatternFill("solid", fgColor=_color(ident.suffix, "suffix"))
    widths = [45, 23, 13, 14, 12, 18, 22, 24, 24, 22, 12, 38]
    for idx, width in enumerate(widths, 1):
        ws.column_dimensions[get_column_letter(idx)].width = width
    ws.freeze_panes = "A2"
    ws.auto_filter.ref = ws.dimensions
    wb.save(path)
