"""Emergency stop: immediately halt all agent activity."""

from __future__ import annotations

import logging

from fastapi import APIRouter, Request

log = logging.getLogger(__name__)

router = APIRouter(tags=["emergency"])


@router.post("/emergency-stop")
async def emergency_stop(request: Request) -> dict:
    """EMERGENCY STOP — immediately halt all agent activity.

    1. Disconnects all channels (WhatsApp, Telegram, etc.)
    2. Stops heartbeat, scheduler, daily cycle
    3. Sets agent to frozen state (blocks all actions)
    4. Logs to audit trail
    """
    stopped = []

    # Stop ALL background services
    for name in ("heartbeat", "scheduler", "daily_cycle", "cron",
                 "work_queue", "raw_watcher", "vault_edit_watcher"):
        svc = getattr(request.app.state, name, None)
        if svc and hasattr(svc, "stop"):
            svc.stop()
            stopped.append(name)

    # Stop filesystem event bridge
    fs_bridge = getattr(request.app.state, "fs_bridge", None)
    if fs_bridge and hasattr(fs_bridge, "stop"):
        fs_bridge.stop()
        stopped.append("fs_bridge")

    # Disconnect all channels
    manager = getattr(request.app.state, "channel_manager", None)
    if manager:
        await manager.disconnect_all()
        stopped.append("channels")

    # Set frozen + unlaunched flags
    request.app.state.frozen = True
    request.app.state.launched = False
    stopped.append("agent_frozen")

    # Audit
    audit = getattr(request.app.state, "audit", None)
    if audit:
        audit.log_action(
            action="emergency_stop",
            target="all",
            approved="manual",
        )

    log.warning("EMERGENCY STOP executed — all activity halted")
    return {"status": "stopped", "stopped": stopped}


@router.post("/resume")
async def resume(request: Request) -> dict:
    """Resume agent activity after emergency stop.

    Delegates to POST /api/launch which starts all services and sets
    launched=True, frozen=False.
    """
    from agntspace.api.routes.launch import launch as do_launch
    result = await do_launch(request)

    # Audit
    audit = getattr(request.app.state, "audit", None)
    if audit:
        audit.log_action(
            action="resume",
            target="all",
            approved="manual",
        )

    log.info("Agent RESUMED via launch — activity restored")
    return {"status": "resumed", "launch": result}


@router.get("/agent-status")
async def agent_status(request: Request) -> dict:
    """Check if agent is frozen or active."""
    frozen = getattr(request.app.state, "frozen", False)
    heartbeat = getattr(request.app.state, "heartbeat", None)

    return {
        "frozen": frozen,
        "heartbeat_running": heartbeat.is_running if heartbeat else False,
        "channels": request.app.state.channel_manager.list_channels()
        if hasattr(request.app.state, "channel_manager") else [],
    }
