"""
Vykreslí jedno Str8ts puzzle v různých velikostech (18×18 cm až 2×2 cm),
každou velikost na samostatnou stránku A4, vycentrované.
"""

import json
import sys
from pathlib import Path

sys.stdout.reconfigure(encoding="utf-8")
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "Knihovny"))

from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm
from reportlab.pdfgen.canvas import Canvas

from mysql_db import connect_mysql

OUTPUT = Path(__file__).parent / "str8ts_velikosti.pdf"
GRID = 9


def draw_str8ts(c: Canvas, x0: float, y0: float, cell: float,
                puzzle: str, bw: str, title: str = ""):
    board = GRID * cell
    font_size = cell * 0.55

    if title:
        c.setFont("Helvetica-Bold", 12)
        c.drawCentredString(x0 + board / 2, y0 + 5, title)

    for idx in range(81):
        row, col = divmod(idx, 9)
        cell_x = x0 + col * cell
        cell_y = y0 - (row + 1) * cell
        cx = cell_x + cell / 2
        cy = cell_y + cell * 0.3
        is_black = bw[idx] == "1"
        ch = puzzle[idx]

        if is_black:
            c.setFillColor(colors.black)
            c.rect(cell_x, cell_y, cell, cell, fill=1, stroke=0)

        if ch in "123456789":
            c.setFillColor(colors.yellow if is_black else colors.black)
            c.setFont("Helvetica-Bold", max(font_size, 4))
            c.drawCentredString(cx, cy, ch)
            c.setFillColor(colors.black)

    for i in range(GRID + 1):
        c.setLineWidth(0.8)
        c.line(x0, y0 - i * cell, x0 + board, y0 - i * cell)
        c.line(x0 + i * cell, y0, x0 + i * cell, y0 - board)


def main():
    conn = connect_mysql(database="puzzle")
    cur = conn.cursor()
    cur.execute(
        "SELECT puzzle, extra FROM puzzles "
        "WHERE game_type='str8ts' AND difficulty='easy' AND puzzle_date='2026-05-08'"
    )
    row = cur.fetchone()
    cur.close()
    conn.close()

    if not row:
        print("Žádná data.")
        return

    puzzle = row[0]
    bw = json.loads(row[1])["bw"]

    page_w, page_h = A4
    c = Canvas(str(OUTPUT), pagesize=A4)

    for size_cm in range(18, 1, -1):
        board = size_cm * cm
        cell = board / GRID
        x0 = (page_w - board) / 2
        y0 = (page_h + board) / 2

        title = f"Str8ts Easy — {size_cm}×{size_cm} cm"
        draw_str8ts(c, x0, y0, cell, puzzle, bw, title)
        c.showPage()

    c.save()
    print(f"PDF uloženo: {OUTPUT}  ({18 - 2} stránek)")


if __name__ == "__main__":
    main()
