from .result import ParsedInput, InputType


class InputParser:
    def __init__(self):
        self._command_registry = None
    
    def _get_registry(self):
        from diona.project.cli.commands import get_command_registry
        if self._command_registry is None:
            self._command_registry = get_command_registry()
        return self._command_registry

    def _is_registered_command(self, command: str) -> bool:
        registry = self._get_registry()
        model = registry.get_model(command)
        return model is not None

    def parse(self, raw_input: str) -> ParsedInput:
        if not raw_input or not raw_input.strip():
            return ParsedInput(
                raw_input=raw_input,
                input_type=InputType.SYSTEM,
                command_name="",
                args=[],
                is_exit=False
            )
        
        parts = raw_input.strip().split()
        command = parts[0]
        args = parts[1:] if len(parts) > 1 else []
        
        if command.startswith("/"):
            command = command[1:]
            
            if command == "exit":
                return ParsedInput(
                    raw_input=raw_input,
                    input_type=InputType.BUILTIN,
                    command_name="exit",
                    args=args,
                    is_exit=True
                )
            
            registry = self._get_registry()
            if registry.has(command):
                return ParsedInput(
                    raw_input=raw_input,
                    input_type=InputType.BUILTIN,
                    command_name=command,
                    args=args
                )
            
            return ParsedInput(
                raw_input=raw_input,
                input_type=InputType.SYSTEM,
                command_name=command,
                args=args
            )
        
        if self._is_registered_command(command):
            return ParsedInput(
                raw_input=raw_input,
                input_type=InputType.REGISTERED,
                command_name=command,
                args=args
            )
        
        return ParsedInput(
            raw_input=raw_input,
            input_type=InputType.SYSTEM,
            command_name=command,
            args=args
        )


_parser = None


def get_input_parser() -> InputParser:
    global _parser
    if _parser is None:
        _parser = InputParser()
    return _parser
