import { NextResponse } from 'next/server';
import { recordEvent } from '@/lib/auditDb';
import { buildCharacterSpec, cleanupCharacterAnchor } from '@/lib/packGenerator';
import { detectProvider } from '@/lib/providers';
import { loadSession, saveSession } from '@/lib/storage';
import type { LockCharacterRequest, LockCharacterResponse } from '@/lib/types';

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

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

  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 });

  if (!force && session.characterSpec?.sourceImageId === imageId) {
    const response: LockCharacterResponse = {
      characterSpec: session.characterSpec,
      provider: detectProvider(),
    };
    recordEvent({ action: 'character.lock_cached', sessionId, targetType: 'image', targetId: imageId, status: 'ok', provider: response.provider });
    return NextResponse.json(response);
  }

  try {
    recordEvent({ action: 'character.lock_started', sessionId, targetType: 'image', targetId: imageId, status: 'started', provider: detectProvider(), metadata: { force } });
    const characterSpec = await buildCharacterSpec(session, sourceImage);
    const cleaned = await cleanupCharacterAnchor({
      session,
      sourceImage,
      characterSpec,
      force,
    });
    session.characterSpec = cleaned.characterSpec;
    await saveSession(session);

    const response: LockCharacterResponse = {
      characterSpec: cleaned.characterSpec,
      provider: detectProvider(),
    };
    recordEvent({
      action: 'character.lock_completed',
      sessionId,
      targetType: 'image',
      targetId: imageId,
      status: 'ok',
      provider: response.provider,
      metadata: { name: cleaned.characterSpec.name, cleanReferenceImageUrl: cleaned.cleanReferenceImageUrl },
    });
    return NextResponse.json(response);
  } catch (error) {
    recordEvent({ action: 'character.lock_failed', sessionId, targetType: 'image', targetId: imageId, status: 'error', provider: detectProvider(), message: String(error) });
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}
