import uuid
from hiveos.agent_interface import AgentInterface
from hiveos.comms_helpers.bluetooth_interface import BluetoothInterface

char_uuid = "19B10001-E8F2-537E-4F6C-D104768A1214"

class TerminalAgent(AgentInterface):
    def __init__(self, ble_address):
        super().__init__()
        self.agent_id = str(uuid.uuid4())
        self.name = f"TerminalAgent-{str(uuid.uuid4())[:4]}"
        self.mac_address = ble_address
        self.status = 'idle'
        self.zone = None
        self.capabilities = ['terminal']
        self._available = True
        self.current_chunk = None
        self.chunk_progress = 0
        self.required_ticks = 0
        self.ble = BluetoothInterface(ble_address, char_uuid)
        
        self.on_injection()
        
    def on_injection(self):
        try:
            self.ble.send_payload("Initializing...")
            print(f"[BLE INIT] {self.agent_id} connected to {self.mac_address}")
        except Exception as e:
            print(f"[BLE ERROR] {self.agent_id} failed to connect: {e}")

    def get_status(self):
        return self.status

    def report_capabilities(self):
        return self.capabilities

    def execute_chunk(self, chunk_id, payload=None):
        super().execute_chunk(chunk_id, payload)

        try:
            intent = payload.get("intent")
            if intent == "display_text":
                self.ble.send_payload(payload.get("text", ""))
            elif intent == "clear_screen":
                self.ble.send_payload("\033[2J")
            elif intent == "status_update":
                self.ble.send_payload(f"[STATUS] {payload.get('message', '')}")
            else:
                self.ble.send_payload(f"[UNKNOWN INTENT] {payload}")
        except Exception as e:
            print(f"[TerminalAgent] BLE send failed: {e}")

    def report_completion(self, chunk_id):
        super().report_completion(chunk_id)

    def health_check(self):
        return self.ble.is_connected()
        
    def enter_cooldown(self, reason: str = ""):
        self.status = 'cooldown'
        self._available = False
        print(f"[cooldown] {self.agent_id}: {reason}")

    def is_available(self):
        return self._available and self.status == 'idle'

    def get_summary(self):
        return super().get_summary() | {
            "name": self.name,
            "type": "Terminal",
            "zone": self.zone or None,
            "status": self.status,
            "progress": self.chunk_progress,
        }
