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

const ENGINE_FILE_PATH = path.join(process.cwd(), 'engine.json');

export async function GET() {
  try {
    if (fs.existsSync(ENGINE_FILE_PATH)) {
      const data = fs.readFileSync(ENGINE_FILE_PATH, 'utf-8');
      const json = JSON.parse(data);
      return NextResponse.json({ engine: json.engine || 'xcu ULTRA' });
    }
    return NextResponse.json({ engine: 'xcu ULTRA' });
  } catch {
    return NextResponse.json({ engine: 'xcu ULTRA' });
  }
}

export async function POST(req: Request) {
  try {
    const body = await req.json();
    if (body.engine === 'xcu ULTRA' || body.engine === 'XCU Ultra' || body.engine === 'XCU_DIRECTOR') {
      fs.writeFileSync(ENGINE_FILE_PATH, JSON.stringify({ engine: body.engine }), 'utf-8');
      return NextResponse.json({ success: true, engine: body.engine });
    }
    return NextResponse.json({ success: false, error: 'Invalid engine' }, { status: 400 });
  } catch {
    return NextResponse.json({ success: false, error: 'Failed to update engine' }, { status: 500 });
  }
}
