Files
lensflix/lib/card-generator.ts
2026-06-18 17:13:24 +02:00

61 lines
2.3 KiB
TypeScript

import type { CardType } from "./cards";
import { getCachedCard, setCachedCard } from "./cache";
import { generateStructuredResponse } from "./llm";
import {
internationalRatingsSchema,
ratingExplainedSchema,
} from "./schemas";
import { formatMovieContext, getMovieDetails } from "./tmdb";
const PROMPTS: Record<CardType, string> = {
rating_explained: `Analyze why this film received its age rating.
You MUST return ONLY valid JSON matching this exact structure (no extra keys, no markdown):
{
"officialRating": string,
"region": string,
"summary": string,
"factors": array of {
"category": one of exactly ["violence", "language", "sexuality", "substances", "frightening", "other"] (use ONLY these strings, no synonyms like "gore" or "nudity" — map to closest),
"intensity": one of exactly ["mild", "moderate", "strong"],
"description": string,
"approximateTiming": string (optional, e.g. "12:45"),
"confidence": one of ["high", "medium", "low"] (optional)
},
"borderlineNote": string (optional)
}
Focus on specific scenes or content patterns that drove the rating. Be precise with the allowed category and intensity values.`,
international_ratings: `Summarize how this film is rated across countries using the certification data provided.
Return JSON with: ratings (array of {country, countryCode, rating, descriptors?}), discrepancyNote, strictestCountry (optional), mostLenientCountry (optional).
Include at least US, GB, ES, DE, FR when data exists. Explain notable differences.`,
};
const SCHEMAS = {
rating_explained: ratingExplainedSchema,
international_ratings: internationalRatingsSchema,
} as const;
export async function generateCard(movieId: number, cardType: CardType) {
const cached = await getCachedCard(movieId, cardType);
if (cached) {
const schema = SCHEMAS[cardType];
if (schema.safeParse(cached).success) {
return { data: cached, cached: true };
}
// stale/invalid cached data (e.g. from before prompt/schema tightening) — regenerate
}
const movie = await getMovieDetails(movieId);
const context = formatMovieContext(movie);
const prompt = `${PROMPTS[cardType]}
Movie context:
${context}`;
const schema = SCHEMAS[cardType];
const data = await generateStructuredResponse(schema, prompt);
await setCachedCard(movieId, cardType, data);
return { data, cached: false };
}