import { NextResponse } from "next/server";
import fs from "fs";
import path from "path";
import { exec } from "child_process";

const configDir = path.join(process.cwd(), ".ai", "neural-loom");
const configPath = path.join(configDir, "ssh.json");

function ensureDir() {
  if (!fs.existsSync(configDir)) {
    fs.mkdirSync(configDir, { recursive: true });
  }
}

export async function GET() {
  try {
    if (fs.existsSync(configPath)) {
      const data = fs.readFileSync(configPath, "utf8");
      const config = JSON.parse(data);
      return NextResponse.json({ success: true, config });
    }
    return NextResponse.json({
      success: true,
      config: {
        host: "",
        port: 22,
        username: "",
        privateKeyPath: "",
      },
    });
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : "Unknown error";
    return NextResponse.json({ success: false, error: errorMessage }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { test, host, port, username, privateKeyPath } = body;

    if (!host || !username) {
      return NextResponse.json({ success: false, error: "Host and Username are required." }, { status: 400 });
    }

    const numericPort = port ? parseInt(String(port), 10) : 22;

    if (test) {
      // Test the SSH connection
      const success = await new Promise<{ ok: boolean; message: string }>((resolve) => {
        const keyOpt = privateKeyPath ? `-i "${privateKeyPath}"` : "";
        const portOpt = `-p ${numericPort}`;
        
        // StrictHostKeyChecking=accept-new automatically adds host key to known_hosts if it's new
        // BatchMode=yes prevents it from waiting for user password prompt
        const sshCmd = `ssh -o ConnectTimeout=3 -o BatchMode=yes -o StrictHostKeyChecking=accept-new ${keyOpt} ${portOpt} ${username}@${host} "echo CONNECTED"`;

        exec(sshCmd, (error, stdout, stderr) => {
          if (error) {
            resolve({ ok: false, message: stderr.trim() || error.message });
          } else if (stdout.trim().includes("CONNECTED")) {
            resolve({ ok: true, message: "Successfully connected to remote VM!" });
          } else {
            resolve({ ok: false, message: stderr.trim() || "Failed to verify remote host verification print." });
          }
        });
      });

      return NextResponse.json({ success: success.ok, message: success.message });
    }

    // Save SSH connection configuration
    ensureDir();
    const config = {
      host,
      port: numericPort,
      username,
      privateKeyPath: privateKeyPath || "",
    };

    fs.writeFileSync(configPath, JSON.stringify(config, null, 2), "utf8");
    return NextResponse.json({ success: true, message: "SSH configuration saved successfully!" });

  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : "Unknown error";
    return NextResponse.json({ success: false, error: errorMessage }, { status: 500 });
  }
}
