from collections import Counter

import discord
import sqlite3
import sys
import time
import re

def connections(message : discord.message, reverse):
    if reverse == True:
        reverse = -1
    else:
        reverse = 1

    conn = sqlite3.connect('stats.db')
    cursor = conn.cursor()
    
    sync_time = 0
    new_sync_time = (int)(time.mktime(message.created_at.timetuple()))

    cursor.execute('''SELECT * FROM CONNECTIONS WHERE NAME = ?''', (message.author.id,))

    data = cursor.fetchone()

    total_guesses = 0
    total_games = 0
    wins = 0
    perfects = 0

    if data:
        total_games = data[1]
        wins = data[2]
        perfects = data[3]
        total_guesses = data[6]
        sync_time = data[8]
        if sync_time > new_sync_time and reverse == 1:
            return

    color_grid = extract_connections_grid( message.content)

    if color_grid:

        guesses = check_connections_win(color_grid)

        total_games += 1 * reverse

        total_guesses += len(color_grid) * reverse
        if guesses > 0:
            wins += 1 * reverse
            perfect_game = is_perfect_game(color_grid)
            if perfect_game:
                perfects += 1 * reverse
    else:
        print("Connections: Failed parsing color grid")
        print(message.content)
        return



    if wins == 0:
        average_guesses = 0
    else:
        average_guesses = total_guesses / wins

    win_rate = (wins / total_games) * 100
    perfect_rate = (perfects / total_games) * 100


    cursor.execute('''INSERT OR REPLACE INTO CONNECTIONS VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)''',
                   (message.author.id,
                    total_games,
                    wins,
                    perfects,
                    win_rate,
                    perfect_rate,
                    total_guesses,
                    average_guesses,
                    new_sync_time,
                    ))

    conn.commit()
    conn.close()

def extract_connections_grid(message):
    message_content = message.strip()
    # Extract the puzzle number
    puzzle_number_start = message_content.find("Puzzle #") + len("Puzzle #")
    puzzle_number_end = message_content.find("\n", puzzle_number_start)
    puzzle_number = message_content[puzzle_number_start:puzzle_number_end].strip()

    # Extract the grid (assume the grid starts after the first two lines)
    grid_start = message_content.find("\n", message_content.find("Puzzle #")) + 1
    grid_content = message_content[grid_start:].strip()

    # Split the grid into lines
    color_grid = grid_content.split("\n")
    return color_grid


    
def check_connections_win(color_grid):
    """
    Check if the Connections game is a win and return the number of guesses.
    A win is when there are exactly 4 groups of 4 colors each.
    """
    # Flatten the color grid into a list of colors
    uniform_rows = [row for row in color_grid if len(set(row)) == 1]

    flattened_grid = ''.join(uniform_rows)
    
    # Count the occurrences of each color in the grid
    color_counts = Counter(flattened_grid)
    
    # Check if there are exactly 4 different colors with 4 squares each
    if len(color_counts) == 4 and all(count == 4 for count in color_counts.values()):
        # A win: return the number of guesses (lines in the grid)
        return len(color_grid)
    return 0  # Not a win

def is_perfect_game(color_grid):
    """
    Check if the Connections game is a perfect game (solved in 4 guesses, no mistakes).
    """
    # A perfect game is one where the first 4 lines form perfect groups
    if len(color_grid) == 4 and all(len(set(line)) == 1 for line in color_grid):
        return True  # It's a perfect game
    return False