from typing import Dict, Any, List
from modules.llm.ollama_client import query_ollama
from ..tools.tool_executor import execute_tool

class Planner:
    def __init__(self):
        self.chat_history = []
        self.context = {}

    def receive_input(self, user_input: str) -> None:
        self._update_history(role='user', content=user_input)

    async def process(self) -> str:
        max_cycles = 5
        for _ in range(max_cycles):
            llm_response = await query_ollama(
                prompt=self.chat_history,
                context=self.context,
                agent_type='planner'
            )
            
            if '[ToolCall:' in llm_response:
                tool_result = await self._handle_tool_call(llm_response)
                self._update_context(tool_result)
            else:
                self._update_history(role='assistant', content=llm_response)
                return llm_response
        return "Maximum processing cycles reached"

    async def _handle_tool_call(self, response: str) -> Dict[str, Any]:
        tool_call = response.split('[ToolCall:')[1].split(']')[0].strip()
        tool_name, args = self._parse_tool_call(tool_call)
        result = await execute_tool(tool_name, args)
        self._update_history(role='tool', content=str(result))
        return result

    def _parse_tool_call(self, tool_call: str) -> tuple:
        return tool_call.split('(', 1)[0], eval(tool_call.split('(', 1)[1].rstrip(')'))

    def _update_history(self, role: str, content: str) -> None:
        self.chat_history.append({'role': role, 'content': content})

    def _update_context(self, tool_data: Dict[str, Any]) -> None:
        self.context.update(tool_data)