import { NextResponse } from 'next/server';
import { recordEvent } from '@/lib/auditDb';
import { buildCharacterSpec, cleanupCharacterAnchor } from '@/lib/packGenerator';
import { loadSession, saveSession } from '@/lib/storage';
import type { CleanupCharacterRequest, CleanupCharacterResponse } from '@/lib/types';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function POST(req: Request) {
  const { sessionId, imageId, force = false, preserveLevel = 'normal' } = (await req.json()) as CleanupCharacterRequest;

  if (!sessionId || !imageId) {
    return NextResponse.json({ error: 'sessionId and imageId required' }, { status: 400 });
  }

  const session = await loadSession(sessionId);
  if (!session) return NextResponse.json({ error: 'session not found' }, { status: 404 });

  const sourceImage = session.images.find(image => image.id === imageId);
  if (!sourceImage) return NextResponse.json({ error: 'image not found' }, { status: 404 });

  try {
    recordEvent({ action: 'character.cleanup_started', sessionId, targetType: 'image', targetId: imageId, status: 'started', metadata: { force, preserveLevel } });
    const characterSpec = session.characterSpec?.sourceImageId === imageId
      ? session.characterSpec
      : await buildCharacterSpec(session, sourceImage);
    const cleaned = await cleanupCharacterAnchor({ session, sourceImage, characterSpec, force, preserveLevel });
    session.characterSpec = cleaned.characterSpec;
    await saveSession(session);
    recordEvent({
      action: 'character.cleanup_completed',
      sessionId,
      targetType: 'image',
      targetId: imageId,
      status: 'ok',
      provider: cleaned.provider,
      metadata: { preserveLevel, cleanReferenceImageUrl: cleaned.cleanReferenceImageUrl },
    });

    return NextResponse.json({
      characterSpec: cleaned.characterSpec,
      cleanReferenceImageUrl: cleaned.cleanReferenceImageUrl,
      provider: cleaned.provider,
    } satisfies CleanupCharacterResponse);
  } catch (error) {
    recordEvent({ action: 'character.cleanup_failed', sessionId, targetType: 'image', targetId: imageId, status: 'error', message: String(error) });
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}
