import os
from typing import Any

from terminaluse.lib.sdk.agent_server import AgentServer
from terminaluse.lib.types.task_context import TaskContext
from terminaluse.lib.utils.logging import make_logger
from terminaluse.types.event import Event

logger = make_logger(__name__)

# Capture version ID at module load time for version routing tests
VERSION_ID = os.environ.get("TERMINALUSE_VERSION_ID", "local")


# Create an agent server
# This sets up the core server that handles task creation, events, and cancellation
server = AgentServer()


@server.on_event
async def handle_event(ctx: TaskContext, event: Event):
    """Handle incoming messages from users.

    This is where you implement your main agent logic.
    """
    logger.info(f"Received message: {event}")

    # Send a response with version ID for version routing tests
    await ctx.messages.send(f"[VERSION: {VERSION_ID}]\n\nHello! I've received your message.")


@server.on_cancel
async def handle_task_cancel(ctx: TaskContext):
    """Handle task cancellation.

    Clean up any resources or state when a task is cancelled.
    """
    logger.info(f"Task cancelled: {ctx.task.id}")


@server.on_create
async def handle_task_create(ctx: TaskContext, params: dict[str, Any]):
    """Handle task creation.

    Initialize any state or resources needed for the task.
    """
    logger.info(f"Task created: {ctx.task.id}")
