"""Génération de fichiers d'import FICTIFS pour les tests (aucune donnée réelle)."""
from __future__ import annotations

import io
import zipfile
from pathlib import Path

from openpyxl import Workbook
from PIL import Image, ImageDraw, ImageFont

FONT = Path(__file__).resolve().parent.parent / "edcf" / "assets" / "fonts" / "Barlow-Regular.ttf"
LABELS = [
    "Alcoolémie délictuelle", "Alcoolémie contraventionnelle", "Conduite sous stupéfiants", "Vitesse (+ 50 km/h)",
    "Vitesse (40 à 49 km/h)", "Vitesse (inférieure ou égale à 39 km/h)", "Distracteurs", "AFD Stupéfiants",
    "AFD Assurance", "AFD Permis", "Contrefaçons", "ESI", "Autres infractions", "Enquêtes judiciaires",
]
VALUES = [3, 5, 2, 1, 4, 27, 8, 2, 1, 3, 0, 1, 12, 2]


def csv_bytes() -> bytes:
    lines = ["Bilan hebdomadaire EDCF 52 - semaine 40 (du 28/09/2026 au 04/10/2026);;",
             "Thématique;Nb;Commentaires"]
    order = list(range(14))[::-1]  # ordre inversé
    for i in order:
        label = LABELS[i].replace("Vitesse (+ 50 km/h)", "Vitesse > 50 km/h")
        lines.append(f"{label};{VALUES[i]};{'Fictif' if i == 0 else ''}")
    lines.append("Distracteurs;9;doublon volontaire")
    lines.append("Total;71;")
    return ("\n".join(lines) + "\n").encode("cp1252")


def xlsx_bytes() -> bytes:
    wb = Workbook()
    hidden = wb.active
    hidden.title = "Brouillon caché"
    hidden["A1"] = "rien"
    hidden.sheet_state = "hidden"
    ws = wb.create_sheet("Bilan S40")
    ws["A1"] = "BILAN HEBDOMADAIRE — SEMAINE 40 — 2026"
    ws.merge_cells("A1:C1")
    ws.append([])
    ws.append(["Thématique de contrôle", "Nombre", "Observations"])
    for i in [5, 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 12]:  # ESI (index 11) manquante, ordre différent
        ws.append([LABELS[i], VALUES[i], "Taux 0,92 et 1,10" if i == 0 else None])
    ws.append(["Enquêtes judiciaires", "=1+1", None])
    out = io.BytesIO()
    wb.save(out)
    return out.getvalue()


def table_image(fmt: str = "PNG", rotate: int = 0) -> bytes:
    font = ImageFont.truetype(str(FONT), 30)
    bold = ImageFont.truetype(str(FONT), 34)
    img = Image.new("RGB", (1500, 1200), "white")
    d = ImageDraw.Draw(img)
    d.text((40, 30), "BILAN HEBDOMADAIRE EDCF 52 - SEMAINE 40", font=bold, fill="black")
    d.text((40, 120), "Thématique de contrôle", font=font, fill="black")
    d.text((900, 120), "Nombre", font=font, fill="black")
    d.text((1120, 120), "Observations", font=font, fill="black")
    for i, (label, value) in enumerate(zip(LABELS, VALUES)):
        y = 180 + i * 68
        d.line((30, y - 10, 1470, y - 10), fill="#999999", width=2)
        d.text((40, y), label, font=font, fill="black")
        d.text((930, y), str(value), font=font, fill="black")
    if rotate:
        img = img.rotate(rotate, expand=True, fillcolor="white")
    out = io.BytesIO()
    img.save(out, fmt, quality=92) if fmt == "JPEG" else img.save(out, fmt)
    return out.getvalue()


def scanned_pdf() -> bytes:
    img = Image.open(io.BytesIO(table_image()))
    out = io.BytesIO()
    img.save(out, "PDF", resolution=150)
    return out.getvalue()


def zip_with(entries: dict[str, bytes], method: int = zipfile.ZIP_DEFLATED) -> bytes:
    out = io.BytesIO()
    with zipfile.ZipFile(out, "w", compression=method) as z:
        for name, data in entries.items():
            z.writestr(name, data)
    return out.getvalue()
