"""Claude Agent SDK Hello World.

This agent uses the Claude Agent SDK to have intelligent conversations.
It can read/write files, run commands, and maintains context across turns.

Telemetry (traces, metrics, log correlation) is automatically configured
by AgentServer. Control via environment variables:
- TERMINALUSE_TELEMETRY=false: Disable telemetry entirely
- TERMINALUSE_AUTO_INSTRUMENT=false: Disable auto-instrumentation (manual spans only)
"""

from typing import Any

from claude_agent_sdk import ClaudeAgentOptions, query
from claude_agent_sdk.types import ResultMessage
from terminaluse.lib import (
    AgentServer,
    TaskContext,
    make_logger,
)
from terminaluse.types import Event
from terminaluse.types.task_message_content import TaskMessageContent_Text

logger = make_logger(__name__)

# Create an agent server - telemetry is automatically configured
server = AgentServer()


@server.on_create
async def handle_create(ctx: TaskContext, params: dict[str, Any]):
    """Handle task creation."""
    # Initialize state - session_id will be set after first query
    await ctx.state.create(
        state={
            "session_id": None,
        },
    )


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

    Routes messages to Claude and streams responses back.
    """
    try:
        # Parse user message
        if not isinstance(event.content, TaskMessageContent_Text):
            raise ValueError("Unsupported message type. Only text messages are supported.")
        user_message = event.content.content

        # Get state for to get the session ID
        state = await ctx.state.get()
        session_id = state.get("session_id") if state else None

        # Configure Claude Agent SDK
        options = ClaudeAgentOptions(
            include_partial_messages=True,  # enable streaming
            permission_mode="bypassPermissions",
            cwd="/workspace",
            extra_args={"debug-to-stderr": None},
            allowed_tools=["Skill", "Read", "Write", "Bash", "Edit", "Grep", "Glob"],
            resume=session_id,  # Resume previous session if exists
        )

        # Query Claude and stream responses
        async for message in query(prompt=user_message, options=options):
            await ctx.messages.send(message)

            # Save session ID for continuity
            if isinstance(message, ResultMessage):
                await ctx.state.update({"session_id": message.session_id})

    except Exception as e:
        error_msg = str(e)
        await ctx.messages.send(f"Sorry, I encountered an error: {error_msg}")


@server.on_cancel
async def handle_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}")
