
import pygame
import sys
from pathlib import Path

# ---------------- Configuration ----------------

CELL_SIZE = 60
MARGIN = 50
BACKGROUND = (245, 245, 240)
GRID_COLOR = (70, 70, 70)
NUMBER_COLOR = (30, 30, 30)
DIAGONAL_COLOR = (35, 100, 190)
DOT_COLOR = (160, 160, 160)

pygame.init()


# ---------------- File reading ----------------

def read_grid(filename):
    """Read a rectangular grid from a text file."""
    path = Path(filename)

    if not path.is_file():
        raise FileNotFoundError(f"File not found: {filename}")

    with path.open("r", encoding="utf-8") as f:
        lines = [line.strip() for line in f if line.strip()]

    if not lines:
        raise ValueError(f"File is empty: {filename}")

    # All rows must have the same length
    width = len(lines[0])

    if any(len(line) != width for line in lines):
        raise ValueError(f"Rows have different lengths in {filename}")

    return lines


def load_puzzle(input_file, solution_file):
    puzzle = read_grid(input_file)
    solution = read_grid(solution_file)

    n = len(puzzle) - 1

    if n <= 0 or len(puzzle) != n + 1:
        raise ValueError("Invalid puzzle dimensions.")

    if len(puzzle[0]) != n + 1:
        raise ValueError("Input must be an (n+1) x (n+1) grid.")

    if len(solution) != n or any(len(row) != n for row in solution):
        raise ValueError("Solution must be an n x n grid.")

    for row in puzzle:
        if any(c not in "01234." for c in row):
            raise ValueError("Invalid character in input file.")

    for row in solution:
        if any(c not in "/\\" for c in row):
            raise ValueError("Invalid character in solution file.")

    return puzzle, solution, n


# ---------------- Drawing functions ----------------

def draw_grid(screen, puzzle, solution, n, font):
    screen.fill(BACKGROUND)

    # Draw grid lines
    for i in range(n + 1):
        x = MARGIN + i * CELL_SIZE
        y = MARGIN + i * CELL_SIZE

        pygame.draw.line(
            screen, GRID_COLOR,
            (x, MARGIN),
            (x, MARGIN + n * CELL_SIZE), 2
        )

        pygame.draw.line(
            screen, GRID_COLOR,
            (MARGIN, y),
            (MARGIN + n * CELL_SIZE, y), 2
        )

    # Draw solution diagonals (thicker lines)
    for i in range(n):
        for j in range(n):
            x1 = MARGIN + j * CELL_SIZE
            y1 = MARGIN + i * CELL_SIZE
            x2 = x1 + CELL_SIZE
            y2 = y1 + CELL_SIZE

            if solution[i][j] == '/':
                pygame.draw.line(
                    screen, DIAGONAL_COLOR,
                    (x1, y2), (x2, y1), 7
                )
            else:
                pygame.draw.line(
                    screen, DIAGONAL_COLOR,
                    (x1, y1), (x2, y2), 7
                )

    # Draw joints
    for i in range(n + 1):
        for j in range(n + 1):
            value = puzzle[i][j]

            x = MARGIN + j * CELL_SIZE
            y = MARGIN + i * CELL_SIZE

            if value == '.':
                pygame.draw.circle(
                    screen, DOT_COLOR, (x, y), 3
                )
            else:
                # Draw a white circle with a black outline
                radius = 17

                pygame.draw.circle(
                    screen, (255, 255, 255),
                    (x, y), radius
                )

                pygame.draw.circle(
                    screen, (0, 0, 0),
                    (x, y), radius, 2
                )

                # Draw the number centered inside the circle
                text = font.render(value, True, NUMBER_COLOR)
                text_rect = text.get_rect(center=(x, y))
                screen.blit(text, text_rect)

    pygame.display.flip()


# ---------------- Main program ----------------

def main():
    input_file = sys.argv[1] if len(sys.argv) > 1 else "input.txt"
    solution_file = sys.argv[2] if len(sys.argv) > 2 else "solution.txt"

    try:
        puzzle, solution, n = load_puzzle(
            input_file, solution_file
        )
    except (FileNotFoundError, ValueError) as error:
        print("Error:", error)
        sys.exit(1)

    width = 2 * MARGIN + n * CELL_SIZE
    height = 2 * MARGIN + n * CELL_SIZE

    screen = pygame.display.set_mode((width, height))
    pygame.display.set_caption("Slant / Gokigen Puzzle")

    font = pygame.font.SysFont("Arial", 28, bold=True)

    clock = pygame.time.Clock()

    running = True

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False

        draw_grid(screen, puzzle, solution, n, font)

        clock.tick(30)

    pygame.quit()


if __name__ == "__main__":
    main()
