#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Licensed under AGPL-3.0.
# See LICENSE file for details.
"""
PULSE CLI - single entry point for the PULSE Neural Operating System.

Usage:
  pulse status              Show running daemons, task board, and system health
  pulse watch               Auto-refreshing status dashboard (3s)
  pulse brain               Brain usage dashboard
  pulse costs               Show cost and token usage stats
  pulse history [--all]     Show timeline of completed tasks

  pulse swarm               Interactive worker launcher (provider -> model -> count)
  pulse swarm gemini        Pick model + count for Gemini
  pulse swarm <model>       Pick count for that model
  pulse swarm stop          Kill all workers
  pulse swarm status        Show running workers

  pulse claude              Launch Claude (Interactive Chat)
  pulse gemini              Launch Gemini (Interactive Chat)
  pulse codex               Launch Codex (Interactive Chat)
  pulse grok                Launch Grok (Interactive Chat)

  pulse start               Start the orchestrator (all daemons)
  pulse stop                Stop all PULSE processes
  pulse post "task"         Post a task to the board
  pulse relay ...           Pass-through to pulse_relay.py
  pulse clean               Remove old tasks and reset stale claims
  pulse logs [worker_id]    Tail worker logs
  pulse dashboard [port]    Start the web monitoring dashboard
"""
import sys
from pathlib import Path

ROOT_DIR = Path(__file__).resolve().parent

# Load .env so PULSE_BRAIN_KEY and other secrets are available
try:
    from dotenv import load_dotenv
    load_dotenv(ROOT_DIR / ".env")
except ImportError:
    pass

# Ensure project root is on path for package imports
sys.path.insert(0, str(ROOT_DIR))

from pulse.cli.status import cmd_status, cmd_watch, cmd_brain
from pulse.cli.cmd_costs import cmd_costs, cmd_history
from pulse.cli.cmd_manage_lifecycle import cmd_start, cmd_stop, cmd_clean, cmd_dashboard
from pulse.cli.cmd_manage_data import cmd_post, cmd_relay, cmd_logs
from pulse.cli.cmd_swarm import cmd_swarm
from pulse.cli.cmd_agent import cmd_agent, AGENT_NAMES
from pulse.brain.brain_query import run_query


def _brain_check(command: str, args: list) -> bool:
    """Show brain context before critical commands. Never blocks."""
    if command not in ("post",):
        return True
    if command == "swarm" and args and args[0] in ("status", "stop"):
        return True

    query = f"{command} {' '.join(args[:5])}".strip()
    briefing = run_query(query)

    if briefing and "!! PREDICTION:" in briefing:
        print(f"\n[BRAIN] {briefing}\n")

    return True


def main():
    if len(sys.argv) < 2:
        print(__doc__)
        return

    cmd = sys.argv[1].lower()
    rest = sys.argv[2:]

    # Route to handler
    routes = {
        "status":    lambda: cmd_status(),
        "watch":     lambda: cmd_watch(),
        "brain":     lambda: cmd_brain(),
        "costs":     lambda: cmd_costs(),
        "history":   lambda: cmd_history(rest),
        "swarm":     lambda: cmd_swarm(rest),
        "start":     lambda: cmd_start(),
        "stop":      lambda: cmd_stop(),
        "post":      lambda: cmd_post(rest),
        "relay":     lambda: cmd_relay(rest),
        "clean":     lambda: cmd_clean(),
        "logs":      lambda: cmd_logs(rest),
        "dashboard": lambda: cmd_dashboard(rest),
    }

    if cmd in routes:
        # Enforce brain check for critical ops
        if not _brain_check(cmd, rest):
            return
        return routes[cmd]()
    elif cmd in AGENT_NAMES:
        # Interactive agents also get checked
        if not _brain_check(cmd, rest):
            return
        return cmd_agent(cmd, rest)
    elif cmd in ("-h", "--help", "help"):
        print(__doc__)
    else:
        print(f"Unknown command: {cmd}")
        print(__doc__)


if __name__ == "__main__":
    main()
