// ── Ollama Launcher ────────────────────────────────────────────────
// Checks if Ollama is already running. If not, finds the binary and
// starts it as a detached background process.
// Cross-platform: uses tasklist (Windows) or pgrep (Linux/Mac) to
// detect running process; uses where/which to find the binary.

import { execSync, spawn } from "node:child_process"
import { platform } from "node:os"

function isRunning() {
  try {
    if (platform() === "win32") {
      execSync('tasklist /FI "IMAGENAME eq ollama.exe" 2>nul | findstr ollama', { stdio: "pipe", timeout: 3000 })
    } else {
      execSync('pgrep -x ollama', { stdio: "pipe", timeout: 3000 })
    }
    return true
  } catch {
    return false
  }
}

function findOllama() {
  if (platform() === "win32") {
    // Try PATH first, then common install locations
    try {
      return execSync("where ollama", { encoding: "utf8", timeout: 3000 }).trim().split("\n")[0]
    } catch {}
    const local = `${process.env.LOCALAPPDATA}\\Programs\\Ollama\\ollama.exe`
    const programFiles = `${process.env.PROGRAMFILES}\\Ollama\\ollama.exe`
    if (local) try { execSync(`"${local}" --version`, { stdio: "ignore", timeout: 2000 }); return local } catch {}
    if (programFiles) try { execSync(`"${programFiles}" --version`, { stdio: "ignore", timeout: 2000 }); return programFiles } catch {}
  } else {
    try { return execSync("which ollama", { encoding: "utf8", timeout: 3000 }).trim() } catch {}
  }
  return null
}

if (!isRunning()) {
  const bin = findOllama()
  if (!bin) {
    console.error("Ollama not found. Install from https://ollama.com")
    process.exit(1)
  }
  console.log("Starting Ollama...")
  // Spawn detached so it outlives this script and the npm process
  if (platform() === "win32") {
    spawn(bin, ["serve"], { stdio: "ignore", detached: true, windowsHide: true }).unref()
  } else {
    spawn(bin, ["serve"], { stdio: "ignore", detached: true }).unref()
  }
  // Give it a moment to start listening
  execSync("sleep 3", { stdio: "ignore", timeout: 5000 })
} else {
  console.log("Ollama already running")
}
