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

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

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

export async function GET() {
  try {
    if (fs.existsSync(configPath)) {
      const rawData = fs.readFileSync(configPath, "utf8");
      const config = JSON.parse(rawData);
      
      return NextResponse.json({
        success: true,
        config: {
          name: config.name || "Claude Local",
          workspaceRoot: config.workspaceRoot || "",
          scopedDirs: config.scopedDirs || [],
        },
      });
    }

    return NextResponse.json({
      success: true,
      config: {
        name: "Claude Local",
        workspaceRoot: "",
        scopedDirs: [],
      },
    });
  } 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 { name, workspaceRoot, scopedDirs } = body;

    ensureDir();

    const newConfig = {
      name: name || "Claude Local",
      workspaceRoot: workspaceRoot || "",
      scopedDirs: scopedDirs || [],
    };

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

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