"""
Vybere 2 puzzle každého typu z MySQL a vygeneruje PDF (jedno na typ).
Použití: python PuzzleSelection.py [YYYY-MM-DD]
Výchozí datum: dnes.
"""

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

sys.stdout.reconfigure(encoding="utf-8")

BASE = Path(__file__).parent
sys.path.insert(0, str(BASE.parent / "Knihovny"))
sys.path.insert(0, str(BASE / "DailyCalcudoku"))
sys.path.insert(0, str(BASE / "DailyKakuro"))
sys.path.insert(0, str(BASE / "DailySudoku"))
sys.path.insert(0, str(BASE / "DailySuguru"))
sys.path.insert(0, str(BASE / "DailyStr8ts"))
sys.path.insert(0, str(BASE / "DailySudokuKiller"))

from mysql_db import connect_mysql
from vykresli_calcudoku import generate_pdf as gen_calcudoku
from vykresli_kakuro import generate_pdf as gen_kakuro
from vykresli_sudoku import generate_pdf as gen_sudoku
from vykresli_suguru import generate_pdf as gen_suguru
from vykresli_puzzle import generate_pdf as gen_str8ts
from vykresli_killer_sudoku import generate_pdf as gen_killer

PUZZLE_DATE = sys.argv[1] if len(sys.argv) > 1 else date.today().isoformat()


def query_by_date(cur, game_type):
    cur.execute(
        "SELECT game_type, difficulty, puzzle, solution, extra FROM puzzles "
        "WHERE game_type=%s AND puzzle_date=%s "
        "ORDER BY RAND() LIMIT 2",
        [game_type, PUZZLE_DATE],
    )
    return cur.fetchall()


def query_killer(cur, game_type):
    cur.execute(
        "SELECT game_type, difficulty, puzzle, solution, extra, puzzle_date FROM puzzles "
        "WHERE game_type=%s AND puzzle_date <= %s "
        "ORDER BY RAND() LIMIT 2",
        [game_type, PUZZLE_DATE],
    )
    return cur.fetchall()


def run(label, puzzles, gen_fn, filename):
    if not puzzles:
        print(f"{label}: žádná data pro {PUZZLE_DATE}")
        return
    out = BASE / filename
    gen_fn(puzzles, out)
    print(f"{label}: {out.name}")


def main():
    conn = connect_mysql(database="puzzle")
    cur = conn.cursor()

    # Calcudoku
    rows = query_by_date(cur, "calcudoku")
    run("calcudoku", [
        {"difficulty": r[1], "cages_str": r[2], "solution_str": r[3],
         "grid_size": json.loads(r[4])["grid_size"], "puzzle_date": PUZZLE_DATE}
        for r in rows
    ], gen_calcudoku, f"calcudoku_{PUZZLE_DATE}.pdf")

    # Kakuro
    rows = query_by_date(cur, "kakuro")
    run("kakuro", [
        {"difficulty": r[1], "puzzle_str": r[2], "puzzle_date": PUZZLE_DATE}
        for r in rows
    ], gen_kakuro, f"kakuro_{PUZZLE_DATE}.pdf")

    # Sudoku
    rows = query_by_date(cur, "sudoku")
    run("sudoku", [
        {"difficulty": r[1], "puzzle": r[2], "solution": r[3], "puzzle_date": PUZZLE_DATE}
        for r in rows
    ], gen_sudoku, f"sudoku_{PUZZLE_DATE}.pdf")

    # Suguru
    rows = query_by_date(cur, "suguru")
    run("suguru", [
        {"difficulty": r[1], "puzzle_str": r[2], "solution_str": r[3],
         "grid_size": json.loads(r[4])["grid_size"], "puzzle_date": PUZZLE_DATE}
        for r in rows
    ], gen_suguru, f"suguru_{PUZZLE_DATE}.pdf")

    # Str8ts
    rows = query_by_date(cur, "str8ts")
    run("str8ts", [
        {"difficulty": r[1], "puzzle": r[2], "solution": r[3],
         "bw": json.loads(r[4])["bw"], "puzzle_date": PUZZLE_DATE}
        for r in rows
    ], gen_str8ts, f"str8ts_{PUZZLE_DATE}.pdf")

    # Killer Sudoku — 2 nejnovější
    rows = query_killer(cur, "killer_sudoku")
    run("killer_sudoku", [
        {"game_type": r[0], "difficulty": r[1], "puzzle_str": r[2],
         "solution_str": r[3], "puzzle_date": str(r[5])}
        for r in rows
    ], gen_killer, f"killer_sudoku_{PUZZLE_DATE}.pdf")

    cur.close()
    conn.close()


if __name__ == "__main__":
    main()
