#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Interactive agent launch — pulse claude, pulse gemini, etc."""
from __future__ import annotations

import subprocess
import sys
import time
from pathlib import Path

from pulse.cli import AGENTS_DIR
from pulse.tasks.task_ops import ensure_orchestrator
from pulse.brain.brain_query import run_query

AGENT_NAMES = {"claude", "gemini", "codex", "grok", "ollama"}
STATE_DIR = Path(__file__).resolve().parent.parent.parent / "state"


def _parse_agent_flags(args: list[str]) -> tuple[str, list[str]]:
    """Extract --model from args. Returns (model, remaining_args)."""
    model = ""
    remaining = []
    i = 0
    while i < len(args):
        if args[i] in ("--model", "-m") and i + 1 < len(args):
            i += 1
            model = args[i]
        elif args[i] in ("--chat", "--autopilot"):
            pass  # legacy no-ops
        else:
            remaining.append(args[i])
        i += 1
    return model, remaining


def _get_initial_context() -> str:
    """Ask user for intent and get brain briefing."""
    print("\n[PULSE] Starting interactive session.")
    print("What are you working on? (Press Enter to skip brain check)")
    try:
        intent = input("> ").strip()
        if not intent:
            return ""
        
        print(f"[BRAIN] Querying wisdom for: '{intent}'...")
        briefing = run_query(intent)
        if briefing:
            print("-" * 60)
            print(briefing)
            print("-" * 60)
            return briefing
    except (KeyboardInterrupt, EOFError):
        pass
    return ""


def _auto_save_session(agent: str, session_start: float) -> None:
    """Session-end knowledge save. V2: handled by brain_scribe daemon."""
    pass


def cmd_agent(agent: str, args: list[str]):
    """Launch an agent in Interactive Chat mode."""
    # "ollama" shortcut → go straight to picker with ollama pre-selected
    if agent == "ollama":
        return cmd_chat_picker(preselect="ollama")

    model, remaining = _parse_agent_flags(args)

    ensure_orchestrator()

    # Brain-first is handled by the agents themselves:
    #   Claude → .claude/settings.json hooks
    #   Gemini → .gemini/hooks/brain_hook.py
    #   REPL   → interactive_chat.py injects brain on first message

    wrapper = AGENTS_DIR / "pulse_wrapper.py"
    cmd = [sys.executable, str(wrapper), "--include-constitution", "--skills-used", "--", agent] + remaining

    if model:
        cmd.extend(["--model", model])

    print(f"[PULSE] Launching {agent} (Interactive)...")
    session_start = time.time()
    try:
        return subprocess.call(cmd)
    except KeyboardInterrupt:
        print(f"\n[PULSE] {agent} session ended.")
        return 0
    finally:
        _auto_save_session(agent, session_start)


def cmd_chat_picker(preselect: str | None = None):
    """Unified interactive agent picker: provider → model → launch."""
    from pulse.cli.cmd_swarm import _pick, BACK
    from pulse.cli.swarm_providers import (
        MODELS, _PROVIDER_META, _detect_providers, _resolve_access, _ollama_models,
    )

    providers = _detect_providers()
    if not providers:
        print("[PULSE] No providers available.")
        print("  Set GEMINI_API_KEY, ANTHROPIC_API_KEY, or install agent CLIs.")
        return

    print("\n  PULSE — Interactive Agent\n")

    # Step 1: Pick provider (or use preselect)
    provider_key = preselect
    if preselect and not any(pk == preselect for pk, _ in providers):
        print(f"  [PULSE] Provider '{preselect}' not available.")
        provider_key = None

    while True:
        if not provider_key:
            idx = _pick("Select Provider:", [(label, "") for _, label in providers])
            if idx is None:
                return
            provider_key = providers[idx][0]

        # Step 2: Pick model
        models = MODELS.get(provider_key, [])
        if provider_key == "ollama":
            models = _ollama_models()
            if not models:
                print("  [PULSE] No Ollama models. Pull one first: ollama pull mistral:7b")
                provider_key = None
                continue
        if not models:
            print(f"  [PULSE] No models for {provider_key}.")
            provider_key = None
            continue

        midx = _pick("Select Model:", [(name, tier) for name, tier in models],
                      allow_back=True)
        if midx is None:
            return
        if midx == BACK:
            provider_key = None
            continue
        model, _tier = models[midx]

        # Step 3: Route based on provider type
        access = _resolve_access(provider_key)
        meta = _PROVIDER_META.get(provider_key, {})

        if provider_key == "ollama":
            from pulse.cli.ollama_launch import launch_interactive
            return launch_interactive(model)
        elif access == "cli":
            # cmd_agent handles orchestrator + brain check + wrapper launch
            return cmd_agent(meta.get("cli", provider_key), ["--model", model])
        else:
            # API-only fallback: Python REPL with tools
            ensure_orchestrator()
            print(f"\n  [PULSE] Launching {model}...")
            from pulse.agents.interactive_chat import run_interactive
            return run_interactive(meta.get("worker_provider", provider_key), model)
