#!/usr/bin/env python3
from __future__ import annotations

import json
from typing import Any, Dict


def print_json(payload: Any) -> None:
    print(json.dumps(payload, ensure_ascii=False, indent=2))


def format_bool(value: Any) -> str:
    return "yes" if bool(value) else "no"


def format_status_payload(payload: Dict[str, Any]) -> None:
    bots = payload.get("bots") if isinstance(payload.get("bots"), list) else []
    print(f"[STATUS] manifest: {payload.get('manifest_path', '-')}")
    print(f"[STATUS] bots: {len(bots)} total, {payload.get('running_count', 0)} running")
    for item in bots:
        bot_id = str(item.get("bot_id") or "-")
        line = (
            f"- {bot_id} ({item.get('channel') or '-'}) "
            f"enabled={format_bool(item.get('enabled'))} "
            f"alive={format_bool(item.get('alive'))} "
            f"pid={item.get('pid') or 0} "
            f"pending={item.get('pending_instruction_count') or 0}"
        )
        print(line)
        print(
            f"  user_data_root={item.get('user_data_root') or '-'} "
            f"main_agent_running={format_bool(item.get('main_agent_running'))}"
        )


def format_list_bots_payload(payload: Dict[str, Any]) -> None:
    bots = payload.get("bots") if isinstance(payload.get("bots"), list) else []
    print(f"[BOTS] manifest: {payload.get('manifest_path', '-')}")
    if not bots:
        print("[BOTS] none")
        return
    for item in bots:
        print(
            f"- {item.get('bot_id') or '-'} "
            f"name={item.get('display_name') or '-'} "
            f"channel={item.get('channel') or '-'} "
            f"enabled={format_bool(item.get('enabled'))} "
            f"webhooks={format_bool(item.get('serve_webhooks'))}"
        )


def format_prepare_payload(payload: Dict[str, Any]) -> None:
    print(f"[PREPARE] manifest: {payload.get('manifest_path', '-')}")
    print(f"[PREPARE] runtime_root: {payload.get('runtime_root', '-')}")
    print(f"[PREPARE] fleet_config: {payload.get('fleet_config_path', '-')}")
    bots = payload.get("bots") if isinstance(payload.get("bots"), list) else []
    print(f"[PREPARE] enabled bots: {len(bots)}")
    for item in bots:
        print(
            f"- {item.get('bot_id') or '-'} "
            f"user_data_root={item.get('user_data_root') or '-'} "
            f"webhooks={format_bool(item.get('serve_webhooks'))}"
        )


def format_agent_system_payload(payload: Dict[str, Any]) -> None:
    print(f"[AGENT_SYSTEM] status: {payload.get('status', '-')}")
    print(f"[AGENT_SYSTEM] scope: {payload.get('scope', '-')}")
    print(f"[AGENT_SYSTEM] name: {payload.get('system_name', '-')}")
    print(f"[AGENT_SYSTEM] archive: {payload.get('archive_path', '-')}")
    print(f"[AGENT_SYSTEM] target: {payload.get('target_root', '-')}")
    print(f"[AGENT_SYSTEM] files: {payload.get('file_count', 0)}")
    if str(payload.get("bot_id") or "").strip():
        print(f"[AGENT_SYSTEM] bot_id: {payload.get('bot_id')}")
    if str(payload.get("next_step") or "").strip():
        print(f"[NEXT] {payload.get('next_step')}")


def format_start_stop_payload(payload: Dict[str, Any], *, title: str) -> None:
    if isinstance(payload.get("results"), list):
        print(f"[{title}] manifest: {payload.get('manifest_path', '-')}")
        if any(
            key in payload
            for key in (
                "requested_bot_count",
                "started_count",
                "already_running_count",
                "conflict_count",
            )
        ):
            print(
                f"[{title}] summary: requested={int(payload.get('requested_bot_count') or 0)} "
                f"started={int(payload.get('started_count') or 0)} "
                f"already_running={int(payload.get('already_running_count') or 0)} "
                f"conflict={int(payload.get('conflict_count') or 0)}"
            )
        for item in payload.get("results", []):
            remaining = item.get("remaining_pids") if isinstance(item.get("remaining_pids"), list) else []
            remaining_text = f" remaining={','.join(str(x) for x in remaining)}" if remaining else ""
            error_text = f" error={item.get('error')}" if str(item.get("error") or "").strip() else ""
            print(
                f"- {item.get('bot_id') or '-'} status={item.get('status') or '-'} "
                f"pid={item.get('pid') or 0} "
                f"log={item.get('log_path') or '-'}"
                f"{remaining_text}"
                f"{error_text}"
            )
            if str(item.get("status") or "") == "conflict" and isinstance(item.get("conflicts"), list):
                for conflict in item.get("conflicts", []):
                    if not isinstance(conflict, dict):
                        continue
                    print(
                        "  conflict: "
                        f"pid={int(conflict.get('pid') or 0)} "
                        f"detected={conflict.get('detected_fleet_config_path') or '-'}"
                    )
        return
    remaining = payload.get("remaining_pids") if isinstance(payload.get("remaining_pids"), list) else []
    remaining_text = f" remaining={','.join(str(x) for x in remaining)}" if remaining else ""
    print(
        f"[{title}] {payload.get('bot_id') or '-'} "
        f"status={payload.get('status') or '-'} "
        f"pid={payload.get('pid') or 0}"
        f"{remaining_text}"
    )
    if str(payload.get("error") or "").strip():
        print(f"[{title}] error: {payload.get('error')}")
    if payload.get("log_path"):
        print(f"[{title}] log: {payload.get('log_path')}")
    if str(payload.get("status") or "") == "conflict" and isinstance(payload.get("conflicts"), list):
        for conflict in payload.get("conflicts", []):
            if not isinstance(conflict, dict):
                continue
            print(
                f"[{title}] conflict: pid={int(conflict.get('pid') or 0)} "
                f"detected={conflict.get('detected_fleet_config_path') or '-'}"
            )


def format_restart_payload(payload: Dict[str, Any]) -> None:
    print(f"[RESTART] manifest: {payload.get('manifest_path', '-')}")
    stop_payload = payload.get("stop") if isinstance(payload.get("stop"), dict) else {}
    start_payload = payload.get("start") if isinstance(payload.get("start"), dict) else {}
    format_start_stop_payload(stop_payload, title="STOP")
    format_start_stop_payload(start_payload, title="START")


def format_emergency_stop_payload(payload: Dict[str, Any]) -> None:
    print("[STOP] manifest missing, fallback stop by process scan")
    bot = payload.get("bot_processes") if isinstance(payload.get("bot_processes"), dict) else {}
    web = payload.get("web_processes") if isinstance(payload.get("web_processes"), dict) else {}
    print(
        f"- bots status={bot.get('status') or '-'} "
        f"pids={','.join(str(x) for x in (bot.get('pids') or [])) or '-'} "
        f"remaining={','.join(str(x) for x in (bot.get('remaining_pids') or [])) or '-'}"
    )
    print(
        f"- web status={web.get('status') or '-'} "
        f"pids={','.join(str(x) for x in (web.get('pids') or [])) or '-'} "
        f"remaining={','.join(str(x) for x in (web.get('remaining_pids') or [])) or '-'}"
    )


def format_web_payload(payload: Dict[str, Any], *, title: str) -> None:
    print(f"[{title}] manifest: {payload.get('manifest_path', '-')}")
    print(
        f"[{title}] status={payload.get('status') or '-'} "
        f"running={format_bool(payload.get('running'))} pid={payload.get('pid') or 0}"
    )
    if payload.get("url"):
        print(f"[{title}] url: {payload.get('url')}")
    if payload.get("log_path"):
        print(f"[{title}] log: {payload.get('log_path')}")
    if payload.get("error"):
        print(f"[{title}] error: {payload.get('error')}")
