import { NextResponse } from "next/server";
import { runPi } from "@/lib/find-pi";

export const dynamic = "force-dynamic";

// POST /api/packages/install
// body: { package: string; scope: "global" | "project"; cwd?: string }
export async function POST(req: Request) {
  try {
    const body = await req.json() as { package?: string; scope?: string; cwd?: string };
    const pkg = body.package?.trim();
    const scope = body.scope ?? "global";
    const cwd = body.cwd;

    if (!pkg) {
      return NextResponse.json({ error: "package name required" }, { status: 400 });
    }

    // Normalize: if it doesn't start with npm:, add it
    const source = pkg.startsWith("npm:") || pkg.startsWith("git:") || pkg.startsWith("https://") || pkg.startsWith("ssh://") || pkg.startsWith("/") || pkg.startsWith(".")
      ? pkg
      : `npm:${pkg}`;

    const args = ["install", source];
    if (scope === "project") args.push("-l");

    console.log(`[packages/install] running: pi ${args.join(" ")}`);
    const { stdout, stderr } = await runPi(args, {
      timeout: 120_000,
      cwd: scope === "project" && cwd ? cwd : undefined,
    });

    const output = stdout + stderr;
    // pi returns exit code 0 on success; check for error patterns
    const hasError = /error|failed|not found/i.test(output) && !/successfully/i.test(output);

    if (hasError && !output.includes("Installed package")) {
      return NextResponse.json({ error: output.slice(-500) || "Install failed" }, { status: 500 });
    }

    return NextResponse.json({ success: true, output: output.slice(0, 1000) });
  } catch (e: unknown) {
    const err = e as { stdout?: string; stderr?: string; message?: string };
    const output = ((err.stdout ?? "") + (err.stderr ?? "")).slice(-500);
    return NextResponse.json({ error: output || (err.message ?? String(e)) }, { status: 500 });
  }
}
