import { NextRequest } from 'next/server'

const BACKEND_BASE = process.env.BACKEND_INTERNAL_URL || process.env.NEXT_PUBLIC_BACKEND_URL;

export async function GET(
  req: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  // 优先从动态路由 params（Promise）获取，其次从 URL 最后一段兜底
  let id: string | undefined
  try {
    const { id: idFromParams } = await context.params
    id = idFromParams
  } catch {
    // ignore
  }
  if (!id) {
    id = new URL(req.url).pathname.split('/').pop() || undefined
  }

  if (!id) {
    return Response.json({ error: 'missing id' }, { status: 400 })
  }

  if (!BACKEND_BASE) {
    return new Response('NEXT_PUBLIC_BACKEND_URL 未配置', { status: 500 });
  }
  const resp = await fetch(`${BACKEND_BASE}/analysis-results/${encodeURIComponent(id)}`);
  const text = await resp.text();
  if (!resp.ok) {
    return new Response(text || 'not found', { status: resp.status });
  }
  // 将后端 DTO（generated_at 等）适配为前端旧结构字段（createdAt）
  try {
    const dto = JSON.parse(text);
    const adapted = {
      id: dto.id,
      symbol: dto.symbol,
      createdAt: dto.generated_at || dto.generatedAt || null,
      content: dto.content,
      module_id: dto.module_id,
      model_name: dto.model_name,
      meta_data: dto.meta_data,
    };
    return Response.json(adapted);
  } catch {
    return Response.json({ error: 'invalid response from backend' }, { status: 502 });
  }
}
