"""Tool: emergency_stop — Immediately pause all active campaigns.

Safety kill-switch. Iterates every active campaign and sets status='paused'.
Logs each pause for audit trail. Use resume_campaign() to re-enable individually.
"""

from __future__ import annotations

import json
import logging
import time

from ..db.queries import (
    get_setting,
    list_campaigns,
    log_action,
    skip_pending_outreaches,
    update_campaign,
)

logger = logging.getLogger(__name__)


async def run_emergency_stop() -> str:
    """Pause all active campaigns immediately."""

    # ── Pre-check ──
    setup_done = get_setting("setup_complete", False)
    if not setup_done:
        return (
            "Setup required before managing campaigns.\n\n"
            "Please run setup_profile first."
        )

    # ── Find all active campaigns ──
    active_campaigns = list_campaigns(status="active")

    if not active_campaigns:
        return (
            "No active campaigns to stop.\n\n"
            "All campaigns are already paused or completed.\n"
            "Use show_status() to see all campaigns."
        )

    # ── Pause each one ──
    paused_names = []
    total_skipped = 0
    for campaign in active_campaigns:
        cid = campaign["id"]
        skipped = skip_pending_outreaches(cid)
        total_skipped += skipped
        cfg = json.loads(campaign.get("config_json") or "{}")
        cfg["pause_reason"] = "emergency_stop"
        cfg["paused_at"] = int(time.time())
        update_campaign(cid, status="paused", config_json=json.dumps(cfg))
        log_action(
            "emergency_stop",
            result="paused",
            details={
                "campaign_id": cid,
                "campaign_name": campaign["name"],
                "pending_skipped": skipped,
            },
        )
        paused_names.append(campaign["name"])
        logger.info(f"Emergency stop: paused campaign {cid}: {campaign['name']} ({skipped} pending skipped)")

    # ── Format result ──
    count = len(paused_names)
    output = [
        f"\U0001f6d1 EMERGENCY STOP: {count} campaign{'s' if count != 1 else ''} paused.",
        "",
    ]

    for i, name in enumerate(paused_names):
        is_last = i == len(paused_names) - 1
        prefix = "\u2514\u2500\u2500" if is_last else "\u251c\u2500\u2500"
        output.append(f"{prefix} {name}")

    output.append("")
    output.append(f"All outreach is stopped. {total_skipped} pending outreaches skipped.")
    output.append("")
    output.append("To resume individual campaigns: resume_campaign(campaign_id='...')")
    output.append("To see all campaigns: show_status()")

    return "\n".join(output)
