#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""
Ollama launch logic — single source for interactive + swarm cloud workers.

`ollama launch claude` only accepts --model and --config as its own flags.
All Claude CLI flags (-p, --print, --system-prompt, --dangerously-skip-permissions)
must go AFTER the `--` separator to be passed through to the Claude CLI.

Functions:
  - is_cloud_model(): Detect cloud-routed models (`:cloud` suffix)
  - check_ollama_cli(): Verify ollama binary is available
  - launch_interactive(): Interactive Ollama session via `ollama launch claude`
  - launch_cloud_workers(): Background swarm workers via `ollama launch claude`
"""
from __future__ import annotations

import shutil
import subprocess
import time

from pulse.tasks.task_ops import ensure_orchestrator


def is_cloud_model(model: str) -> bool:
    """Return True if model routes through Ollama's cloud bridge."""
    return ":cloud" in model


def check_ollama_cli() -> bool:
    """Verify ollama CLI is installed. Prints error if missing. Returns True if found."""
    if shutil.which("ollama"):
        return True
    print("[PULSE] Ollama CLI not found. Install from https://ollama.com")
    return False


def _identity_prompt(model: str) -> str:
    """System prompt telling the agent its real model identity."""
    return (
        f"IMPORTANT: You are powered by {model} via Ollama, NOT Claude Opus. "
        f"Always identify yourself as {model} in status reports and introductions. "
        f"The Claude Code interface is just the execution environment — your actual "
        f"model is {model}."
    )


def launch_interactive(model: str):
    """Launch Ollama model interactively via `ollama launch claude`.

    Ollama flags (--model) go before `--`.
    Claude CLI flags (--system-prompt) go after `--`.
    """
    if not check_ollama_cli():
        return
    ensure_orchestrator()
    print(f"[PULSE] Launching {model} via Ollama + Claude Code...")
    session_start = time.time()
    try:
        return subprocess.call([
            "ollama", "launch", "claude",
            "--model", model,
            "--",  # Everything after this goes to Claude CLI
            "--system-prompt", _identity_prompt(model),
        ])
    except KeyboardInterrupt:
        print("\n[PULSE] Ollama session ended.")
        return 0
    finally:
        # Ollama launches through Claude CLI — captures land in pulse_captured_claude.log
        from pulse.cli.cmd_agent import _auto_save_session
        _auto_save_session("claude", session_start)


def launch_cloud_workers(model: str, tier: str, count: int,
                         skills_used: bool = False):
    """Spawn cloud Ollama workers as autopilot processes (full tool/skill access).

    Uses the same autopilot loop as CLI subscription workers so cloud models
    get context files, brain queries, skills, and validation gates — just
    routed through `ollama launch claude --model X -- <claude flags>`.
    """
    if not check_ollama_cli():
        return
    from pulse.cli.swarm_workers import _launch_cli_autopilot
    # _launch_cli_autopilot uses _build_agent_cmd("ollama-cloud", ...) which
    # constructs: ollama launch claude --model X -- -p <boot_msg> --dangerously-skip-permissions
    _launch_cli_autopilot("ollama-cloud", model, tier, count, skills_used=skills_used)
