import uuid
import random
from hiveos.db import get_db
from hiveos.models.chunk import Chunk
from hiveos.agent_interface import AgentInterface
from hiveos.utilities.log_event import log_chunk_event

# Runtime registry here instead of in agent_runtime.py
instances = []

def register(agent):
    instances.append(agent)

def get_agent_by_name(name):
    return next((a for a in instances if a.name == name), None)

class SimAgent(AgentInterface):
    _name_counter = 1

    def __init__(self, agent_id=None, name=None, battery=100, zone=None, capabilities='[]', residency=None):
        self.agent_id = agent_id or str(uuid.uuid4())
        print(f"[DEBUG] SimAgent.__init__: initializing agent {self.agent_id[:8]}")
        self.status = 'idle'
        self.battery = battery
        self.zone = zone
        self.capabilities = capabilities
        self.zone_residency_until = residency

        if name:
            self.name = name
            print(f"[DEBUG] Assigned name directly: {self.name}")
        else:
            try:
                from hiveos.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}"
                    print(f"[DEBUG] Assigned auto-name: {self.name}")
                    SimAgent._name_counter += 1
            except ImportError:
                self.name = f"Agent-{SimAgent._name_counter:03d}"
                print(f"[DEBUG] Assigned auto-name: {self.name}")
                SimAgent._name_counter += 1

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

        self.register()
        from hiveos.agent_runtime import register
        register(self)

    def register(self):
        with get_db() as conn:
            conn.execute("""
                INSERT OR REPLACE INTO agents (agent_id, status, battery, zone, capabilities, zone_residency_until)
                VALUES (?, ?, ?, ?, ?, ?)
            """, (self.agent_id, self.status, self.battery, self.zone, self.capabilities, self.zone_residency_until))

    def get_status(self):
        return self.status

    def report_capabilities(self):
        return self.capabilities

    def execute_chunk(self, chunk_id):
        print(f"[{self.name}] Executing chunk {chunk_id}...")
        self.status = 'working'
        self.current_chunk = chunk_id
        self.chunk_progress = 0
        self.required_ticks = random.randint(3, 7)
        self.register()

    def report_completion(self, chunk_id):
        print(f"[{self.name}] Completed chunk {chunk_id}.")
        self.status = 'idle'
        self.current_chunk = None
        self.chunk_progress = 0
        self.required_ticks = 0
        Chunk.complete(chunk_id)
        self.register()

    def enter_cooldown(self, reason=""):
        print(f"[{self.name}] Entering cooldown: {reason}")
        self.status = 'cooldown'
        self.cooldown_ticks = random.randint(3, 6)
        self.register()

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

    def tick(self):
        if self.status == 'cooldown':
            self.cooldown_ticks -= 1
            if self.cooldown_ticks <= 0:
                print(f"[{self.name}] Cooldown complete.")
                self.status = 'idle'
                self.register()
            return

        if self.status == 'recharging':
            self.cooldown_ticks -= 1
            if self.cooldown_ticks <= 0:
                print(f"[{self.name}] Recharged.")
                self.status = 'idle'
                self.battery = 100
                self.register()
            return

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

            if self.battery == 0:
                print(f"[{self.name}] Battery depleted. Dropping chunk {self.current_chunk}.")
                task_id = Chunk.get_task_id(self.current_chunk)
                log_chunk_event(self.current_chunk, task_id, self.agent_id, "fallback", reason="battery depleted")
                Chunk.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
                self.register()
                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):
        """
        TODO: Return a dynamic score representing this agent's fitness
        to be assigned work. Could include battery, history, latency,
        or custom telemetry when real data is available.
        """
        return 1.0  # neutral score for now
