import uuid
import random
import ast
from hiveos.agent_interface import AgentInterface
from hiveos.utilities.log_event import log_chunk_event

class SimAgent(AgentInterface):
    _name_counter = 1

    def __init__(self, agent_id=None, name=None, battery=100, zone=None, capabilities='[]', residency=None):
        super().__init__()
        self.agent_id = agent_id or str(uuid.uuid4())
        self.status = 'idle'
        self.battery = battery
        self.zone = zone
        self.capabilities = self._normalize_capabilities(capabilities)
        self.zone_residency_until = residency

        if name:
            self.name = name
        else:
            try:
                from hiveos.runtime.agent_runtime import agent_objects
                if self.agent_id in agent_objects:
                    self.name = agent_objects[self.agent_id].name
                else:
                    self.name = f"Agent-{SimAgent._name_counter:03d}"
                    SimAgent._name_counter += 1
            except ImportError:
                self.name = f"Agent-{SimAgent._name_counter:03d}"
                SimAgent._name_counter += 1

        self.current_chunk = None
        self.chunk_progress = 0
        self.required_ticks = 0
        self.cooldown_ticks = 0

    @staticmethod
    def _normalize_capabilities(capabilities):
        if isinstance(capabilities, list):
            return capabilities
        if isinstance(capabilities, str):
            try:
                parsed = ast.literal_eval(capabilities)
                if isinstance(parsed, list):
                    return parsed
            except Exception:
                pass
            return [capabilities]
        return ["generic"]

    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)       
        
        #self.required_ticks = random.randint(3, 7)       

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

    def enter_cooldown(self, reason=""):
        self.status = 'cooldown'
        self.cooldown_ticks = random.randint(3, 6)
        
    def is_available(self):
        return self.status == 'idle'

    """
    def tick(self):
        super().tick()
        
        if self.status == 'cooldown':
            self.cooldown_ticks -= 1
            if self.cooldown_ticks <= 0:
                self.status = 'idle'
            return

        if self.status == 'recharging':
            self.cooldown_ticks -= 1
            if self.cooldown_ticks <= 0:
                self.status = 'idle'
                self.battery = 100
            return

        if self.status == 'working':
            self.battery = max(0, self.battery - 1)

            if self.battery == 0:
                task_id = get_task_id(self.current_chunk)
                log_chunk_event(self.current_chunk, task_id, self.agent_id, "fallback", reason="battery depleted")
                reset(self.current_chunk)
                self.status = 'recharging'
                self.cooldown_ticks = random.randint(5, 10)
                self.current_chunk = None
                self.chunk_progress = 0
                self.required_ticks = 0
                return

            if self.chunk_progress >= self.required_ticks:
                self.report_completion(self.current_chunk)
    """
    
    def health_check(self):
        return {'battery': self.battery, 'status': self.status}

    def score(self, task_context=None):
        return 1.0  # neutral score for now

    def get_summary(self) -> dict:
        return super().get_summary() | {
            "battery": self.battery,
            "cooldown_ticks": self.cooldown_ticks,
        }
