"""Desktop Agent orchestrator."""
import asyncio
from .heartbeat import HeartbeatSender
from .poller import ActionPoller
from .reporter import StatusReporter

class DesktopAgent:
    def __init__(self, config, unishell):
        self.config = config
        self.unishell = unishell
        self.heartbeat = HeartbeatSender(config)
        self.poller = ActionPoller(config)
        self.reporter = StatusReporter(config)
        self.running = False
        
    async def execute_action(self, action_id, action_input):
        """Execute action through UniShell CLI."""
        await self.reporter.update_status(action_id, "RUNNING")
        
        print(f"\n▶️  Executing: {action_input}")
        print("=" * 60)
        
        try:
            # Execute through UniShell synchronously
            result_messages = await asyncio.get_event_loop().run_in_executor(
                None,
                lambda: self.unishell.chat(message=action_input, display=False, stream=False)
            )
            
            # Extract output from messages
            output_parts = []
            for msg in result_messages:
                if msg.get("type") == "message" and msg.get("role") == "assistant":
                    output_parts.append(msg.get("content", ""))
                elif msg.get("type") == "console" and msg.get("format") == "output":
                    output_parts.append(msg.get("content", ""))
            
            output = "\n".join(output_parts)
            
            print(output if output else "(no output)")
            print("=" * 60)
            print("✅ Execution complete\n")
            
            # Report success
            await self.reporter.update_status(
                action_id,
                "COMPLETED",
                result={"output": output, "messages": len(result_messages)}
            )
            
        except Exception as e:
            print(f"❌ Execution failed: {str(e)}\n")
            await self.reporter.update_status(
                action_id,
                "FAILED",
                error=str(e)
            )
    
    async def run(self):
        """Main agent loop."""
        self.running = True
        
        # Start heartbeat in background
        heartbeat_task = asyncio.create_task(self.heartbeat.start())
        
        print(f"\n🤖 Desktop Agent Mode")
        print(f"Gateway: {self.config.gateway_url}")
        print(f"Desktop ID: {self.config.desktop_id}")
        print(f"\nAgent will execute commands from gateway and display results here.")
        print("Press CTRL-C to stop.\n")
        
        try:
            while self.running:
                # Poll for action
                action = await self.poller.pull_action()
                
                if action:
                    action_id = action.get("action_id")
                    action_input = action.get("action_input")
                    
                    if action_id and action_input:
                        await self.execute_action(action_id, action_input)
                
                # Sleep before next poll
                await asyncio.sleep(self.config.polling_interval)
                
        except KeyboardInterrupt:
            print("\n\n🛑 Agent stopped by user")
        finally:
            self.running = False
            self.heartbeat.stop()
            heartbeat_task.cancel()
            try:
                await heartbeat_task
            except asyncio.CancelledError:
                pass
