"""
Skill: call_agents_parallel
Herramienta para invocar a DeepCoder y DeepResearcher en paralelo
"""
import os
import logging
from typing import Any
from rich.console import Console

logger = logging.getLogger(__name__)
console = Console()

RESEARCHER_RECURSION_LIMIT = int(os.getenv("RESEARCHER_RECURSION_LIMIT", "100"))

class TerminalUIProxy:
    def __init__(self, original_ui, panel_id):
        self.original_ui = original_ui
        self.panel_id = panel_id
        
    def __getattr__(self, name):
        return getattr(self.original_ui, name)
        
    def print_stream(self, text: str):
        if hasattr(self.original_ui, 'print_stream'):
            import inspect
            sig = inspect.signature(self.original_ui.print_stream)
            if 'panel_id' in sig.parameters:
                return self.original_ui.print_stream(text, panel_id=self.panel_id)
        return self.original_ui.print_stream(text)
        
    def write_stream_to_chat(self, content: str):
        if hasattr(self.original_ui, 'write_stream_to_chat'):
            import inspect
            sig = inspect.signature(self.original_ui.write_stream_to_chat)
            if 'panel_id' in sig.parameters:
                return self.original_ui.write_stream_to_chat(content, panel_id=self.panel_id)
        return self.original_ui.write_stream_to_chat(content)
        
    def update_live(self, renderable):
        if hasattr(self.original_ui, 'update_live'):
            import inspect
            sig = inspect.signature(self.original_ui.update_live)
            if 'panel_id' in sig.parameters:
                return self.original_ui.update_live(renderable, panel_id=self.panel_id)
        return self.original_ui.update_live(renderable)
        
    def print_message(self, message: str, style: str = "", is_user_message: bool = False, status: str = None, use_bubble: bool = False):
        if hasattr(self.original_ui, 'print_message'):
            import inspect
            sig = inspect.signature(self.original_ui.print_message)
            if 'panel_id' in sig.parameters:
                return self.original_ui.print_message(message, style, is_user_message, status, use_bubble, panel_id=self.panel_id)
        return self.original_ui.print_message(message, style, is_user_message, status, use_bubble)

    def print_tool_notification(self, tool_name: str, action_desc: str = ""):
        if hasattr(self.original_ui, 'print_tool_notification'):
            import inspect
            sig = inspect.signature(self.original_ui.print_tool_notification)
            if 'panel_id' in sig.parameters:
                return self.original_ui.print_tool_notification(tool_name, action_desc, panel_id=self.panel_id)
        return self.original_ui.print_tool_notification(tool_name, action_desc)

    def print_success_box(self, message: str, title: str = "Éxito"):
        if hasattr(self.original_ui, 'print_success_box'):
            import inspect
            sig = inspect.signature(self.original_ui.print_success_box)
            if 'panel_id' in sig.parameters:
                return self.original_ui.print_success_box(message, title, panel_id=self.panel_id)
        return self.original_ui.print_success_box(message, title)
        
    def print_error_box(self, message: str, title: str = "Error"):
        if hasattr(self.original_ui, 'print_error_box'):
            import inspect
            sig = inspect.signature(self.original_ui.print_error_box)
            if 'panel_id' in sig.parameters:
                return self.original_ui.print_error_box(message, title, panel_id=self.panel_id)
        return self.original_ui.print_error_box(message, title)

    def print_warning_box(self, message: str, title: str = "Advertencia"):
        if hasattr(self.original_ui, 'print_warning_box'):
            import inspect
            sig = inspect.signature(self.original_ui.print_warning_box)
            if 'panel_id' in sig.parameters:
                return self.original_ui.print_warning_box(message, title, panel_id=self.panel_id)
        return self.original_ui.print_warning_box(message, title)
        
    def update_terminal_output(self, tool_name: str, output: str, command: str = "", show_cursor: bool = None):
        if hasattr(self.original_ui, 'update_terminal_output'):
            import inspect
            sig = inspect.signature(self.original_ui.update_terminal_output)
            if 'panel_id' in sig.parameters:
                return self.original_ui.update_terminal_output(tool_name, output, command, show_cursor, panel_id=self.panel_id)
        return self.original_ui.update_terminal_output(tool_name, output, command, show_cursor)
        
    def stop_live(self):
        if hasattr(self.original_ui, 'stop_live'):
            import inspect
            sig = inspect.signature(self.original_ui.stop_live)
            if 'panel_id' in sig.parameters:
                return self.original_ui.stop_live(panel_id=self.panel_id)
        return self.original_ui.stop_live()

def call_agents_parallel(task_coder: str, task_researcher: str, llm_service: Any = None, terminal_ui: Any = None, interrupt_queue: Any = None, approval_handler: Any = None) -> str:
    """Invoca ambos agentes en paralelo"""
    from kogniterm.core.agents.deep_coder import create_deep_coder
    from kogniterm.core.agents.deep_researcher import create_deep_researcher
    from kogniterm.core.agent_state import AgentState
    from langchain_core.messages import HumanMessage
    import concurrent.futures

    console.print("\n[bold green]🤖 Iniciando agentes en PARALELO[/bold green]")
    
    ui_coder = TerminalUIProxy(terminal_ui, "live_display_coder")
    ui_researcher = TerminalUIProxy(terminal_ui, "live_display_researcher")
    
    agent_coder = create_deep_coder(llm_service, ui_coder, interrupt_queue)
    agent_researcher = create_deep_researcher(llm_service, ui_researcher, interrupt_queue)
    
    def run_coder():
        state = AgentState(messages=[HumanMessage(content=task_coder)])
        try:
            res = agent_coder.invoke(state, config={"recursion_limit": RESEARCHER_RECURSION_LIMIT})
            return f"RESULTADO DEEP CODER:\n{res['messages'][-1].content}"
        except Exception as e:
            return f"Error en Deep Coder: {e}"

    def run_researcher():
        state = AgentState(messages=[HumanMessage(content=task_researcher)])
        try:
            res = agent_researcher.invoke(state, config={"recursion_limit": RESEARCHER_RECURSION_LIMIT})
            return f"RESULTADO DEEP RESEARCHER:\n{res['messages'][-1].content}"
        except Exception as e:
            return f"Error en Deep Researcher: {e}"

    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
        f_coder = executor.submit(run_coder)
        f_res = executor.submit(run_researcher)
        
        result_coder = f_coder.result()
        result_res = f_res.result()

    # Consolidar: mover contenido de los paneles al chat log y ocultarlos
    if hasattr(terminal_ui, "consolidate_parallel_panels"):
        terminal_ui.consolidate_parallel_panels()
        
    return f"{result_coder}\n\n{'='*40}\n\n{result_res}"

tool_schema = {
    "name": "call_agents_parallel",
    "description": "Invoca a DeepCoder y DeepResearcher simultáneamente para acelerar el procesamiento paralelo de tareas complementarias.",
    "parameters": {
        "type": "object",
        "properties": {
            "task_coder": {
                "type": "string",
                "description": "La tarea específica que debe realizar el DeepCoder (desarrollo, edición de código, refactorización)."
            },
            "task_researcher": {
                "type": "string",
                "description": "La tarea específica que debe realizar el DeepResearcher (investigación, análisis de archivos, diseño)."
            }
        },
        "required": ["task_coder", "task_researcher"]
    }
}
