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

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

class OledDisplayAgent(AgentInterface):
    def __init__(self, ble_address):
        super().__init__()
        self.agent_id = f"oled-display-{str(uuid.uuid4())[:8]}"
        self.name = f"OledDisplay-{str(uuid.uuid4())[:4]}"
        self.mac_address = ble_address
        self.zone = None
        self.status = 'idle'
        self.capabilities = ['oled']
        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:
            self.ble.send_payload(payload)
        except Exception as e:
            print(f"[ERROR] Failed to send to OLED: {e}")
            self.enter_cooldown("BLE failure")

    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=""):
        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) -> dict:
        return super().get_summary() | {
            "type": "OledDisplay",
            "zone": self.zone or "None",
            "status": self.status,
            "current_chunk": self.current_chunk,
            "chunk_progress": self.chunk_progress,
            "required_ticks": self.required_ticks
        }
        
    """
    def tick(self):
        super().tick()
        if self.status == 'working':
            self.chunk_progress += 1
            if self.chunk_progress >= self.required_ticks:
                self.report_completion(self.current_chunk)
    """
