"""
Vybere 2 calcudoku z MySQL a vygeneruje PDF.
Použití: python tisk_calcudoku.py [YYYY-MM-DD] [obtiznost1] [obtiznost2]
Výchozí: dnešní datum, 5x5 a 6x6.
"""

import json
import sys
from datetime import date
from pathlib import Path

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

from mysql_db import connect_mysql
from vykresli_calcudoku import generate_pdf

PUZZLE_DATE = sys.argv[1] if len(sys.argv) > 1 else date.today().isoformat()
DIFFICULTIES = sys.argv[2:4] if len(sys.argv) > 3 else ["5x5", "6x6"]
OUTPUT = Path(__file__).parent.parent / f"calcudoku_{PUZZLE_DATE}.pdf"


def main():
    conn = connect_mysql(database="puzzle")
    cur = conn.cursor()
    placeholders = ", ".join(["%s"] * len(DIFFICULTIES))
    cur.execute(
        f"SELECT difficulty, puzzle, solution, extra FROM puzzles "
        f"WHERE game_type='calcudoku' AND puzzle_date=%s AND difficulty IN ({placeholders}) "
        f"ORDER BY FIELD(difficulty, {placeholders})",
        [PUZZLE_DATE] + DIFFICULTIES + DIFFICULTIES,
    )
    rows = cur.fetchall()
    cur.close()
    conn.close()

    if not rows:
        print(f"Žádná calcudoku pro {PUZZLE_DATE} / {DIFFICULTIES}")
        return

    puzzles = []
    for difficulty, cages_str, solution_str, extra_json in rows:
        extra = json.loads(extra_json)
        puzzles.append({
            "difficulty": difficulty,
            "cages_str": cages_str,
            "solution_str": solution_str,
            "grid_size": extra["grid_size"],
            "puzzle_date": PUZZLE_DATE,
        })

    generate_pdf(puzzles, OUTPUT)
    print(f"PDF uloženo: {OUTPUT}")


if __name__ == "__main__":
    main()
