Spaces:
Sleeping
Sleeping
| import { NextRequest, NextResponse } from 'next/server'; | |
| import type { ApiResponse, StructureRequest, StructureData } from '@/types/api'; | |
| import type { Slide } from '@/types/carousel'; | |
| import { getAnalyticsSummary } from '@/lib/analytics/calculate'; | |
| import { generateInsightsFromMetrics, formatInsightsForPrompt } from '@/lib/analytics/insights'; | |
| import { filterHighConfidenceInsights } from '@/lib/insights/recommender'; | |
| import { structureCarousel } from '@/lib/ai/structure'; | |
| export async function POST(req: NextRequest): Promise<NextResponse<ApiResponse<StructureData>>> { | |
| try { | |
| const body: StructureRequest = await req.json(); | |
| if (!body.text) { | |
| return NextResponse.json({ success: false, error: 'Missing text' }, { status: 400 }); | |
| } | |
| // Phase 13: Fetch insights and inject them into generation context | |
| let appliedInsights: StructureData['appliedInsights'] = undefined; | |
| let insightPrompt = ''; | |
| try { | |
| const summary = await getAnalyticsSummary('weekly'); | |
| const allInsights = generateInsightsFromMetrics(summary.insights); | |
| const highConfInsights = filterHighConfidenceInsights(allInsights); | |
| if (highConfInsights.length > 0) { | |
| insightPrompt = formatInsightsForPrompt(highConfInsights); | |
| appliedInsights = highConfInsights.slice(0, 3); | |
| } | |
| } catch (insightErr) { | |
| console.warn('[structure] insights fetch failed, continuing without insights:', insightErr); | |
| } | |
| // Call the LLM structurer | |
| const structureResult = await structureCarousel({ | |
| text: body.text, | |
| template: body.template, | |
| palette: body.palette, | |
| insights: insightPrompt | |
| }); | |
| if (!structureResult.success) { | |
| return NextResponse.json({ success: false, error: structureResult.error }, { status: 500 }); | |
| } | |
| const { slides, title } = structureResult.data as StructureData; | |
| return NextResponse.json({ | |
| success: true, | |
| data: { | |
| slides: slides, | |
| title: title || 'Generated Carousel', | |
| appliedInsights: appliedInsights && appliedInsights.length > 0 ? appliedInsights : undefined, | |
| }, | |
| }); | |
| } catch (err) { | |
| console.error('[structure] failed:', err); | |
| return NextResponse.json({ success: false, error: 'Something went wrong — please try again' }, { status: 500 }); | |
| } | |
| } | |