import random
from hiveos.runtime.agent_runtime import agent_objects
from hiveos.runtime.chunk_runtime import get_task_id, reset

def induce_failure(agent_name=None):
    """
    If agent_name is provided, attempt to fail that specific agent.
    If None, fail a random working agent.
    """
    target_agent = None

    if agent_name:
        target_agent = agent_objects.get(agent_name)
        if not target_agent:
            print(f"[Demo] Agent '{agent_name}' not found in runtime.")
            return
    else:
        working_agents = [a for a in agent_objects.values() if a.status == 'working']
        if not working_agents:
            print("[Demo] No agents are currently working.")
            return
        target_agent = random.choice(working_agents)

    if target_agent.status == 'working' and target_agent.current_chunk:
        task_id = get_task_id(target_agent.current_chunk)
        reset(target_agent.current_chunk)

        target_agent.status = 'recharging'
        target_agent.cooldown_ticks = 5
        target_agent.current_chunk = None
        target_agent.chunk_progress = 0
        target_agent.required_ticks = 0
        print(f"[Demo] Induced failure on {target_agent.name}. Chunk reassigned. Agent now recharging.")
    else:
        print(f"[Demo] Agent {target_agent.name} is not working — no failure induced.")
