import pygame
import sys
import os
import select
import random

def get_cmd():
    if select.select([sys.stdin], [], [], 0)[0]:
        return sys.stdin.readline().strip().upper()
    return None

def close_game():
    pygame.quit()
    os._exit(0)

pygame.init()
pygame.mouse.set_visible(False)

# ----------------------------
# SCREEN
# ----------------------------
WIDTH, HEIGHT = 1440, 900
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Arcade")

clock = pygame.time.Clock()
FPS = 10

# ----------------------------
# COLORS
# ----------------------------
BLACK = (10, 10, 10)
WHITE = (255, 255, 255)
YELLOW = (255, 215, 0)
DARK = (25, 25, 25)
GREEN = (0, 200, 0)
RED = (220, 50, 50)

# ----------------------------
# LAYOUT
# ----------------------------
HUD_HEIGHT = int(HEIGHT * 0.10)
GAME_HEIGHT = HEIGHT - HUD_HEIGHT

# ----------------------------
# FONTS
# ----------------------------
font = pygame.font.SysFont(None, 60)
small_font = pygame.font.SysFont(None, 40)
big_font = pygame.font.SysFont(None, 90)

# ----------------------------
# CLOSE BUTTON (PONG STYLE)
# ----------------------------
close_text = small_font.render("CLOSE", True, WHITE)
close_rect = close_text.get_rect(center=(WIDTH - 80, HUD_HEIGHT // 2))
close_box = close_rect.inflate(40, 30)

# ----------------------------
# GRID
# ----------------------------
CELL_SIZE = 30
GRID_W = WIDTH // CELL_SIZE
GRID_H = GAME_HEIGHT // CELL_SIZE

# ----------------------------
# SNAKE STATE
# ----------------------------
snake = [(GRID_W // 2, GRID_H // 2)]
direction = (1, 0)
pending_direction = direction

points = 0
game_over = False

# ----------------------------
# GAME OVER TIMER (NEW)
# ----------------------------
game_over_time = None
GAME_OVER_DELAY = 3000  # 3 seconds

def spawn_apple():
    while True:
        pos = (random.randint(0, GRID_W - 1),
               random.randint(0, GRID_H - 1))
        if pos not in snake:
            return pos

apple = spawn_apple()

def draw_cell(pos, color):
    x, y = pos
    pygame.draw.rect(
        screen,
        color,
        (x * CELL_SIZE,
         HUD_HEIGHT + y * CELL_SIZE,
         CELL_SIZE - 2,
         CELL_SIZE - 2)
    )

# ----------------------------
# MAIN LOOP
# ----------------------------
running = True

while running:
    clock.tick(FPS)

    # ----------------------------
    # EVENTS
    # ----------------------------
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            close_game()

        if event.type == pygame.MOUSEBUTTONDOWN:
            mx, my = pygame.mouse.get_pos()
            if close_box.collidepoint(mx, my):
                close_game()

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                close_game()

    cmd = get_cmd()

    # ----------------------------
    # INPUT + GAME LOGIC
    # ----------------------------
    if not game_over:
        # EMERGENCY EXIT COMMAND
        if cmd == "RASP":
            running = False
        if cmd == "UP" and direction != (0, 1):
            pending_direction = (0, -1)
        elif cmd == "DOWN" and direction != (0, -1):
            pending_direction = (0, 1)
        elif cmd == "LEFT" and direction != (1, 0):
            pending_direction = (-1, 0)
        elif cmd == "RIGHT" and direction != (-1, 0):
            pending_direction = (1, 0)
        elif cmd == "STOP":
            pending_direction = direction
        elif cmd == "CLOSE":
            close_game()

        direction = pending_direction

        # ----------------------------
        # MOVE SNAKE
        # ----------------------------
        head_x, head_y = snake[0]
        dx, dy = direction
        new_head = (head_x + dx, head_y + dy)

        # WALL COLLISION
        if new_head[0] < 0 or new_head[0] >= GRID_W or new_head[1] < 0 or new_head[1] >= GRID_H:
            game_over = True
            game_over_time = pygame.time.get_ticks()

        # SELF COLLISION
        elif new_head in snake:
            game_over = True
            game_over_time = pygame.time.get_ticks()

        else:
            snake.insert(0, new_head)

            if new_head == apple:
                points += 1
                apple = spawn_apple()
            else:
                snake.pop()

    # ----------------------------
    # AUTO CLOSE AFTER 3 SECONDS
    # ----------------------------
    if game_over and game_over_time is not None:
        if pygame.time.get_ticks() - game_over_time > GAME_OVER_DELAY:
            close_game()

    # ----------------------------
    # DRAW
    # ----------------------------
    screen.fill(BLACK)

    # HUD
    pygame.draw.rect(screen, DARK, (0, 0, WIDTH, HUD_HEIGHT))

    score_text = font.render(f"Points : {points}", True, WHITE)
    screen.blit(score_text, score_text.get_rect(center=(WIDTH // 2, HUD_HEIGHT // 2)))

    # Close button
    pygame.draw.rect(screen, WHITE, close_box, 5, border_radius=8)
    screen.blit(close_text, close_rect)

    # Border
    pygame.draw.rect(screen, YELLOW, screen.get_rect(), 10)
    pygame.draw.line(screen, YELLOW, (0, HUD_HEIGHT), (WIDTH, HUD_HEIGHT), 10)

    # Apple
    draw_cell(apple, RED)

    # Snake
    for segment in snake:
        draw_cell(segment, GREEN)

    # ----------------------------
    # GAME OVER UI (PONG STYLE)
    # ----------------------------
    if game_over:
        text = big_font.render("GAME OVER", True, YELLOW)
        rect = text.get_rect(center=(WIDTH // 2, HUD_HEIGHT + GAME_HEIGHT // 2))

        box = rect.inflate(80, 50)

        pygame.draw.rect(screen, WHITE, box, 6, border_radius=12)
        pygame.draw.rect(screen, BLACK, box.inflate(-10, -10), 0, border_radius=12)

        screen.blit(text, rect)

    pygame.display.flip()

pygame.quit()
sys.exit()