"""
Vykreslí Str8ts puzzle do PDF z dat v MySQL tabulce puzzles.
Formát: 2 puzzle nad sebou na A4, velikost 11×11 cm.
"""

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 / "test_grid2.pdf"

GRID = 9
BOARD_CM = 11
BOARD = BOARD_CM * cm
CELL = BOARD / GRID


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

    if title:
        c.setFont("Helvetica-Bold", 12)
        c.drawString(x0, 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", font_size)
            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 _draw_sized(c: Canvas, x0: float, y0: float, cell: float,
                puzzle: str, bw: str, title: str = ""):
    grid = 9
    board = grid * cell
    font_size = cell * 0.55

    if title:
        c.setFont("Helvetica-Bold", 12)
        c.drawString(x0, y0 + 5, title)

    for idx in range(81):
        row, col = divmod(idx, 9)
        cell_x = x0 + col * cell
        cell_y = y0 - (row + 1) * cell
        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(cell_x + cell / 2, cell_y + cell * 0.3, 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 generate_pdf(puzzles: list[dict], output_path: Path):
    """puzzles: difficulty, puzzle, bw, solution, puzzle_date"""
    BOARD_CM = 11
    SOL_CM = 6
    GAP = 1.5 * cm
    page_w, page_h = A4
    cell_main = BOARD_CM * cm / 9
    board_main = 9 * cell_main
    x0_main = (page_w - board_main) / 2

    c = Canvas(str(output_path), pagesize=A4)

    for i in range(0, len(puzzles), 2):
        for j, p in enumerate(puzzles[i:i + 2]):
            y0 = page_h - 2 * cm - j * (BOARD_CM * cm + 3 * cm)
            _draw_sized(c, x0_main, y0, cell_main, p["puzzle"], p["bw"],
                        f"Str8ts {p['difficulty'].capitalize()} — {p['puzzle_date']}")
        c.showPage()

    c.setFont("Helvetica-Bold", 14)
    c.drawCentredString(page_w / 2, page_h - 2 * cm, "Řešení")
    y_cursor = page_h - 3.5 * cm
    sol_cell = SOL_CM * cm / 9
    sol_board = 9 * sol_cell
    x0_sol = (page_w - sol_board) / 2
    for p in puzzles:
        _draw_sized(c, x0_sol, y_cursor, sol_cell, p["solution"], p["bw"],
                    p["difficulty"].capitalize())
        y_cursor -= sol_board + GAP
    c.showPage()
    c.save()


def main():
    conn = connect_mysql(database="puzzle")
    cur = conn.cursor()
    cur.execute(
        "SELECT difficulty, puzzle, extra FROM puzzles "
        "WHERE game_type='str8ts' AND puzzle_date='2026-05-08' "
        "ORDER BY FIELD(difficulty, 'easy', 'medium', 'hard')"
    )
    rows = cur.fetchall()
    cur.close()
    conn.close()

    if not rows:
        print("Žádná data pro dnešek.")
        return

    page_w, page_h = A4
    x0 = (page_w - BOARD) / 2
    c = Canvas(str(OUTPUT), pagesize=A4)

    # 2 puzzle na stránku
    for i in range(0, len(rows), 2):
        page_rows = rows[i:i + 2]
        for j, (difficulty, puzzle, extra) in enumerate(page_rows):
            bw = json.loads(extra)["bw"]
            y0 = page_h - 2 * cm - j * (BOARD + 3 * cm)
            draw_str8ts(c, x0, y0, puzzle, bw, difficulty.capitalize())
        c.showPage()

    c.save()
    print(f"PDF uloženo: {OUTPUT}")


if __name__ == "__main__":
    main()
