"""Alive integrations — unified system for web search, notifications, scheduling, and browser automation."""

from __future__ import annotations

import json
import logging
from typing import Any

_log = logging.getLogger("alive")


def _load_config() -> dict[str, Any]:
    """Load ~/.alive/config.json if it exists."""
    from alive.config import CONFIG_FILE

    if CONFIG_FILE.exists():
        try:
            return json.loads(CONFIG_FILE.read_text())
        except (json.JSONDecodeError, OSError):
            return {}
    return {}


def _save_config(cfg: dict[str, Any]) -> None:
    """Save config to ~/.alive/config.json."""
    from alive.config import CONFIG_FILE

    CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
    CONFIG_FILE.write_text(json.dumps(cfg, indent=2))


def _check_daemon() -> bool:
    """Check if the Alive scheduler daemon is running."""
    from alive.config import ALIVE_HOME

    pid_file = ALIVE_HOME / "daemon.pid"
    if not pid_file.exists():
        return False
    try:
        import os
        import signal

        pid = int(pid_file.read_text().strip())
        os.kill(pid, 0)  # Check if process exists (signal 0)
        return True
    except (ValueError, OSError, ProcessLookupError):
        return False


def _count_schedules() -> int:
    """Count the number of active scheduled tasks."""
    from alive.config import ALIVE_HOME

    schedule_file = ALIVE_HOME / "schedules.json"
    if not schedule_file.exists():
        return 0
    try:
        data = json.loads(schedule_file.read_text())
        return sum(1 for t in data if t.get("enabled", True))
    except (json.JSONDecodeError, OSError):
        return 0


def _check_playwright() -> bool:
    """Check if Playwright + Chromium are installed."""
    try:
        from playwright.sync_api import sync_playwright  # noqa: F401

        return True
    except ImportError:
        return False


def get_available_integrations() -> dict[str, dict[str, Any]]:
    """Return status of all integrations.

    Returns:
        Dict mapping integration names to their status dicts with
        keys: configured (bool), description (str), and integration-specific extras.
    """
    config = _load_config()

    # Determine web search backend
    if config.get("tavily_key"):
        search_backend = "tavily"
    elif config.get("searxng_url"):
        search_backend = "searxng"
    else:
        search_backend = "duckduckgo"

    # Telegram bot name
    telegram_bot_name = None
    if config.get("telegram_token"):
        try:
            from alive.integrations.telegram import _get_bot_name

            telegram_bot_name = _get_bot_name(config["telegram_token"])
        except Exception:
            telegram_bot_name = "(configured)"

    webhooks = config.get("webhooks", {})

    return {
        "web_search": {
            "configured": True,  # always available (DuckDuckGo)
            "backend": search_backend,
            "description": "Search the web for current information",
        },
        "telegram": {
            "configured": bool(config.get("telegram_token")),
            "bot_name": telegram_bot_name,
            "description": "Send alerts and chat via Telegram",
        },
        "scheduler": {
            "configured": True,  # always available
            "daemon_running": _check_daemon(),
            "active_tasks": _count_schedules(),
            "description": "Run skills on a schedule",
        },
        "browser": {
            "configured": _check_playwright(),
            "description": "Automate JavaScript-heavy websites",
        },
        "webhook": {
            "configured": bool(webhooks),
            "count": len(webhooks),
            "names": list(webhooks.keys()),
            "description": "Send alerts to Slack, Discord, Zapier, etc.",
        },
    }


def display_integrations(console=None) -> None:
    """Display integration status as a rich panel."""
    from rich.console import Console
    from rich.panel import Panel

    con = console or Console()
    integrations = get_available_integrations()

    lines = []
    all_configured = True

    # Web Search
    ws = integrations["web_search"]
    backend = ws["backend"]
    lines.append(f"[green]✅[/] Web Search  — {backend.title()} (ready, no config needed)")

    # Telegram
    tg = integrations["telegram"]
    if tg["configured"]:
        bot = tg.get("bot_name") or "connected"
        lines.append(f"[green]✅[/] Telegram    — {bot} (alert + chat mode)")
    else:
        lines.append("[dim]⬚  Telegram    — not configured (run: alive setup telegram)[/]")
        all_configured = False

    # Scheduler
    sc = integrations["scheduler"]
    if sc["daemon_running"]:
        lines.append(f"[green]✅[/] Scheduler   — daemon running, {sc['active_tasks']} active tasks")
    else:
        tasks = sc["active_tasks"]
        if tasks:
            lines.append(f"[yellow]⚠[/]  Scheduler   — {tasks} tasks, daemon not running")
        else:
            lines.append("[green]✅[/] Scheduler   — ready (run: alive daemon start)")

    # Browser
    br = integrations["browser"]
    if br["configured"]:
        lines.append("[green]✅[/] Browser     — Playwright + Chromium ready")
    else:
        lines.append("[dim]⬚  Browser     — not installed (run: alive setup browser)[/]")
        all_configured = False

    # Webhook
    wh = integrations["webhook"]
    if wh["configured"]:
        names = ", ".join(wh["names"][:3])
        lines.append(f"[green]✅[/] Webhook     — {wh['count']} configured ({names})")
    else:
        lines.append("[dim]⬚  Webhook     — not configured (run: alive setup webhook)[/]")
        all_configured = False

    lines.append("")
    if all_configured:
        lines.append("[bold green]💡 All integrations active. Alive is fully connected.[/]")
    else:
        lines.append("[dim]Setup: alive setup <name>  |  Test: alive test-<name>[/]")

    con.print(Panel(
        "\n".join(lines),
        title="[bold cyan]Integrations[/]",
        border_style="cyan",
        padding=(1, 2),
    ))


__all__ = [
    "get_available_integrations",
    "display_integrations",
]
