from __future__ import annotations

from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageOps


ROOT = Path(__file__).resolve().parents[1]
SOURCE = Path(r"C:\Users\conta\OneDrive\Desktop\cardapio PDF")
OUT = ROOT / "output" / "cardapio_refeito"


def deepen_brand_colors(img: Image.Image) -> Image.Image:
    arr = np.array(img.convert("RGB")).astype(np.float32)
    r, g, b = arr[..., 0], arr[..., 1], arr[..., 2]

    # Clean whites without washing the text.
    white = (r > 232) & (g > 232) & (b > 232)
    arr[white] = arr[white] * 0.28 + np.array([255, 255, 252]) * 0.72

    # Make black menu bands richer.
    dark = (r < 55) & (g < 55) & (b < 55)
    arr[dark] *= 0.72

    # Strengthen the existing red brand accents.
    red = (r > 145) & (r > g * 1.35) & (r > b * 1.35)
    arr[..., 0][red] = np.minimum(255, r[red] * 1.12 + 10)
    arr[..., 1][red] = g[red] * 0.82
    arr[..., 2][red] = b[red] * 0.82

    # Warm up food tones very lightly.
    food = (r > 115) & (g > 65) & (b < 120) & ~red
    arr[..., 0][food] = np.minimum(255, r[food] * 1.04)
    arr[..., 1][food] = np.minimum(255, g[food] * 1.025)

    return Image.fromarray(np.clip(arr, 0, 255).astype(np.uint8), "RGB")


def add_subtle_finish(img: Image.Image) -> Image.Image:
    img = ImageOps.autocontrast(img.convert("RGB"), cutoff=0.35)
    img = deepen_brand_colors(img)
    img = ImageEnhance.Contrast(img).enhance(1.06)
    img = ImageEnhance.Color(img).enhance(1.08)
    img = img.filter(ImageFilter.UnsharpMask(radius=1.15, percent=118, threshold=3))

    # Very thin premium edge, kept outside useful content as much as possible.
    draw = ImageDraw.Draw(img, "RGBA")
    w, h = img.size
    draw.rectangle((0, 0, w - 1, h - 1), outline=(12, 12, 12, 210), width=max(2, w // 900))
    draw.rectangle((5, 5, w - 6, h - 6), outline=(220, 43, 45, 95), width=max(1, w // 1600))
    return img


def process_page(path: Path) -> Image.Image:
    img = Image.open(path).convert("RGB")
    return add_subtle_finish(img)


def make_contact_sheet(files: list[Path]) -> None:
    thumbs = []
    for file in files:
        im = Image.open(file).convert("RGB")
        im.thumbnail((210, 285), Image.Resampling.LANCZOS)
        thumbs.append((file.name, im.copy()))

    cols = 4
    cell_w, cell_h = 230, 330
    rows = (len(thumbs) + cols - 1) // cols
    sheet = Image.new("RGB", (cols * cell_w, rows * cell_h), (24, 24, 24))
    draw = ImageDraw.Draw(sheet)
    for i, (name, im) in enumerate(thumbs):
        x = (i % cols) * cell_w + (cell_w - im.width) // 2
        y = (i // cols) * cell_h + 12
        sheet.paste(im, (x, y))
        draw.text(((i % cols) * cell_w + 10, y + im.height + 8), name, fill=(245, 245, 245))
    sheet.save(OUT / "preview_cardapio_refeito.png", quality=95)


def make_pdf(files: list[Path]) -> None:
    pages = [Image.open(file).convert("RGB") for file in files]
    pdf = OUT / "cardapio_refeito_completo.pdf"
    pages[0].save(pdf, save_all=True, append_images=pages[1:], resolution=200)


def main() -> None:
    OUT.mkdir(parents=True, exist_ok=True)
    final_files: list[Path] = []
    for idx in range(1, 9):
        src = SOURCE / f"{idx:02d}.png"
        out = OUT / f"{idx:02d}_cardapio_refeito.png"
        process_page(src).save(out, quality=96)
        print(out)
        final_files.append(out)

    make_contact_sheet(final_files)
    make_pdf(final_files)
    print(OUT / "preview_cardapio_refeito.png")
    print(OUT / "cardapio_refeito_completo.pdf")


if __name__ == "__main__":
    main()
