"""MCP fleet status tool — returns all known VMs with their job associations.

Provides the ``vm_fleet_status`` tool (R005) that agents use to query the
fleet-wide VM ↔ job view.  Each VM entry includes its running state and a
list of associated jobs with their current status and last step.
"""

from __future__ import annotations

from fastmcp.tools import tool

from mcp_vm_blackbox.job_store import default_job_store
from mcp_vm_blackbox.models import FleetEntry, JobSummary
from mcp_vm_blackbox.vm_registry import default_registry


@tool
async def vm_fleet_status() -> list[FleetEntry]:
    """Return all known VMs with their running state and associated jobs.

    Reads the VM registry for the list of known VMs, then queries the job
    store for each VM to build a fleet-wide status view.

    Returns:
        List of ``FleetEntry`` models.  Each entry contains the VM
        name, UUID, running state, and a list of ``JobSummary`` models
        for all jobs associated with that VM.  Returns an empty list when
        the registry is empty.
    """
    vm_entries = await default_registry.list_all()
    if not vm_entries:
        return []

    fleet: list[FleetEntry] = []
    for vm in vm_entries:
        job_records = await default_job_store.list_by_vm(vm.vm_name)
        job_summaries = [
            JobSummary(
                job_id=r.job_id,
                scenario_name=r.scenario_name,
                status=r.status,
                last_agent_id=r.last_agent_id,
                last_step=r.steps[-1].action if r.steps else None,
                updated_at=r.updated_at,
                pilot_context_usage=r.pilot_context_usage,
            )
            for r in job_records
        ]
        fleet.append(
            FleetEntry(
                vm_name=vm.vm_name,
                uuid=vm.uuid,
                running=vm.running,
                recording=vm.recording,
                recording_path=vm.recording_path,
                recording_started_at=vm.recording_started_at,
                jobs=job_summaries,
            )
        )

    return fleet
