// ── One-command Setup ──────────────────────────────────────────────
// Run via: npm run setup
// Does the following in order:
//   1. npm install (Node.js dependencies)
//   2. pip install -r requirements.txt (Python dependencies)
//   3. playwright install firefox chromium (Playwright browsers)
//   4. Copies .env.example to .env.local if not exists
//
// All steps are cross-platform (Windows, Mac, Linux).
// Uses execSync for simplicity since each step blocks the next.

import { execSync } from "node:child_process"
import { existsSync, copyFileSync } from "node:fs"
import { platform } from "node:os"

const SEP = platform() === "win32" ? "&" : ";"

// Auto-detect Python executable (python vs python3)
function detectPython() {
  const candidates = platform() === "win32" ? ["python", "python3"] : ["python3", "python"]
  for (const cmd of candidates) {
    try {
      execSync(`${cmd} --version`, { stdio: "pipe", timeout: 5000 })
      return cmd
    } catch {}
  }
  console.error("Python not found. Install Python 3 from https://python.org")
  process.exit(1)
}

// Auto-detect pip (pip vs pip3), fall back to python -m pip
function detectPip(python) {
  const candidates = platform() === "win32" ? ["pip", "pip3"] : ["pip3", "pip"]
  for (const cmd of candidates) {
    try {
      execSync(`${cmd} --version`, { stdio: "pipe", timeout: 5000 })
      return cmd
    } catch {}
  }
  return `${python} -m pip`
}

const PY = detectPython()
const PIP = detectPip(PY)

function run(cmd, label) {
  console.log(`\n── ${label} ──`)
  try {
    execSync(cmd, { stdio: "inherit", timeout: 120000 })
  } catch (e) {
    console.error(`  ✗ Failed: ${e.message}`)
    process.exit(1)
  }
}

console.log("=== CoastIT CRM Setup ===\n")

// 1. Node dependencies
run("npm install", "Installing Node.js dependencies")

// 2. Python dependencies (run from browser-use-service directory)
run(`cd browser-use-service ${SEP} ${PIP} install -r requirements.txt`, "Installing Python dependencies")

// 3. Playwright browsers (Firefox for primary scraping, Chromium for Chrome/Edge/Opera + Agent fallback)
run(`${PY} -m playwright install firefox chromium`, "Installing Playwright browsers")

// 4. .env file — create from template if it doesn't exist
if (!existsSync(".env.local")) {
  console.log("\n── Creating .env.local ──")
  copyFileSync(".env.example", ".env.local")
  console.log("  ✓ Created .env.local from .env.example — edit it with your settings")
} else {
  console.log("\n── .env.local already exists, skipping ──")
}

// 5. Remaining manual steps
console.log("\n── Next steps ──")
console.log("  1. Make sure PostgreSQL is running with database 'crm'")
console.log("  2. Pull the Ollama model:  ollama pull dolphin-llama3:8b")
console.log("  3. Edit .env.local with your settings")
console.log("  4. Run:  npm run dev")
console.log("\n=== Setup complete! ===")
