from __future__ import annotations

from typing import Any

from armorer.agent_sdk import tool


def _services():
    from armorer.web import services

    return services


def build_runtime_state_snapshot(agent: str = "") -> dict[str, Any]:
    services = _services()
    return {
        "status": services.status_summary(),
        "urls": services.urls_summary(agent),
        "installed_agents": services.installed_agents_summary(),
        "recent_jobs": services.read_recent_jobs(limit=10),
    }


@tool(category="runtime_state", verification_level="live_state", safe_for_retrieval=True)
def get_runtime_access_snapshot(agent: str = "") -> dict[str, Any]:
    """Return live Armorer-managed runtime access information for URLs, agent state, and recent jobs."""
    return build_runtime_state_snapshot(agent)


@tool(category="runtime_state", verification_level="live_state", safe_for_retrieval=True)
def get_status_snapshot() -> dict[str, Any]:
    """Return a compact live Armorer runtime status summary."""
    return _services().status_summary()


@tool(category="runtime_state", verification_level="live_state", safe_for_retrieval=True)
def get_installed_agents_snapshot() -> dict[str, Any]:
    """Return installed Armorer-managed agents and their live dashboard/status metadata."""
    return _services().installed_agents_summary()


@tool(category="runtime_state", verification_level="live_state", safe_for_retrieval=True)
def get_dashboard_urls(agent: str = "") -> dict[str, Any]:
    """Return user-facing Armorer and app dashboard URLs from live runtime state."""
    return _services().urls_summary(agent)


@tool(category="runtime_state", verification_level="job_state", safe_for_retrieval=True)
def get_recent_jobs_snapshot(limit: int = 10) -> list[dict[str, Any]]:
    """Return recent Armorer background jobs."""
    return _services().read_recent_jobs(limit=max(1, int(limit)))


@tool(category="setup_state", verification_level="live_state", safe_for_retrieval=True)
def get_agent_setup_state(agent: str) -> dict[str, Any]:
    """Return the current setup/readiness state for an installed agent."""
    services = _services()
    requested = str(agent or "").strip()
    if not requested:
        return {"ok": False, "message": "Agent alias is required."}
    installed = services.installed_agents_summary()
    for item in installed.get("agents", []) or []:
        if not isinstance(item, dict):
            continue
        alias = str(item.get("alias") or "").strip()
        agent_id = str(item.get("agent_id") or "").strip()
        if requested.lower() in {alias.lower(), agent_id.lower()}:
            if agent_id.lower() == "openclaw":
                return services.openclaw_setup_summary(alias)
            return {
                "ok": True,
                "agent": alias,
                "setup": item.get("setup") or {},
                "status": item.get("status") or {},
                "dashboard_url": item.get("dashboard_url") or "",
            }
    return {"ok": False, "message": f"No installed agent matched '{requested}'."}
