"""Client mode adapter - only supports builtin, registered, and system commands"""

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


class ClientAdapter:
    """Client mode adapter - minimal implementation
    
    Supports:
    - Builtin commands (/help, /exit, /time, etc.)
    - Registered commands (from CommandModel)
    - System commands (shell execution)
    """

    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, RegisteredExecutor, SystemExecutor
            )
            from diona.project.cli.engine.engine import CommandExecutor
            
            self._executor = CommandExecutor()
            self._executor.register(BuiltinExecutor())
            self._executor.register(RegisteredExecutor())
            self._executor.register(SystemExecutor())
        return self._executor

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


_adapter: "ClientAdapter" = None


def get_client_adapter() -> ClientAdapter:
    global _adapter
    if _adapter is None:
        _adapter = ClientAdapter()
    return _adapter
