#!/usr/bin/env python3
"""
Battleships Agent - Python Implementation
Implements the full protocol with stateful ship placement.
"""
import sys
import random

# =============================================================================
# State
# =============================================================================

already_fired = set()

ships_to_place = [
    "PLACE C A1 N",   # Carrier (5 cells)
    "PLACE B C1 N",   # Battleship 1 (4 cells)
    "PLACE B E1 N",   # Battleship 2 (4 cells)
    "PLACE D G1 N",   # Destroyer 1 (3 cells)
    "PLACE D I1 N",   # Destroyer 2 (3 cells)
    "PLACE P A7 D",   # Patrol 1 (2 cells)
    "PLACE P A9 D",   # Patrol 2 (2 cells)
    "PLACE P H8 N",   # Patrol 3 (2 cells)
]

current_ship_index = 0
preparation_done = False

# =============================================================================
# Command Detection
# =============================================================================

def starts_with(line: str, prefix: str) -> bool:
    """Check if line starts with the given prefix."""
    return line.startswith(prefix)

# =============================================================================
# Actions
# =============================================================================

def send(message: str):
    """Send a message to the server."""
    print(message)
    sys.stdout.flush()

def place_next_ship():
    """Place the next ship in the queue."""
    global current_ship_index
    if current_ship_index < len(ships_to_place):
        send(ships_to_place[current_ship_index])

def fire_random():
    """Fire at a random position not yet fired."""
    while True:
        row = random.randint(1, 10)
        row_char = chr(65 + row - 1)  # A-J
        column = random.randint(1, 10)
        pos = f"{row_char}{column}"
        if pos not in already_fired:
            break
    send(f"FIRE {pos}")
    already_fired.add(pos)

# =============================================================================
# Command Handlers
# =============================================================================

def handle_game_started():
    """Handle GAME STARTED message - start placing ships."""
    global current_ship_index, preparation_done
    current_ship_index = 0
    preparation_done = False
    place_next_ship()

def handle_ok():
    """Handle OK response from server."""
    global current_ship_index, preparation_done
    if preparation_done:
        return
    
    current_ship_index += 1
    if current_ship_index < len(ships_to_place):
        place_next_ship()
    elif current_ship_index == len(ships_to_place):
        send("READY")
    else:
        preparation_done = True

def handle_your_turn():
    """Handle YOUR TURN message - fire at enemy."""
    fire_random()

def handle_game_over():
    """Handle GAME OVER message - exit program."""
    sys.exit(0)

def handle_you_won():
    """Handle YOU WON message - exit program."""
    sys.exit(0)

def handle_ko(line: str):
    """Handle KO (error) response from server."""
    print(f"Error: {line}", file=sys.stderr)

# =============================================================================
# Main Loop
# =============================================================================

def process_line(line: str):
    """Process a single line from stdin."""
    line = line.rstrip('\n')
    
    if starts_with(line, "GAME STARTED"):
        handle_game_started()
    elif starts_with(line, "YOUR TURN"):
        handle_your_turn()
    elif starts_with(line, "GAME OVER"):
        handle_game_over()
    elif starts_with(line, "YOU WON"):
        handle_you_won()
    elif starts_with(line, "OK"):
        handle_ok()
    elif starts_with(line, "KO"):
        handle_ko(line)

def main():
    """Main entry point."""
    try:
        for line in sys.stdin:
            process_line(line)
    except KeyboardInterrupt:
        pass
    sys.exit(0)

if __name__ == "__main__":
    main()
