# Miku UNO Bot Integration - Setup Guide

## Overview
Miku can now play UNO using a combination of:
- **Playwright**: Headless browser automation to join and play the game
- **LLM Integration**: Strategic decision-making with Miku's personality
- **Discord Commands**: Easy interface for starting/joining games

## Files Created
1. `bot/commands/uno.py` - Discord command handler
2. `bot/utils/uno_game.py` - Core game automation (MikuUnoPlayer class)
3. `bot/bot.py` - Updated to route !uno commands

## Prerequisites

### 1. Install Playwright Browsers
Playwright requires browser binaries to be installed:

```bash
# Inside the bot container or virtual environment
python -m playwright install chromium
```

Or if you need all browsers:
```bash
python -m playwright install
```

### 2. Verify UNO Server is Running
Make sure both UNO game servers are running:
```bash
# Terminal 1 - Backend (port 5000)
cd /home/koko210Serve/docker/uno-online
node server.js

# Terminal 2 - Frontend (port 3002)
cd /home/koko210Serve/docker/uno-online/client
npm start
```

## Discord Commands

### Create a New Game
```
!uno create
```
- Miku creates a new UNO room and joins as Player 2
- Returns room code for you to join
- Automatically starts playing when you join

### Join an Existing Game
```
!uno join ABC123
```
- Miku joins room ABC123 as Player 2
- Starts playing automatically

### List Active Games
```
!uno list
```
- Shows all active UNO games Miku is currently playing

### Quit a Game
```
!uno quit ABC123
```
- Makes Miku leave the specified game

### Help
```
!uno help
```
- Shows all available UNO commands

## How It Works

### Game Flow
1. **User sends command**: `!uno create` or `!uno join <code>`
2. **Playwright launches**: Headless Chromium browser opens
3. **Navigation**: Bot navigates to game URL (http://192.168.1.2:3002)
4. **Join room**: Enters room code and joins as Player 2
5. **Game loop starts**: Polls game state every 2 seconds
6. **Turn detection**: Checks if it's Miku's turn
7. **LLM decision**: Prompts Miku's LLM with game state for strategy
8. **Action execution**: Sends JSON action to game via HTTP API
9. **Trash talk**: Sends personality-driven message to Discord
10. **Repeat**: Loop continues until game ends

### LLM Strategy System
When it's Miku's turn, the bot:
1. Gets current game state (hand, top card, opponent cards)
2. Builds a strategic prompt with:
   - Current game situation
   - Available cards in hand
   - Strategic advice (color matching, special cards, etc.)
   - JSON format requirements
3. Gets Miku's decision from LLM
4. Validates and executes the action

### Personality Integration
Miku trash talks based on card type:
- **Draw 4**: "Take four cards! 💙✨ I hope you're ready for a comeback~"
- **Draw 2**: "Draw two cards! Don't worry, I still believe in you~ ✨"
- **Skip**: "Sorry~ Skipping your turn! Maybe next time? 🎶"
- **Wild**: "I'm changing the color! Let's see how you handle this~ 💫"
- **Regular cards**: "Playing my card~ Let's keep this fun! 🎵"

## Configuration

### Server URLs
Located in `bot/utils/uno_game.py`:
```python
UNO_SERVER_URL = "http://localhost:5000"  # Backend API
UNO_CLIENT_URL = "http://192.168.1.2:3002"  # Frontend URL
```

Adjust these if your setup is different.

### Polling Interval
Game state is checked every 2 seconds:
```python
POLL_INTERVAL = 2  # seconds
```

You can adjust this in `uno_game.py` if needed.

## Testing

### 1. Quick Test
```bash
# Start both UNO servers first

# In Discord, type:
!uno create

# You'll get a response like:
# "🎮 Created UNO room: ABC123
#  Join at: http://192.168.1.2:3002
#  I'm joining now as Player 2! ✨"

# Open that URL in your browser and join
# Miku will start playing automatically
```

### 2. Check Logs
Watch bot logs for:
- `[UNO]` - Game actions and status
- `[MikuUnoPlayer]` - Detailed game loop info
- LLM prompts and responses
- Trash talk messages

### 3. Manual Testing
You can still test the JSON action API directly:
```bash
# Get game state
curl http://localhost:5000/api/game/ABC123/state | jq

# Send bot action
node test-bot-action.js ABC123 '{"action":"draw"}'
```

## Troubleshooting

### Browser Not Found
**Error**: `playwright._impl._api_types.Error: Executable doesn't exist`

**Solution**:
```bash
python -m playwright install chromium
```

### Bot Not Responding to Commands
**Check**:
1. Is bot.py running?
2. Check bot logs for errors
3. Try `!uno help` to verify command is loaded

### Game Not Starting
**Check**:
1. Are both UNO servers running? (ports 5000 and 3002)
2. Can you access http://192.168.1.2:3002 in browser?
3. Check server logs for errors

### Miku Not Making Moves
**Check**:
1. Is it actually Miku's turn? (Player 2)
2. Check bot logs for LLM errors
3. Verify game state is being fetched correctly
4. Check if LLM is returning valid JSON

### Invalid JSON from LLM
The bot validates LLM output. If invalid:
- Bot will log the error
- May attempt to draw a card as fallback
- Check LLM prompt in `build_strategy_prompt()`

## Architecture

### HTTP API (Game Server)
- `GET /api/game/:roomCode/state` - Get game state
- `POST /api/game/:roomCode/action` - Send bot action

### WebSocket Events (Optional)
- `botActionReceived` - Triggers action execution in client
- Not currently used by Playwright approach

### Playwright Automation
- Headless Chromium browser
- Navigates to game URL
- No actual UI interaction needed (uses HTTP API)
- Browser is just for joining the room

## Future Enhancements

### Discord Activity Integration (Phase 2)
After testing is complete, we can convert this to a proper Discord Activity:
1. Package as Discord Activity
2. Use Discord's activity APIs
3. Embed directly in Discord
4. No external browser needed

### Improvements
- [ ] Better error recovery
- [ ] Multiple concurrent games
- [ ] Difficulty levels (aggressive vs casual play)
- [ ] Statistics tracking
- [ ] Tournament mode

## Documentation References
- `BOT_ACTION_SPEC.md` - JSON action format specification
- `QUICK_START_BOT.md` - Quick start for manual testing
- `BOT_INTEGRATION_COMPLETE.md` - Full integration details

## Need Help?
Check the logs first:
```bash
# Bot logs
tail -f bot.log

# UNO server logs
# (in terminal where server.js is running)
```

Look for `[UNO]` or `[MikuUnoPlayer]` tags for game-specific logs.
