import pyxel
from moteur_demineur import (
    calculer_tous_les_voisins,
    creer_grille_vide,
    devoiler,
    placer_mines,
)

# --- CONSTANTES ET CONFIGURATION ---
GRILLE_TAILLE = 10
NB_MINES = 12
TAILLE_CASE = 12
MARGE_HAUT = 16

LARGEUR = GRILLE_TAILLE * TAILLE_CASE
HAUTEUR = GRILLE_TAILLE * TAILLE_CASE + MARGE_HAUT

# Variables globales d'état
grille = []
partie_terminee = False
message_fin = ""


def verifier_victoire(g: list, nb_m: int) -> bool:
    """Renvoie True si toutes les cases non-minées ont été découvertes."""
    masquees = sum(
        1
        for x in range(GRILLE_TAILLE)
        for y in range(GRILLE_TAILLE)
        if not g[x][y]["decouverte"]
    )
    return masquees == nb_m


def update():
    """Gestion des événements et mise à jour du jeu."""
    global partie_terminee, message_fin
    if partie_terminee:
        return

    # Clic Gauche : Dévoiler
    if pyxel.btnp(pyxel.MOUSE_BUTTON_LEFT):
        mx, my = pyxel.mouse_x, pyxel.mouse_y
        if my >= MARGE_HAUT:
            col, lig = mx // TAILLE_CASE, (my - MARGE_HAUT) // TAILLE_CASE

            if grille[lig][col]["mine"]:
                # Défaite : révéler toutes les mines
                for ligne in grille:
                    for case in ligne:
                        if case["mine"]:
                            case["decouverte"] = True
                partie_terminee = True
                message_fin = "PERDU !"
            else:
                devoiler(grille, lig, col)
                if verifier_victoire(grille, NB_MINES):
                    partie_terminee = True
                    message_fin = "GAGNE !"

    # Clic Droit : Poser / retirer un drapeau
    elif pyxel.btnp(pyxel.MOUSE_BUTTON_RIGHT):
        mx, my = pyxel.mouse_x, pyxel.mouse_y
        if my >= MARGE_HAUT:
            col, lig = mx // TAILLE_CASE, (my - MARGE_HAUT) // TAILLE_CASE
            case = grille[lig][col]
            if not case["decouverte"]:
                case["drapeau"] = not case["drapeau"]


def draw():
    """Rendu graphique du jeu."""
    pyxel.cls(7)

    # Affichage du score
    pyxel.text(4, 5, f"MINES: {NB_MINES}", 0)
    if message_fin:
        c_msg = 8 if message_fin == "PERDU !" else 11
        pyxel.text(LARGEUR - 40, 5, message_fin, c_msg)

    # Rendu du plateau
    for x in range(GRILLE_TAILLE):
        for y in range(GRILLE_TAILLE):
            case = grille[x][y]
            px, py = y * TAILLE_CASE, MARGE_HAUT + x * TAILLE_CASE

            if case["decouverte"]:
                pyxel.rect(px, py, TAILLE_CASE, TAILLE_CASE, 6)
                if case["mine"]:
                    pyxel.rect(px + 4, py + 4, 4, 4, 8)
                elif case["voisins"] > 0:
                    pyxel.text(px + 4, py + 3, str(case["voisins"]), 0)
            else:
                pyxel.rect(px, py, TAILLE_CASE, TAILLE_CASE, 13)
                if case["drapeau"]:
                    pyxel.rect(px + 4, py + 3, 4, 5, 11)

            pyxel.rectb(px, py, TAILLE_CASE, TAILLE_CASE, 0)


# --- DÉMARRAGE DU JEU ---
grille = creer_grille_vide(GRILLE_TAILLE)
placer_mines(grille, NB_MINES)
calculer_tous_les_voisins(grille)

pyxel.init(LARGEUR, HAUTEUR, title="Démineur NSI", fps=30)
pyxel.mouse(True)
pyxel.run(update, draw)