import uuid
import requests
from hiveos.agent_interface import AgentInterface

class ClosedSystemAgent(AgentInterface):
    def __init__(self, system_address):
        super().__init__()
        self.agent_id = f"closed-system-{str(uuid.uuid4())[:8]}"
        self.name = f"ClosedSystem-{str(uuid.uuid4())[:4]}"
        self.api_address = system_address  # Example: http://192.168.1.100/api
        self.zone = None
        self.status = 'idle'
        self.capabilities = ['closed_system']
        self._available = True
        self.current_chunk = None
        self.chunk_progress = 0
        self.required_ticks = 0
        self.task_id = None

        self.on_injection()

    def on_injection(self):
        try:
            ping = requests.get(f"{self.api_address}/ping")
            print(f"[SYSTEM INIT] {self.agent_id} connected to {self.api_address} :: {ping.text}")
        except Exception as e:
            print(f"[SYSTEM 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:
            result = requests.post(f"{self.api_address}/execute", json={"task": payload})
            self.task_id = result.json().get("task_id")
            print(f"[SYSTEM CMD] {self.agent_id} -> {payload}")
        except Exception as e:
            print(f"[ERROR] Failed to send command to system: {e}")
            self.enter_cooldown("Execution failure")

    def tick(self):
        super().tick()

        if self.status != 'working' or not self.task_id:
            return

        try:
            status = requests.get(f"{self.api_address}/status/{self.task_id}").json()
            if status.get("state") == "complete":
                self.report_completion(self.current_chunk)
                self.task_id = None
        except Exception as e:
            print(f"[ERROR] Poll failed: {e}")

    def health_check(self):
        try:
            response = requests.get(f"{self.api_address}/ping")
            return response.status_code == 200
        except Exception:
            return False

    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": "ClosedSystem",
            "zone": self.zone or "None",
            "status": self.status,
            "current_chunk": self.current_chunk,
            "chunk_progress": self.chunk_progress,
            "required_ticks": self.required_ticks
        }
