"""Natural language intent parsing for King's commands.

The ChatHandler takes freeform messages from the King and interprets them
as structured API actions.  It leverages Grukk's system prompt (via the
Claude Agent SDK) for understanding but provides a structured output
interface for the agent loop.

In the current implementation the ChatHandler is a simple passthrough:
it logs the King's message and returns it for the Agent SDK session in
``agent.py`` to handle the actual NL understanding.  The intent enum and
ChatResponse dataclass are retained so that future deterministic routing
can be layered on top.
"""

from __future__ import annotations

import logging
from dataclasses import dataclass, field
from enum import Enum
from typing import Any

from peon_mcp.grukk.api import GrukkAPIClient

log = logging.getLogger("peon-grukk")


class IntentType(Enum):
    """Recognized intent categories from the King's messages."""

    # Project management
    LIST_PROJECTS = "list_projects"
    GET_PROJECT_STATUS = "get_project_status"
    CREATE_FEATURE = "create_feature"
    LIST_FEATURES = "list_features"

    # Task management
    LIST_TASKS = "list_tasks"
    CREATE_TASK = "create_task"
    UPDATE_TASK = "update_task"
    CANCEL_TASK = "cancel_task"

    # Loop management
    CHECK_LOOPS = "check_loops"
    PAUSE_LOOP = "pause_loop"
    RESUME_LOOP = "resume_loop"
    RESTART_LOOP = "restart_loop"

    # Information queries
    GET_LOGS = "get_logs"
    GET_HEARTBEATS = "get_heartbeats"

    # Meta
    CLARIFICATION_NEEDED = "clarification_needed"
    UNKNOWN = "unknown"


@dataclass
class ChatResponse:
    """Structured response from processing a King's message."""

    intent: IntentType
    parameters: dict[str, Any] = field(default_factory=dict)
    grukk_message: str = ""
    api_calls_made: list[str] = field(default_factory=list)
    success: bool = True
    error: str | None = None


class ChatHandler:
    """Routes King's natural language commands to Grukk's Agent SDK session.

    The ChatHandler is the bridge between the polling loop and the NL
    processing layer.  For now it acts as a passthrough: it logs the
    message, records it via the API, and returns a ``ChatResponse`` with
    intent ``UNKNOWN`` so the caller knows to forward to the Agent SDK
    for full NL understanding.

    Parameters
    ----------
    client:
        :class:`GrukkAPIClient` instance for API access.
    """

    def __init__(self, client: GrukkAPIClient) -> None:
        self.client = client

    async def handle_message(self, message: str) -> ChatResponse:
        """Log a King's message and return it for Agent SDK processing.

        Parameters
        ----------
        message:
            Raw natural language message from the King.

        Returns
        -------
        ChatResponse
            A response with intent ``UNKNOWN`` indicating the message needs
            Agent SDK processing.  The ``grukk_message`` field is left empty
            because the actual Grukk response will be generated by the Agent
            SDK session in ``agent.py``.
        """
        log.info("King says: %s", message)

        return ChatResponse(
            intent=IntentType.UNKNOWN,
            grukk_message="",
            success=True,
            parameters={"raw_message": message},
        )
