import pygame
import sys
import os
import select

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)

WIDTH, HEIGHT = 1440, 900
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pong Arcade")

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

BLACK = (10, 10, 10)
WHITE = (255, 255, 255)
YELLOW = (255, 215, 0)
DARK = (25, 25, 25)

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

player_score = 0
ai_score = 0

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

PADDLE_W, PADDLE_H = 15, 140
BALL_SIZE = 18
PADDLE_SPEED = 8

left_paddle = pygame.Rect(
    50,
    HUD_HEIGHT + GAME_HEIGHT // 2 - PADDLE_H // 2,
    PADDLE_W,
    PADDLE_H
)

right_paddle = pygame.Rect(
    WIDTH - 50 - PADDLE_W,
    HUD_HEIGHT + GAME_HEIGHT // 2 - PADDLE_H // 2,
    PADDLE_W,
    PADDLE_H
)

ball = pygame.Rect(
    WIDTH // 2,
    HUD_HEIGHT + GAME_HEIGHT // 2,
    BALL_SIZE,
    BALL_SIZE
)

ball_vel_x = 6
ball_vel_y = 6

move_up = False
move_down = False

# ----------------------------
# WIN SYSTEM (FIXED)
# ----------------------------
game_over = False
winner_text = None
win_timer = None
WIN_WAIT = 3000  # 3 seconds

def reset_ball(direction=1):
    global ball_vel_x, ball_vel_y
    ball.center = (WIDTH // 2, HUD_HEIGHT + GAME_HEIGHT // 2)
    ball_vel_x = 6 * direction
    ball_vel_y = 6

AI_SPEED = 5
AI_ERROR = 20

def move_ai():
    target_y = ball.centery + AI_ERROR

    if right_paddle.centery < target_y:
        right_paddle.y += AI_SPEED
    if right_paddle.centery > target_y:
        right_paddle.y -= AI_SPEED

    right_paddle.y = max(
        HUD_HEIGHT,
        min(HUD_HEIGHT + GAME_HEIGHT - PADDLE_H, right_paddle.y)
    )

running = True

while running:
    clock.tick(FPS)

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

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

        if event.type == pygame.MOUSEBUTTONDOWN:
            mx, my = pygame.mouse.get_pos()
            if my < HUD_HEIGHT and mx > WIDTH - 140:
                close_game()

    cmd = get_cmd()

    # ----------------------------
    # GAME INPUT ONLY IF NOT OVER
    # ----------------------------
    if not game_over:
        # EMERGENCY EXIT COMMAND
        if cmd == "RASP":
            running = False
        if cmd == "UP":
            move_up = True
            move_down = False
        elif cmd == "DOWN":
            move_down = True
            move_up = False
        elif cmd == "STOP":
            move_up = False
            move_down = False
        elif cmd == "CLOSE":
            close_game()

        if move_up:
            left_paddle.y -= PADDLE_SPEED
        if move_down:
            left_paddle.y += PADDLE_SPEED

        left_paddle.y = max(
            HUD_HEIGHT,
            min(HUD_HEIGHT + GAME_HEIGHT - PADDLE_H, left_paddle.y)
        )

        move_ai()

        ball.x += ball_vel_x
        ball.y += ball_vel_y

        if ball.top <= HUD_HEIGHT or ball.bottom >= HEIGHT:
            ball_vel_y *= -1

        if ball.colliderect(left_paddle) and ball_vel_x < 0:
            ball_vel_x *= -1

        if ball.colliderect(right_paddle) and ball_vel_x > 0:
            ball_vel_x *= -1

        if ball.left <= 0:
            ai_score += 1
            reset_ball(1)

        if ball.right >= WIDTH:
            player_score += 1
            reset_ball(-1)

        WIN_SCORE = 10

        if player_score >= WIN_SCORE:
            winner_text = "PLAYER WINS"
            game_over = True
            win_timer = pygame.time.get_ticks()

        elif ai_score >= WIN_SCORE:
            winner_text = "AI WINS"
            game_over = True
            win_timer = pygame.time.get_ticks()

    # ----------------------------
    # WIN TIMER (NON-BLOCKING)
    # ----------------------------
    if game_over and win_timer is not None:
        if pygame.time.get_ticks() - win_timer > WIN_WAIT:
            close_game()

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

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

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

    close_text = small_font.render("CLOSE", True, WHITE)
    close_rect = close_text.get_rect(center=(WIDTH - 80, HUD_HEIGHT // 2))

    box_rect = close_rect.inflate(40, 30)
    pygame.draw.rect(screen, WHITE, box_rect, 5, border_radius=8)
    screen.blit(close_text, close_rect)

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

    pygame.draw.rect(screen, YELLOW, left_paddle)
    pygame.draw.rect(screen, WHITE, right_paddle)

    if not game_over:
        pygame.draw.ellipse(screen, WHITE, ball)

    # WIN OVERLAY (NO BLACK SCREEN)
    if game_over:
        text = big_font.render(winner_text, True, YELLOW)
        text_rect = text.get_rect(center=(WIDTH // 2, HUD_HEIGHT + GAME_HEIGHT // 2))

        box_rect = text_rect.inflate(80, 50)

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

        screen.blit(text, text_rect)

    pygame.display.flip()

pygame.quit()
sys.exit()