import { NextResponse } from "next/server";
import { ContextManager } from "@/lib/agents/ContextManager";

export async function GET() {
  try {
    const prompt = ContextManager.loadPrompt();
    const rules = ContextManager.loadRules();

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

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { promptText, rulesText } = body;

    if (promptText !== undefined) {
      ContextManager.updatePrompt(promptText);
    }

    if (rulesText !== undefined) {
      ContextManager.updateRules(rulesText);
    }

    // Compile global rules context map
    ContextManager.compileGlobalRules();

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