"""Desktop Agent - executes commands from gateway."""
import asyncio
import aiohttp
from .config import AgentConfig
from .heartbeat import HeartbeatSender
from .poller import ActionPoller
from .reporter import StatusReporter

class DesktopAgent:
    def __init__(self, config: AgentConfig, orchestrator):
        self.config = config
        self.orchestrator = orchestrator
        self.heartbeat = HeartbeatSender(config)
        self.poller = ActionPoller(config)
        self.reporter = StatusReporter(config)
        self.running = False
        
    async def run(self, silent=False):
        """Start agent loop."""
        self.running = True
        if not silent:
            print(f"✓ Agent started")
            print(f"✓ Connected to gateway: {self.config.gateway_url}")
            print("\n🔄 Listening for commands...\n")
        
        # Start heartbeat in background
        heartbeat_task = asyncio.create_task(self.heartbeat.start())
        
        try:
            while self.running:
                # Pull action from gateway
                action = await self.poller.pull_action()
                
                if action:
                    await self._execute_action(action, silent)
                
                await asyncio.sleep(self.config.polling_interval)
        except KeyboardInterrupt:
            if not silent:
                print("\n\n⏹ Stopping agent...")
        finally:
            self.heartbeat.stop()
            await heartbeat_task
            
    async def _execute_action(self, action, silent=False):
        """Execute action and report result."""
        action_id = action.get("action_id")
        command = action.get("action_input")
        
        if not silent:
            print(f"📥 Received: {command}")
        
        # Update status to RUNNING
        await self.reporter.update_status(action_id, "RUNNING")
        
        try:
            # Execute command using orchestrator
            result = self.orchestrator.execute(command, dry_run=False)
            
            if result and result.get("success"):
                # Success
                output = result.get("message", "")
                if result.get("data") and result["data"].get("output"):
                    output += "\n" + result["data"]["output"]
                
                await self.reporter.update_status(
                    action_id, 
                    "COMPLETED",
                    result=output
                )
                if not silent:
                    print(f"✓ Completed: {command}\n")
            else:
                # Failed
                error = result.get("message", "Unknown error") if result else "No result"
                await self.reporter.update_status(
                    action_id,
                    "FAILED",
                    error=error
                )
                if not silent:
                    print(f"✗ Failed: {error}\n")
                
        except Exception as e:
            # Exception
            await self.reporter.update_status(
                action_id,
                "FAILED",
                error=str(e)
            )
            if not silent:
                print(f"✗ Error: {str(e)}\n")
