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, "aider.json");

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

function maskKey(key: string): string {
  if (!key) return "";
  if (key.length <= 8) return "********";
  return `${key.slice(0, 6)}...${key.slice(-4)}`;
}

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: {
          openaiApiKey: config.openaiApiKey ? maskKey(config.openaiApiKey) : "",
          anthropicApiKey: config.anthropicApiKey ? maskKey(config.anthropicApiKey) : "",
          geminiApiKey: config.geminiApiKey ? maskKey(config.geminiApiKey) : "",
          model: config.model || "claude-3-5-sonnet",
          extraFlags: config.extraFlags || "",
          workspaceRoot: config.workspaceRoot || "",
          scopedDirs: config.scopedDirs || [],
        },
      });
    }

    return NextResponse.json({
      success: true,
      config: {
        openaiApiKey: "",
        anthropicApiKey: "",
        geminiApiKey: "",
        model: "claude-3-5-sonnet",
        extraFlags: "",
        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 { openaiApiKey, anthropicApiKey, geminiApiKey, model, extraFlags, workspaceRoot, scopedDirs } = body;

    ensureDir();

    let existingConfig = {
      openaiApiKey: "",
      anthropicApiKey: "",
      geminiApiKey: "",
      model: "claude-3-5-sonnet",
      extraFlags: "",
      workspaceRoot: "",
      scopedDirs: [] as string[],
    };

    if (fs.existsSync(configPath)) {
      try {
        existingConfig = JSON.parse(fs.readFileSync(configPath, "utf8"));
      } catch (e) {
        console.error("Failed to parse existing aider.json:", e);
      }
    }

    // Determine whether to use new keys or preserve existing ones if masked sentinels are received
    const finalOpenaiKey = (openaiApiKey && openaiApiKey.includes("...")) 
      ? existingConfig.openaiApiKey 
      : (openaiApiKey || "");

    const finalAnthropicKey = (anthropicApiKey && anthropicApiKey.includes("...")) 
      ? existingConfig.anthropicApiKey 
      : (anthropicApiKey || "");

    const finalGeminiKey = (geminiApiKey && geminiApiKey.includes("...")) 
      ? existingConfig.geminiApiKey 
      : (geminiApiKey || "");

    const newConfig = {
      openaiApiKey: finalOpenaiKey,
      anthropicApiKey: finalAnthropicKey,
      geminiApiKey: finalGeminiKey,
      model: model || "claude-3-5-sonnet",
      extraFlags: extraFlags || "",
      workspaceRoot: workspaceRoot || "",
      scopedDirs: scopedDirs || [],
    };

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

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