import { NextRequest, NextResponse } from 'next/server';
import { buildCustomApiHeaders, fetchWithRetry, parseCustomApiError } from '@/lib/custom-api-fetch';
import { resolveServerApiConfig } from '@/lib/server-api-config';

interface CustomApiConfig {
  apiUrl: string;
  modelName: string;
  apiKey: string;
  provider: string;
  customApiKeyId?: string;
  systemApiId?: string;
}

const SUGGEST_TIMEOUT = 60_000;

function parseOptimizedPrompt(content: string): { prompt: string; negativePrompt?: string } {
  const trimmed = content.trim();
  const jsonMatch = trimmed.match(/\{[\s\S]*\}/);
  if (jsonMatch) {
    try {
      const parsed = JSON.parse(jsonMatch[0]) as Record<string, unknown>;
      const prompt = typeof parsed.prompt === 'string'
        ? parsed.prompt
        : typeof parsed.positivePrompt === 'string'
          ? parsed.positivePrompt
          : typeof parsed.positive === 'string'
            ? parsed.positive
            : '';
      const negativePrompt = typeof parsed.negativePrompt === 'string'
        ? parsed.negativePrompt
        : typeof parsed.negative === 'string'
          ? parsed.negative
          : '';
      if (prompt.trim()) {
        return {
          prompt: prompt.trim(),
          negativePrompt: negativePrompt.trim() || undefined,
        };
      }
    } catch {
      // Fall through to labeled text parsing.
    }
  }

  const positiveMatch = trimmed.match(/(?:正向提示词|优化提示词|正面提示词|Positive Prompt|Prompt)\s*[:：]\s*([\s\S]*?)(?=(?:负向提示词|负面提示词|反向提示词|Negative Prompt|Negative)\s*[:：]|$)/i);
  const negativeMatch = trimmed.match(/(?:负向提示词|负面提示词|反向提示词|Negative Prompt|Negative)\s*[:：]\s*([\s\S]*)$/i);
  const prompt = (positiveMatch?.[1] || trimmed).trim();
  const negativePrompt = negativeMatch?.[1]?.trim();

  return {
    prompt,
    negativePrompt: negativePrompt || undefined,
  };
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const {
      prompt,
      customApiConfig,
      systemPrefix,
    } = body as {
      prompt?: string;
      modelName?: string;
      customApiConfig?: CustomApiConfig;
      systemPrefix?: string;
    };

    if (!prompt) {
      return NextResponse.json({ error: '请提供创作描述' }, { status: 400 });
    }

    const resolvedCustomApiConfig = await resolveServerApiConfig(request, customApiConfig);

    // Use custom/system multimodal model API if provided
    if (resolvedCustomApiConfig && resolvedCustomApiConfig.apiKey) {
      const resolvedApiKey = resolvedCustomApiConfig.apiKey;
      const endpoint = resolvedCustomApiConfig.apiUrl;
      if (!endpoint) {
        return NextResponse.json({ error: '多模态模型API未配置请求地址' }, { status: 400 });
      }
      if (!resolvedCustomApiConfig.modelName) {
        return NextResponse.json({ error: '多模态模型API未配置模型名称' }, { status: 400 });
      }

      // Build system message with optional prefix
      const baseInstruction = systemPrefix
        ? `${systemPrefix}。`
        : '你是一个专业的AI绘图/视频提示词优化专家。';
      const systemMessage = `${baseInstruction}请基于用户描述同时生成正向提示词和反向/负面提示词。正向提示词要更详细、更有画面感、更适合生成模型；负面提示词要列出应避免的低质量、畸形、错误结构、画面瑕疵、文字水印等内容。只返回JSON，不要解释，格式为：{"prompt":"优化后的正向提示词","negativePrompt":"优化后的负面提示词"}`;

      const headers = buildCustomApiHeaders(resolvedApiKey);
      const chatBody = {
        model: resolvedCustomApiConfig.modelName,
        stream: false,
        messages: [
          { role: 'system', content: systemMessage },
          { role: 'user', content: prompt },
        ],
      };

      console.log('[Suggest Prompt] Using custom multimodal model:', resolvedCustomApiConfig.modelName, '| prefix:', systemPrefix || 'default');

      try {
        const response = await fetchWithRetry(
          endpoint,
          {
            method: 'POST',
            headers,
            body: JSON.stringify(chatBody),
          },
          SUGGEST_TIMEOUT,
          1,
        );

        if (!response.ok) {
          const errorText = await response.text();
          console.error('[Suggest Prompt] API error:', response.status, errorText.slice(0, 200));
          return NextResponse.json(
            { error: parseCustomApiError(response.status, errorText) },
            { status: response.status >= 500 ? 502 : response.status }
          );
        }

        const data = await response.json();
        const choices = (data as Record<string, unknown>).choices as Array<Record<string, unknown>> | undefined;
        if (choices && choices.length > 0) {
          const message = choices[0].message as Record<string, unknown>;
          const content = message?.content;
          if (typeof content === 'string' && content.trim()) {
            return NextResponse.json(parseOptimizedPrompt(content));
          }
        }

        return NextResponse.json({ error: '多模态模型未返回有效内容' }, { status: 502 });
      } catch (fetchError: unknown) {
        const msg = fetchError instanceof Error ? fetchError.message : '请求失败';
        console.error('[Suggest Prompt] Fetch error:', msg);
        return NextResponse.json({ error: `提示词优化失败: ${msg}` }, { status: 502 });
      }
    }

    // No multimodal model configured
    return NextResponse.json({ error: '未配置多模态模型，请在API设置中添加多模态模型' }, { status: 400 });
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : '提示词优化失败';
    console.error('[Suggest Prompt Error]', message);
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
