import datetime
import time

from hiveos.intelligence.tracing import get_trace_sink_stats


def build_status_response(core, session_id):
    agents = [ra.to_dict() for ra in core._runtime_agents.values() if ra.session_id == session_id]
    chunks = [c.to_dict() for c in core.chunk_objects.values() if c.session_id == session_id]
    tasks = [t.to_dict() for t in core.task_objects.values() if t.session_id == session_id]
    zones = [
        {
            "task_id": zone.task_id,
            "zone_id": zone.zone_id,
            "frozen": zone.frozen,
            "agents": [a.agent_id for a in zone.agent_instances],
            "session_id": zone.session_id,
            "watchdog": zone.get_watchdog_summary(),
        }
        for _, zone in core.zones.items()
        if zone.session_id == session_id
    ]

    uptime_seconds = int(time.time() - core.start_time)
    uptime_str = str(datetime.timedelta(seconds=uptime_seconds))

    return {
        "status": "OK",
        "zone_count": len(zones),
        "agents": agents,
        "chunks": chunks,
        "tasks": tasks,
        "zones": zones,
        "tickrate": core.tick_control["delay"],
        "core_running": core.tick_control["running"],
        "ticks": core.tick_counter["count"],
        "uptime": uptime_str,
        "ai_execution_plane": core.ai_execution_plane.get_stats(),
        "tool_registry": core.tool_registry.get_stats(),
        "proposal_manager": core.proposal_manager.stats(),
        "memory_store": core.memory_store.stats(),
        "sandbox_runtime": core.sandbox_runtime.get_stats(),
        "terminal_runtime": core.terminal_service.get_stats(),
        "intent_runtime": core.intent_service.stats(),
        "runtime_perf": core.get_runtime_perf(),
        "execution_hardening": dict(core.execution_hardening),
        "trace_sink": get_trace_sink_stats(),
    }
