"""Agent mode adapter - only supports builtin commands and agent dialogue"""

import asyncio
from typing import AsyncIterator
from diona.project.cli.engine.parser import get_input_parser
from diona.project.cli.engine.result import StreamChunk, InputType, ParsedInput


class AgentAdapter:
    """Agent mode adapter - minimal implementation
    
    Supports:
    - Builtin commands (/help, /exit, etc.)
    - Agent dialogue (non-command input sent to AI agent)
    """

    def __init__(self):
        self._parser = None
        self._executor = None

    def _get_parser(self):
        if self._parser is None:
            self._parser = get_input_parser()
        return self._parser

    def _get_executor(self):
        if self._executor is None:
            from diona.project.cli.commands.executor import BuiltinExecutor, AgentExecutor
            from diona.project.cli.engine.engine import CommandExecutor
            
            self._executor = CommandExecutor()
            self._executor.register(BuiltinExecutor())
            self._executor.register(AgentExecutor())
        return self._executor

    async def execute(self, user_input: str) -> AsyncIterator[StreamChunk]:
        if user_input.startswith("/"):
            parser = self._get_parser()
            executor = self._get_executor()
            parsed = parser.parse(user_input)
            async for chunk in executor.execute(parsed):
                yield chunk
            return

        executor = self._get_executor()
        parsed = ParsedInput(
            raw_input=user_input,
            input_type=InputType.AGENT,
            command_name="agent",
            args=[]
        )
        async for chunk in executor.execute(parsed):
            yield chunk


_adapter: "AgentAdapter" = None


def get_agent_adapter() -> AgentAdapter:
    global _adapter
    if _adapter is None:
        _adapter = AgentAdapter()
    return _adapter
