"""
2048 Game - CLI Interface
"""
import sys
import os
import pickle
from .game import Game2048

# ANSI color codes
COLORS = {
    0: '\033[0m',       # Reset
    2: '\033[93m',      # Yellow
    4: '\033[92m',      # Green
    8: '\033[96m',      # Cyan
    16: '\033[94m',     # Blue
    32: '\033[95m',     # Magenta
    64: '\033[91m',     # Red
    128: '\033[93;1m',  # Bright Yellow
    256: '\033[92;1m',  # Bright Green
    512: '\033[96;1m',  # Bright Cyan
    1024: '\033[94;1m', # Bright Blue
    2048: '\033[95;1m', # Bright Magenta
}

def clear_screen():
    """Clear the terminal screen"""
    os.system('cls' if os.name == 'nt' else 'clear')

def get_color(value):
    """Get color for a tile value"""
    return COLORS.get(value, '\033[97;1m')  # White for unknown values

def print_grid(game):
    """Print the game grid with colors"""
    grid = game.get_grid()
    score = game.get_score()
    
    print(f"\n{'='*30}")
    print(f"  SCORE: {score}")
    print(f"{'='*30}\n")
    
    # Find max width for alignment
    max_val = max(max(row) for row in grid)
    max_width = max(4, len(str(max_val)))
    
    # Print grid
    for row in grid:
        print('+', end='')
        for _ in row:
            print(f'{"-" * (max_width + 2)}+', end='')
        print()
        
        print('|', end='')
        for cell in row:
            color = get_color(cell)
            reset = '\033[0m'
            if cell == 0:
                print(f' {color}{" "*max_width}{reset} |', end='')
            else:
                print(f' {color}{cell:^{max_width}}{reset} |', end='')
        print()
    
    print('+', end='')
    for _ in grid[0]:
        print(f'{"-" * (max_width + 2)}+', end='')
    print()

def print_help():
    """Print help message"""
    print("\nControls:")
    print("  W/↑ - Move Up")
    print("  S/↓ - Move Down")
    print("  A/← - Move Left")
    print("  D/→ - Move Right")
    print("  Q   - Quit")
    print("  N   - New Game")
    print("  H   - Help")

def get_key():
    """Get a single key press (cross-platform)"""
    try:
        import tty
        import termios
        import select
        
        # Unix/Linux/Mac
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setcbreak(sys.stdin.fileno())
            if select.select([sys.stdin], [], [], 0.1)[0]:
                return sys.stdin.read(1)
            return None
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    except ImportError:
        # Windows
        import msvcrt
        if msvcrt.kbhit():
            return msvcrt.getch().decode('utf-8')
        return None

def play_game():
    """Main game loop"""
    game = Game2048()
    
    try:
        while True:
            clear_screen()
            print("\n" + "="*30)
            print("         2048 GAME")
            print("="*30)
            print_grid(game)
            
            if game.has_won():
                print("\n🎉 CONGRATULATIONS! You reached 2048! 🎉")
                print("Continue playing to get higher score!")
            
            if game.is_game_over():
                print("\n💥 GAME OVER! 💥")
                print(f"Final Score: {game.get_score()}")
                choice = input("\nPlay again? (y/n): ").lower()
                if choice == 'y':
                    game = Game2048()
                    continue
                else:
                    break
            
            print_help()
            
            # Get user input
            try:
                move = input("\nYour move: ").lower().strip()
            except (EOFError, KeyboardInterrupt):
                print("\n\nThanks for playing!")
                break
            
            moved = False
            
            if move in ['w', 'k', '8']:
                moved = game.move_up()
            elif move in ['s', 'j', '2']:
                moved = game.move_down()
            elif move in ['a', 'h', '4']:
                moved = game.move_left()
            elif move in ['d', 'l', '6']:
                moved = game.move_right()
            elif move == 'q':
                print("\nThanks for playing!")
                break
            elif move == 'n':
                game = Game2048()
            elif move == 'h':
                input("\nPress Enter to continue...")
            else:
                print("\nInvalid move! Press H for help.")
                input("Press Enter to continue...")
    
    except KeyboardInterrupt:
        print("\n\nGame interrupted. Thanks for playing!")

def main():
    """Entry point"""
    print("Welcome to 2048!")
    print("A Python implementation of the classic 2048 game.")
    play_game()

if __name__ == '__main__':
    main()
