"""Heartbeat sender for desktop agent."""
import asyncio
import socket
from datetime import datetime
import aiohttp

class HeartbeatSender:
    def __init__(self, config):
        self.config = config
        self.running = False
        
    async def send_heartbeat(self):
        """Send heartbeat to gateway."""
        url = f"{self.config.gateway_url}/desktops/{self.config.desktop_id}/heartbeat"
        headers = {"Authorization": self.config.device_token}
        payload = {
            "agent_version": self.config.agent_version,
            "hostname": socket.gethostname(),
            "timestamp": datetime.utcnow().isoformat() + "Z"
        }
        
        try:
            async with aiohttp.ClientSession() as session:
                async with session.post(url, json=payload, headers=headers, timeout=aiohttp.ClientTimeout(total=5)) as resp:
                    if resp.status == 200:
                        return True
        except:
            pass
        return False
    
    async def start(self):
        """Start heartbeat loop."""
        self.running = True
        while self.running:
            await self.send_heartbeat()
            await asyncio.sleep(self.config.heartbeat_interval)
    
    def stop(self):
        """Stop heartbeat loop."""
        self.running = False
