import { NextResponse } from "next/server";
import { getProjectConfigs, getProcessInfo } from "@/lib/autobuilder";
import path from "path";
import { execSync, spawn } from "child_process";

export const dynamic = "force-dynamic";

const PROJECT_ROOT = path.join(process.cwd(), "..");
const BUILDER_LOOP = path.join(PROJECT_ROOT, "skills", "build-feature", "builder_loop.py");

export async function GET(
  _req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const configs = await getProjectConfigs();
  const cfg = configs.find((c) => c.name === id);
  if (!cfg) return NextResponse.json({ error: "Project not found" }, { status: 404 });

  const proc = await getProcessInfo(cfg.autobuilderDir);
  return NextResponse.json(proc);
}

export async function POST(
  req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const configs = await getProjectConfigs();
  const cfg = configs.find((c) => c.name === id);
  if (!cfg) return NextResponse.json({ error: "Project not found" }, { status: 404 });

  const body = await req.json();
  const { action } = body;

  if (action === "start") {
    const info = await getProcessInfo(cfg.autobuilderDir);
    if (info.pid && info.running) {
      return NextResponse.json({ error: "Process already running" }, { status: 400 });
    }
    try {
      // Strip PORT to prevent the dashboard's port (3333) from leaking
      // into project dev servers via process.env.PORT inheritance.
      const cleanEnv = { ...process.env };
      delete cleanEnv.PORT;

      const child = spawn("python3", [BUILDER_LOOP, "--start", cfg.name], {
        cwd: PROJECT_ROOT,
        detached: true,
        stdio: "ignore",
        env: cleanEnv,
      });
      child.unref();
      return NextResponse.json({ success: true, message: `Started ${cfg.name} (PID ${child.pid})` });
    } catch (e) {
      return NextResponse.json({ error: `Failed to start: ${e}` }, { status: 500 });
    }
  }

  if (action === "stop") {
    try {
      const { writeFileSync } = await import("fs");
      writeFileSync(path.join(cfg.autobuilderDir, "stop"), "");
      return NextResponse.json({ success: true, message: "Stop signal sent" });
    } catch (e) {
      return NextResponse.json({ error: `Failed: ${e}` }, { status: 500 });
    }
  }

  if (action === "kill") {
    const info = await getProcessInfo(cfg.autobuilderDir);
    if (info.pid && info.running) {
      try {
        execSync(`kill -TERM ${info.pid}`, { timeout: 5000 });
        return NextResponse.json({ success: true, message: `Sent SIGTERM to PID ${info.pid}` });
      } catch (e) {
        return NextResponse.json({ error: `Failed: ${e}` }, { status: 500 });
      }
    }
    return NextResponse.json({ error: "No running process" }, { status: 400 });
  }

  return NextResponse.json({ error: "Unknown action" }, { status: 400 });
}
