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

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

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)
}

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(`cd browser-use-service ${SEP} ${PIP} install -r requirements.txt`, "Installing Python dependencies")

// 3. Playwright browsers
run(`${PY} -m playwright install firefox chromium`, "Installing Playwright browsers")

// 4. .env file
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. Ollama model
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! ===")
