/**
 * Rig Service Integration for QwenClaw Daemon
 * Checks and manages Rig service availability
 */

import { spawn } from "child_process";
import { join } from "path";

const RIG_HOST = process.env.RIG_HOST || "127.0.0.1";
const RIG_PORT = process.env.RIG_PORT || "8080";

/**
 * Check if Rig service is available
 */
export async function checkRigService(): Promise<boolean> {
  try {
    const res = await fetch(`http://${RIG_HOST}:${RIG_PORT}/health`);
    const data = await res.json();
    return data.status === "ok";
  } catch {
    return false;
  }
}

/**
 * Start Rig service as child process
 */
export function startRigService(): Promise<boolean> {
  return new Promise((resolve) => {
    const rigDir = join(process.cwd(), "rig-service");
    
    console.log("🦀 Starting Rig service...");
    
    const rigProcess = spawn("cargo", ["run", "--release"], {
      cwd: rigDir,
      detached: true,
      stdio: "ignore",
      windowsHide: true,
    });

    rigProcess.unref();

    // Wait for service to start
    setTimeout(async () => {
      const available = await checkRigService();
      if (available) {
        console.log(`✅ Rig service started on http://${RIG_HOST}:${RIG_PORT}`);
      } else {
        console.log("⚠️  Rig service may still be starting...");
      }
      resolve(available);
    }, 5000);
  });
}

/**
 * Initialize Rig integration
 */
export async function initRigIntegration(): Promise<void> {
  const available = await checkRigService();
  
  if (available) {
    console.log(`✅ Rig service available at http://${RIG_HOST}:${RIG_PORT}`);
  } else {
    console.log("ℹ️  Rig service not running. Start with: bun run rig:start");
  }
}
