# AeThex API Reference

Complete reference for AeThex-specific features and APIs.

## Table of Contents

- [Cloud Services](#cloud-services)
- [AI Assistant](#ai-assistant)
- [Studio Bridge](#studio-bridge)
- [Multiplayer](#multiplayer)
- [Authentication](#authentication)
- [Cloud Saves](#cloud-saves)
- [Analytics](#analytics)

---

## Cloud Services

### AeThexCloud Singleton

Global singleton for all cloud operations.

```gdscript
# Available everywhere as 'AeThexCloud'
var cloud = AeThexCloud
```

#### Methods

##### `connect_to_cloud() -> bool`
Establish connection to AeThex cloud services.

```gdscript
func _ready():
    if AeThexCloud.connect_to_cloud():
        print("Connected to cloud!")
    else:
        print("Connection failed")
```

**Returns:** `true` if connection successful

---

##### `get_connection_status() -> String`
Get current cloud connection status.

```gdscript
var status = AeThexCloud.get_connection_status()
# Returns: "connected", "disconnected", "connecting", "error"
```

---

##### `disconnect_from_cloud()`
Disconnect from cloud services.

```gdscript
func _exit_tree():
    AeThexCloud.disconnect_from_cloud()
```

---

## Multiplayer

### Quick Setup (3 Lines)

```gdscript
extends Node

func _ready():
    # That's it - multiplayer is ready!
    AeThexMultiplayer.create_room("my-game-room")
    AeThexMultiplayer.connect("player_joined", self, "_on_player_joined")
    AeThexMultiplayer.connect("player_left", self, "_on_player_left")

func _on_player_joined(player_id: int):
    print("Player %d joined!" % player_id)
    
func _on_player_left(player_id: int):
    print("Player %d left" % player_id)
```

### AeThexMultiplayer Singleton

#### Methods

##### `create_room(room_name: String, max_players: int = 8) -> bool`
Create a new multiplayer room.

```gdscript
var success = AeThexMultiplayer.create_room("lobby-1", 4)
if success:
    print("Room created! Code:", AeThexMultiplayer.get_room_code())
```

**Parameters:**
- `room_name` - Unique room identifier
- `max_players` - Maximum players allowed (default: 8)

**Returns:** `true` if room created successfully

---

##### `join_room(room_code: String) -> bool`
Join an existing room using a room code.

```gdscript
func join_clicked():
    var code = $RoomCodeInput.text
    if AeThexMultiplayer.join_room(code):
        get_tree().change_scene("res://game.tscn")
```

**Returns:** `true` if join successful

---

##### `get_room_code() -> String`
Get the current room's join code.

```gdscript
var code = AeThexMultiplayer.get_room_code()
$CodeLabel.text = "Code: " + code
```

---

##### `leave_room()`
Leave current multiplayer session.

```gdscript
func quit_to_menu():
    AeThexMultiplayer.leave_room()
    get_tree().change_scene("res://menu.tscn")
```

---

##### `get_players() -> Array`
Get list of all players in room.

```gdscript
var players = AeThexMultiplayer.get_players()
for player in players:
    print("Player ID:", player.id)
    print("Username:", player.username)
    print("Is Ready:", player.is_ready)
```

**Returns:** Array of player dictionaries with:
- `id` (int) - Unique player ID
- `username` (String) - Display name
- `is_ready` (bool) - Ready status
- `ping` (int) - Latency in ms

---

##### `send_message(type: String, data: Dictionary)`
Send custom message to all players.

```gdscript
func shoot_projectile(position: Vector2, direction: Vector2):
    AeThexMultiplayer.send_message("projectile_spawn", {
        "position": position,
        "direction": direction,
        "owner_id": get_tree().get_network_unique_id()
    })
```

---

#### Signals

##### `player_joined(player_id: int)`
Emitted when a player joins the room.

```gdscript
func _on_player_joined(player_id):
    var player_node = spawn_player(player_id)
    $PlayersNode.add_child(player_node)
```

---

##### `player_left(player_id: int)`
Emitted when a player leaves.

```gdscript
func _on_player_left(player_id):
    var player = $PlayersNode.get_node(str(player_id))
    if player:
        player.queue_free()
```

---

##### `room_closed()`
Emitted when room host closes the room.

```gdscript
func _on_room_closed():
    show_message("Host closed the room")
    get_tree().change_scene("res://menu.tscn")
```

---

##### `message_received(from_id: int, type: String, data: Dictionary)`
Emitted when custom message is received.

```gdscript
func _on_message_received(from_id, type, data):
    match type:
        "projectile_spawn":
            spawn_projectile(data.position, data.direction)
        "chat_message":
            add_chat_message(data.username, data.text)
```

---

### RPC Alternative

Standard RPC syntax works automatically with AeThex multiplayer:

```gdscript
# Define synchronized variable
puppet var position = Vector2()

# Call remote function
rpc("update_position", global_position)

# Remote function
remote func update_position(new_pos):
    position = new_pos
```

---

## Authentication

### AeThexAuth Singleton

#### Methods

##### `login_with_email(email: String, password: String) -> Dictionary`
Login with email and password.

```gdscript
func login_clicked():
    var result = await AeThexAuth.login_with_email(
        $EmailInput.text,
        $PasswordInput.text
    )
    
    if result.success:
        print("Logged in as:", result.user.username)
        get_tree().change_scene("res://menu.tscn")
    else:
        $ErrorLabel.text = result.error
```

**Returns:** Dictionary with:
- `success` (bool)
- `user` (Dictionary) - User info if successful
- `error` (String) - Error message if failed

---

##### `login_as_guest() -> Dictionary`
Create temporary guest account.

```gdscript
func play_as_guest():
    var result = await AeThexAuth.login_as_guest()
    if result.success:
        start_game()
```

---

##### `login_with_google() -> Dictionary`
OAuth login with Google.

```gdscript
func google_login_clicked():
    var result = await AeThexAuth.login_with_google()
    if result.success:
        start_game()
```

---

##### `register(email: String, password: String, username: String) -> Dictionary`
Create new account.

```gdscript
func register_clicked():
    var result = await AeThexAuth.register(
        $EmailInput.text,
        $PasswordInput.text,
        $UsernameInput.text
    )
    
    if result.success:
        print("Account created!")
    else:
        show_error(result.error)
```

---

##### `logout()`
Log out current user.

```gdscript
func logout_clicked():
    AeThexAuth.logout()
    get_tree().change_scene("res://login.tscn")
```

---

##### `get_current_user() -> Dictionary`
Get currently logged in user.

```gdscript
var user = AeThexAuth.get_current_user()
if user:
    $UsernameLabel.text = user.username
    $AvatarTexture.texture = load_avatar(user.avatar_url)
```

**Returns:** Dictionary with:
- `id` (String) - User ID
- `username` (String) - Display name
- `email` (String) - Email address
- `avatar_url` (String) - Avatar image URL
- `is_guest` (bool) - Whether guest account

---

##### `is_logged_in() -> bool`
Check if user is logged in.

```gdscript
func _ready():
    if not AeThexAuth.is_logged_in():
        get_tree().change_scene("res://login.tscn")
```

---

## Cloud Saves

### AeThexSaves Singleton

Automatic cloud save synchronization.

#### Methods

##### `save_game(slot: String, data: Dictionary) -> bool`
Save game data to cloud.

```gdscript
func save_game():
    var save_data = {
        "level": current_level,
        "health": player.health,
        "inventory": player.inventory,
        "position": {
            "x": player.position.x,
            "y": player.position.y
        }
    }
    
    if AeThexSaves.save_game("slot_1", save_data):
        print("Game saved!")
    else:
        print("Save failed")
```

**Parameters:**
- `slot` - Save slot name (e.g., "slot_1", "autosave")
- `data` - Dictionary of game data (auto-serialized)

**Returns:** `true` if save successful

---

##### `load_game(slot: String) -> Dictionary`
Load game data from cloud.

```gdscript
func load_game():
    var data = await AeThexSaves.load_game("slot_1")
    
    if data:
        current_level = data.level
        player.health = data.health
        player.inventory = data.inventory
        player.position = Vector2(data.position.x, data.position.y)
        print("Game loaded!")
    else:
        print("No save found")
```

**Returns:** Dictionary with save data, or `null` if not found

---

##### `get_save_slots() -> Array`
List all available save slots.

```gdscript
func show_load_menu():
    var slots = await AeThexSaves.get_save_slots()
    
    for slot in slots:
        var button = SaveSlotButton.new()
        button.text = slot.name
        button.metadata = slot.timestamp
        $SavesList.add_child(button)
```

**Returns:** Array of dictionaries with:
- `name` (String) - Slot name
- `timestamp` (int) - Unix timestamp
- `size_bytes` (int) - Save file size

---

##### `delete_save(slot: String) -> bool`
Delete a save slot.

```gdscript
func delete_clicked():
    if AeThexSaves.delete_save("slot_1"):
        print("Save deleted")
```

---

##### `set_auto_save(enabled: bool, interval: float = 60.0)`
Configure automatic saving.

```gdscript
func _ready():
    # Auto-save every 2 minutes
    AeThexSaves.set_auto_save(true, 120.0)
```

**Parameters:**
- `enabled` - Whether auto-save is active
- `interval` - Seconds between auto-saves (default: 60)

---

#### Signals

##### `save_completed(slot: String)`
Emitted when save finishes.

```gdscript
func _ready():
    AeThexSaves.connect("save_completed", self, "_on_save_done")

func _on_save_done(slot):
    show_notification("Game saved!")
```

---

##### `sync_started()`
Emitted when cloud sync begins.

```gdscript
func _on_sync_started():
    $SyncIndicator.visible = true
```

---

##### `sync_completed()`
Emitted when cloud sync finishes.

```gdscript
func _on_sync_completed():
    $SyncIndicator.visible = false
```

---

## AI Assistant

### AeThexAI Singleton

In-game AI help and code generation.

#### Methods

##### `ask_question(question: String) -> String`
Get AI answer to a question.

```gdscript
func help_button_clicked():
    var answer = await AeThexAI.ask_question(
        "How do I add a jump mechanic?"
    )
    $HelpText.text = answer
```

---

##### `generate_code(prompt: String, language: String = "gdscript") -> String`
Generate code from description.

```gdscript
func generate_clicked():
    var code = await AeThexAI.generate_code(
        "Create a health bar that decreases when player takes damage",
        "gdscript"
    )
    $CodeEditor.text = code
```

**Parameters:**
- `prompt` - Description of desired code
- `language` - "gdscript", "csharp", or "cpp"

---

##### `explain_code(code: String) -> String`
Get explanation of code.

```gdscript
func explain_clicked():
    var explanation = await AeThexAI.explain_code($CodeEditor.text)
    $ExplanationLabel.text = explanation
```

---

##### `suggest_fix(error_message: String, code: String) -> String`
Get suggestion for fixing an error.

```gdscript
func _on_error_occurred(error):
    var fix = await AeThexAI.suggest_fix(error, $CodeEditor.text)
    show_suggestion_popup(fix)
```

---

## Analytics

### AeThexAnalytics Singleton

Track game events and player behavior.

#### Methods

##### `track_event(event_name: String, properties: Dictionary = {})`
Log custom event.

```gdscript
func level_completed():
    AeThexAnalytics.track_event("level_complete", {
        "level": current_level,
        "time_seconds": level_time,
        "score": player_score
    })
```

---

##### `track_screen(screen_name: String)`
Track screen view.

```gdscript
func _ready():
    AeThexAnalytics.track_screen("main_menu")
```

---

##### `set_user_property(key: String, value)`
Set user attribute.

```gdscript
func _ready():
    AeThexAnalytics.set_user_property("player_level", 5)
    AeThexAnalytics.set_user_property("vip_status", true)
```

---

## Studio Bridge

### AeThexStudio Singleton

Communicate with Studio IDE.

#### Methods

##### `send_to_studio(command: String, args: Dictionary = {})`
Send command to Studio.

```gdscript
func debug_node():
    AeThexStudio.send_to_studio("highlight_node", {
        "path": get_path()
    })
```

---

##### `log_message(message: String, type: String = "info")`
Send log message to Studio console.

```gdscript
func custom_log(msg):
    AeThexStudio.log_message(msg, "debug")
    # Types: "info", "warning", "error", "debug"
```

---

## Environment Variables

Configure AeThex through environment variables:

```bash
# Cloud API endpoint
export AETHEX_API_URL="https://api.aethex.games"

# Disable cloud features
export AETHEX_OFFLINE_MODE="true"

# Studio connection
export AETHEX_STUDIO_PORT="9002"

# Debug logging
export AETHEX_DEBUG="true"
```

Or in project settings:

```gdscript
# project.godot
[aethex]
api_url="https://api.aethex.games"
offline_mode=false
studio_port=9002
debug_mode=false
```

---

## Error Codes

Common error codes and solutions:

| Code | Meaning | Solution |
|------|---------|----------|
| `CLOUD_001` | Connection timeout | Check internet connection |
| `CLOUD_002` | Authentication failed | Re-login required |
| `CLOUD_003` | Rate limit exceeded | Wait and retry |
| `MP_001` | Room full | Join different room |
| `MP_002` | Invalid room code | Check code and retry |
| `SAVE_001` | Save quota exceeded | Delete old saves |
| `AUTH_001` | Invalid credentials | Check email/password |
| `AUTH_002` | Account exists | Use different email |

---

## Best Practices

### Connection Management
```gdscript
func _ready():
    # Always check connection before cloud operations
    if not AeThexCloud.is_connected():
        AeThexCloud.connect_to_cloud()
        await AeThexCloud.connection_established
```

### Error Handling
```gdscript
func save_game():
    var result = AeThexSaves.save_game("slot_1", data)
    if not result:
        # Fallback to local save
        save_locally(data)
```

### Multiplayer State Sync
```gdscript
# Use @rpc for automatic synchronization
@rpc("any_peer", "reliable")
func update_position(pos: Vector2):
    position = pos

func _physics_process(delta):
    if is_multiplayer_master():
        rpc("update_position", position)
```

---

## See Also

- [Getting Started Guide](../GETTING_STARTED.md)
- [Cloud Services Architecture](CLOUD_SERVICES_ARCHITECTURE.md)
- [Multiplayer Pong Tutorial](tutorials/FIRST_GAME_TUTORIAL.md)
- [Studio Bridge Guide](STUDIO_BRIDGE_GUIDE.md)
