import uuid
from hiveos.agent_interface import AgentInterface
from hiveos.runtime.agent_runtime import register

class MyCustomAgent(AgentInterface):
    def __init__(self, capability="custom.capability"):
        self.agent_id = f"custom-agent-{str(uuid.uuid4())[:8]}"
        self.name = f"MyAgent-{str(uuid.uuid4())[:4]}"
        self.capabilities = [capability]
        self.status = "idle"
        self._available = True
        self.zone = None
        self.current_chunk = None
        self.chunk_progress = 0
        self.required_ticks = 0

        # Optional: communication hook (e.g. BLE, serial, etc.)
        self.device = None  # e.g. self.device = SerialHelper(...)

        register(self)

    def get_status(self):
        return self.status

    def report_capabilities(self):
        return self.capabilities

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

    def health_check(self):
        # Customize per agent — return True if healthy
        return True

    def enter_cooldown(self, reason=""):
        self.status = 'cooldown'
        print(f"[{self.agent_id}] cooldown triggered: {reason}")

    def on_injection(self):
        # Useful for comms handshakes to keep blocking to a minimum
        print(f"[{self.agent_id}] injected into runtime.")

    def on_removal(self):
        print(f"[{self.agent_id}] removed from runtime.")
        # Example: if self.device: self.device.disconnect()

    def execute_chunk(self, chunk_id, payload=None):
        super().execute_chunk(chunk_id, payload)
        print(f"[{self.agent_id}] executing: {payload}")
        
        intent = self.payload.get("intent") if isinstance(self.payload, dict) else None
        params = self.payload.get("parameters", {}) if isinstance(self.payload, dict) else {}

        # Handle portable format
        if intent == "do_something":
            print(f"Intent received: do_something with {params}")
            # Your hardware logic here (e.g., self.device.send_command(...))
        else:
            print(f"[{self.agent_id}] Unrecognized intent: {intent}")

    def get_summary(self) -> dict:
        return super().get_summary() | {
            "type": "GenericHiveAgent",
            "zone": self.zone or "None",
            "status": self.status,
            "current_chunk": self.current_chunk,
            "chunk_progress": self.chunk_progress,
            "required_ticks": self.required_ticks
        }

    def describe_payload(self):
        return {
            "intents": {
                "do_something": {
                    "description": "Performs a custom device behavior.",
                    "parameters": {
                        "value": "integer or string, e.g. 42"
                    }
                }
            }
        }
