simplificando app

This commit is contained in:
2026-06-18 17:13:24 +02:00
parent cdf2893b94
commit f977925880
16 changed files with 82 additions and 614 deletions
+5 -5
View File
@@ -1,15 +1,15 @@
# Film Intel # Film Intel
Advanced movie insight you won't find in one click. Search any film and generate Reliable film age ratings, explained. Search any film and get a clear breakdown
ratings explained, skip guides, sensitivity warnings, international ratings, of why it received its age rating, plus how that rating differs across
production facts, and historical-accuracy breakdowns. countries.
## Requirements ## Requirements
- Node.js 22 - Node.js 22
- A TMDB API key (https://www.themoviedb.org/settings/api) - A TMDB API key (https://www.themoviedb.org/settings/api)
- An LLM API key (OpenRouter or any OpenAI-compatible endpoint) - An LLM API key (OpenRouter or any OpenAI-compatible endpoint)
- PostgreSQL for caching generated insight cards (optional but recommended) - PostgreSQL for caching generated rating cards (optional but recommended)
Copy `.env.example` to `.env` and fill in the keys. Copy `.env.example` to `.env` and fill in the keys.
@@ -33,7 +33,7 @@ npm install
npm run dev npm run dev
``` ```
> Without a database the insight cards will still generate (they just won't be > Without a database the rating cards will still generate (they just won't be
> cached), thanks to graceful cache handling. Run `npm run db:migrate` against a > cached), thanks to graceful cache handling. Run `npm run db:migrate` against a
> reachable Postgres to enable caching. > reachable Postgres to enable caching.
+1 -1
View File
@@ -14,7 +14,7 @@ const geistMono = Geist_Mono({
export const metadata: Metadata = { export const metadata: Metadata = {
title: "Film Intel", title: "Film Intel",
description: "Advanced movie insight you won't find in one click", description: "Reliable film age ratings, explained",
}; };
export default function RootLayout({ export default function RootLayout({
-41
View File
@@ -1,41 +0,0 @@
import { notFound } from "next/navigation";
import { MovieHeader } from "@/components/MovieHeader";
import { MovieInsightPanel } from "@/components/MovieInsightPanel";
import { getMovieDetails } from "@/lib/tmdb";
export default async function MoviePage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
const movieId = Number(id);
if (!Number.isFinite(movieId) || movieId <= 0) {
notFound();
}
let movie;
try {
movie = await getMovieDetails(movieId);
} catch {
notFound();
}
return (
<main className="mx-auto min-h-screen w-full max-w-6xl px-6 py-10">
<div className="space-y-10">
<MovieHeader movie={movie} />
<MovieInsightPanel
movieId={movie.id}
genres={movie.genres.map((genre) => genre.name)}
/>
</div>
<footer className="mt-16 border-t border-stone-200 pt-6 text-center text-xs text-stone-500">
AI-generated content for informational purposes. Verify timestamps on
your copy.
</footer>
</main>
);
}
+5 -36
View File
@@ -1,6 +1,6 @@
"use client"; "use client";
import { useEffect, useState } from "react"; import { useState } from "react";
import { SearchBar } from "@/components/SearchBar"; import { SearchBar } from "@/components/SearchBar";
import { MovieHeader } from "@/components/MovieHeader"; import { MovieHeader } from "@/components/MovieHeader";
import { MovieInsightPanel } from "@/components/MovieInsightPanel"; import { MovieInsightPanel } from "@/components/MovieInsightPanel";
@@ -16,33 +16,6 @@ export default function HomePage() {
const [isLoadingMovie, setIsLoadingMovie] = useState(false); const [isLoadingMovie, setIsLoadingMovie] = useState(false);
const [movieError, setMovieError] = useState<string | null>(null); const [movieError, setMovieError] = useState<string | null>(null);
// Preload a random interesting movie on initial page load to demonstrate the app
useEffect(() => {
const DEMO_IDS = [27205, 157336, 155, 550, 496243, 424]; // Inception, Interstellar, Dark Knight, Fight Club, Parasite, Schindler's List
const loadDemo = async () => {
const id = DEMO_IDS[Math.floor(Math.random() * DEMO_IDS.length)];
try {
const res = await fetch(`/api/movie/${id}`);
if (!res.ok) return;
const details: TmdbMovieDetails = await res.json();
const minimalSearch: TmdbSearchResult = {
id: details.id,
title: details.title,
release_date: details.release_date || "",
poster_path: details.poster_path,
overview: details.overview || "",
};
setSelectedMovie(minimalSearch);
setMovieDetails(details);
} catch {
// silently fall back to empty state if demo preload fails
}
};
if (!selectedMovie) {
void loadDemo();
}
}, []);
const handleSelect = async (movie: TmdbSearchResult) => { const handleSelect = async (movie: TmdbSearchResult) => {
setSelectedMovie(movie); setSelectedMovie(movie);
setMovieDetails(null); setMovieDetails(null);
@@ -77,7 +50,7 @@ export default function HomePage() {
Film Intel Film Intel
</span> </span>
<span className="hidden truncate text-xs text-stone-500 sm:inline"> <span className="hidden truncate text-xs text-stone-500 sm:inline">
Movie insight you won&apos;t find in one click Reliable film ratings, explained
</span> </span>
</div> </div>
@@ -95,9 +68,8 @@ export default function HomePage() {
{!selectedMovie && ( {!selectedMovie && (
<div className="flex flex-col items-center justify-center py-16 text-center"> <div className="flex flex-col items-center justify-center py-16 text-center">
<p className="max-w-md text-sm text-stone-600"> <p className="max-w-md text-sm text-stone-600">
Search for any film using the bar above. We&apos;ll generate Search for any film using the bar above. We&apos;ll explain its
ratings explained, skip guides, sensitivity warnings, production age rating and how it differs across countries.
facts, and more.
</p> </p>
</div> </div>
)} )}
@@ -136,10 +108,7 @@ export default function HomePage() {
</div> </div>
)} )}
<MovieInsightPanel <MovieInsightPanel movieId={selectedMovie.id} />
movieId={selectedMovie.id}
genres={movieDetails?.genres.map((g) => g.name) ?? []}
/>
</div> </div>
)} )}
</main> </main>
+5 -23
View File
@@ -1,35 +1,17 @@
"use client"; "use client";
import { useState } from "react"; import { useState } from "react";
import { import { CARD_META, CARD_TYPES, type CardType } from "@/lib/cards";
CARD_META,
CARD_TYPES,
shouldShowHistoricalAccuracy,
type CardType,
} from "@/lib/cards";
import { CardContent } from "./cards/CardContent"; import { CardContent } from "./cards/CardContent";
import { InfoCard } from "./InfoCard"; import { InfoCard } from "./InfoCard";
export function MovieInsightPanel({ export function MovieInsightPanel({ movieId }: { movieId: number }) {
movieId, const [selected, setSelected] = useState<CardType>(CARD_TYPES[0]);
genres,
}: {
movieId: number;
genres: string[];
}) {
const visibleCards = CARD_TYPES.filter((type) => {
if (type === "historical_accuracy") {
return shouldShowHistoricalAccuracy(genres);
}
return true;
});
const [selected, setSelected] = useState<CardType>(visibleCards[0]);
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3"> <div className="grid gap-4 sm:grid-cols-2">
{visibleCards.map((type) => ( {CARD_TYPES.map((type) => (
<InfoCard <InfoCard
key={type} key={type}
meta={CARD_META[type]} meta={CARD_META[type]}
-12
View File
@@ -2,12 +2,8 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import type { CardType } from "@/lib/cards"; import type { CardType } from "@/lib/cards";
import { HistoricalAccuracyView } from "./HistoricalAccuracy";
import { InternationalRatingsView } from "./InternationalRatings"; import { InternationalRatingsView } from "./InternationalRatings";
import { ProductionFactsView } from "./ProductionFacts";
import { RatingExplainedView } from "./RatingExplained"; import { RatingExplainedView } from "./RatingExplained";
import { SensitivityGuideView } from "./SensitivityGuide";
import { SkipGuideView } from "./SkipGuide";
interface CardContentProps { interface CardContentProps {
movieId: number; movieId: number;
@@ -99,16 +95,8 @@ export function CardContent({ movieId, cardType }: CardContentProps) {
switch (cardType) { switch (cardType) {
case "rating_explained": case "rating_explained":
return <RatingExplainedView data={data} />; return <RatingExplainedView data={data} />;
case "skip_guide":
return <SkipGuideView data={data} />;
case "sensitivity_guide":
return <SensitivityGuideView data={data} />;
case "international_ratings": case "international_ratings":
return <InternationalRatingsView data={data} />; return <InternationalRatingsView data={data} />;
case "production_facts":
return <ProductionFactsView data={data} />;
case "historical_accuracy":
return <HistoricalAccuracyView data={data} />;
default: default:
return null; return null;
} }
-76
View File
@@ -1,76 +0,0 @@
import {
historicalAccuracySchema,
type HistoricalAccuracy,
} from "@/lib/schemas";
export function HistoricalAccuracyView({ data }: { data: unknown }) {
const result = historicalAccuracySchema.safeParse(data);
if (!result.success) {
return (
<div className="rounded-2xl border border-stone-200 bg-white p-6 text-sm text-stone-700">
Could not display this insight (data format issue). Try another card or refresh later.
</div>
);
}
const parsed = result.data as HistoricalAccuracy;
return (
<div className="space-y-5 rounded-2xl border border-stone-200 bg-white p-6">
<div className="flex items-end gap-4">
<div>
<p className="text-xs uppercase tracking-wide text-stone-500">
Accuracy score
</p>
<p className="text-4xl font-semibold text-amber-700">
{parsed.accuracyScore}
<span className="text-lg text-stone-500">/100</span>
</p>
</div>
<p className="pb-1 text-sm capitalize text-stone-600">
Confidence: {parsed.confidence}
</p>
</div>
<p className="text-stone-700">{parsed.summary}</p>
{parsed.accurateElements.length > 0 && (
<div>
<p className="mb-2 text-sm font-medium text-stone-950">What holds up</p>
<ul className="space-y-2">
{parsed.accurateElements.map((item) => (
<li
key={item}
className="rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-stone-700"
>
{item}
</li>
))}
</ul>
</div>
)}
{parsed.inventions.length > 0 && (
<div>
<p className="mb-2 text-sm font-medium text-stone-950">
Dramatizations & inventions
</p>
<div className="space-y-3">
{parsed.inventions.map((item, index) => (
<div
key={`${item.claim}-${index}`}
className="rounded-xl border border-stone-200 bg-stone-100 p-4"
>
<p className="text-sm text-stone-700">
<span className="text-stone-500">Film claim:</span> {item.claim}
</p>
<p className="mt-2 text-sm text-stone-700">
<span className="text-stone-500">Reality:</span> {item.reality}
</p>
</div>
))}
</div>
</div>
)}
</div>
);
}
-70
View File
@@ -1,70 +0,0 @@
import {
productionFactsSchema,
type ProductionFacts,
} from "@/lib/schemas";
export function ProductionFactsView({ data }: { data: unknown }) {
const result = productionFactsSchema.safeParse(data);
if (!result.success) {
return (
<div className="rounded-2xl border border-stone-200 bg-white p-6 text-sm text-stone-700">
Could not display this insight (data format issue). Try another card or refresh later.
</div>
);
}
const parsed = result.data as ProductionFacts;
return (
<div className="space-y-5 rounded-2xl border border-stone-200 bg-white p-6">
{(parsed.budget || parsed.boxOffice) && (
<div className="grid gap-3 sm:grid-cols-2">
{parsed.budget ? <Stat label="Budget" value={parsed.budget} /> : null}
{parsed.boxOffice ? (
<Stat label="Box office" value={parsed.boxOffice} />
) : null}
</div>
)}
{parsed.filmingLocations?.length ? (
<div>
<p className="mb-2 text-sm text-stone-600">Filming locations</p>
<div className="flex flex-wrap gap-2">
{parsed.filmingLocations.map((location) => (
<span
key={location}
className="rounded-full border border-stone-200 bg-stone-100 px-3 py-1 text-sm text-stone-700"
>
{location}
</span>
))}
</div>
</div>
) : null}
<div className="space-y-3">
{parsed.facts.map((item, index) => (
<div
key={`${item.category}-${index}`}
className="rounded-xl border border-stone-200 bg-stone-100 p-4"
>
<p className="text-xs uppercase tracking-wide text-amber-700">
{item.category}
</p>
<p className="mt-2 text-sm leading-relaxed text-stone-700">
{item.fact}
</p>
</div>
))}
</div>
</div>
);
}
function Stat({ label, value }: { label: string; value: string }) {
return (
<div className="rounded-xl border border-stone-200 bg-stone-100 p-4">
<p className="text-xs uppercase tracking-wide text-stone-500">{label}</p>
<p className="mt-1 text-lg font-medium text-stone-950">{value}</p>
</div>
);
}
-56
View File
@@ -1,56 +0,0 @@
import {
sensitivityGuideSchema,
type SensitivityGuide,
} from "@/lib/schemas";
import { cn } from "@/lib/utils";
const severityColors = {
mild: "border-emerald-400/20 bg-emerald-400/5",
moderate: "border-amber-400/20 bg-amber-400/5",
strong: "border-red-400/20 bg-red-400/5",
};
export function SensitivityGuideView({ data }: { data: unknown }) {
const result = sensitivityGuideSchema.safeParse(data);
if (!result.success) {
return (
<div className="rounded-2xl border border-stone-200 bg-white p-6 text-sm text-stone-700">
Could not display this insight (data format issue). Try another card or refresh later.
</div>
);
}
const parsed = result.data as SensitivityGuide;
return (
<div className="space-y-5 rounded-2xl border border-stone-200 bg-white p-6">
<p className="text-stone-700">{parsed.summary}</p>
<div className="space-y-3">
{parsed.themes.map((theme, index) => (
<div
key={`${theme.theme}-${index}`}
className={cn(
"rounded-xl border p-4",
severityColors[theme.severity],
)}
>
<div className="mb-2 flex flex-wrap items-center gap-2">
<h4 className="font-medium text-stone-950">{theme.theme}</h4>
<span className="text-xs capitalize text-stone-600">
{theme.severity}
</span>
{theme.approximateTiming ? (
<span className="text-xs text-stone-500">
~{theme.approximateTiming}
</span>
) : null}
</div>
<p className="text-sm leading-relaxed text-stone-700">
{theme.description}
</p>
</div>
))}
</div>
</div>
);
}
-124
View File
@@ -1,124 +0,0 @@
import { skipGuideSchema, type SkipGuide } from "@/lib/schemas";
import { cn } from "@/lib/utils";
const recommendationStyles = {
recommended: "bg-red-100 text-red-700 border-red-200",
optional: "bg-amber-100 text-amber-700 border-amber-200",
do_not_skip: "bg-stone-200 text-stone-700 border-stone-300",
};
const recommendationLabels = {
recommended: "Recommended skip",
optional: "Optional skip",
do_not_skip: "Do not skip",
};
function parseTimestamp(value: string): number {
const hours = value.match(/(\d+)\s*h/i);
const minutes = value.match(/(\d+)\s*m/i);
return (hours ? Number(hours[1]) * 60 : 0) + (minutes ? Number(minutes[1]) : 0);
}
export function SkipGuideView({ data }: { data: unknown }) {
const result = skipGuideSchema.safeParse(data);
if (!result.success) {
return (
<div className="rounded-2xl border border-stone-200 bg-white p-6 text-sm text-stone-700">
Could not display this insight (data format issue). Try another card or refresh later.
</div>
);
}
const parsed = result.data as SkipGuide;
const maxMinutes = Math.max(
...parsed.segments.map((segment) => parseTimestamp(segment.end)),
120,
);
return (
<div className="space-y-5 rounded-2xl border border-stone-200 bg-white p-6">
<div className="grid gap-4 sm:grid-cols-3">
<Stat label="Original rating" value={parsed.originalRating} />
<Stat
label="Suggested age after skips"
value={`${parsed.suggestedAudienceAge}+`}
/>
<Stat
label="Skippable runtime"
value={`${parsed.totalSkippedMinutes} min`}
/>
</div>
<div>
<p className="mb-2 text-sm text-stone-600">Content timeline</p>
<div className="relative h-4 overflow-hidden rounded-full bg-emerald-400/20">
{parsed.segments.map((segment, index) => {
const start = parseTimestamp(segment.start);
const end = parseTimestamp(segment.end);
const left = (start / maxMinutes) * 100;
const width = Math.max(((end - start) / maxMinutes) * 100, 1.5);
return (
<div
key={`${segment.start}-${index}`}
className={cn(
"absolute top-0 h-full rounded-full",
segment.skipRecommendation === "do_not_skip"
? "bg-stone-300"
: "bg-red-500/80",
)}
style={{ left: `${left}%`, width: `${width}%` }}
title={`${segment.start} ${segment.end}`}
/>
);
})}
</div>
<div className="mt-2 flex justify-between text-xs text-stone-500">
<span>0:00</span>
<span>{Math.floor(maxMinutes / 60)}h {maxMinutes % 60}m</span>
</div>
</div>
<div className="space-y-3">
{parsed.segments.map((segment, index) => (
<div
key={`${segment.start}-${segment.end}-${index}`}
className="rounded-xl border border-stone-200 bg-stone-100 p-4"
>
<div className="mb-2 flex flex-wrap items-center gap-2">
<span className="font-medium text-stone-950">
{segment.start} {segment.end}
</span>
<span
className={cn(
"rounded-full border px-2 py-0.5 text-xs",
recommendationStyles[segment.skipRecommendation],
)}
>
{recommendationLabels[segment.skipRecommendation]}
</span>
<span className="text-xs capitalize text-stone-500">
Plot impact: {segment.plotImpact.replace("_", " ")}
</span>
</div>
<p className="text-sm text-stone-700">{segment.reason}</p>
<p className="mt-2 text-sm text-stone-600">
<span className="text-stone-500">Resume hint:</span>{" "}
{segment.resumeHint}
</p>
</div>
))}
</div>
<p className="text-xs text-stone-500">{parsed.disclaimer}</p>
</div>
);
}
function Stat({ label, value }: { label: string; value: string }) {
return (
<div className="rounded-xl border border-stone-200 bg-stone-100 p-4">
<p className="text-xs uppercase tracking-wide text-stone-500">{label}</p>
<p className="mt-1 text-lg font-medium text-stone-950">{value}</p>
</div>
);
}
+59
View File
@@ -0,0 +1,59 @@
Behavioral guidelines to reduce common LLM coding mistakes. Merge with project-specific instructions as needed.
**Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment.
## 1. Think Before Coding
**Don't assume. Don't hide confusion. Surface tradeoffs.**
Before implementing:
- State your assumptions explicitly. If uncertain, ask.
- If multiple interpretations exist, present them - don't pick silently.
- If a simpler approach exists, say so. Push back when warranted.
- If something is unclear, stop. Name what's confusing. Ask.
## 2. Simplicity First
**Minimum code that solves the problem. Nothing speculative.**
- No features beyond what was asked.
- No abstractions for single-use code.
- No "flexibility" or "configurability" that wasn't requested.
- No error handling for impossible scenarios.
- If you write 200 lines and it could be 50, rewrite it.
Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify.
## 3. Surgical Changes
**Touch only what you must. Clean up only your own mess.**
When editing existing code:
- Don't "improve" adjacent code, comments, or formatting.
- Don't refactor things that aren't broken.
- Match existing style, even if you'd do it differently.
- If you notice unrelated dead code, mention it - don't delete it.
When your changes create orphans:
- Remove imports/variables/functions that YOUR changes made unused.
- Don't remove pre-existing dead code unless asked.
The test: Every changed line should trace directly to the user's request.
## 4. Goal-Driven Execution
**Define success criteria. Loop until verified.**
Transform tasks into verifiable goals:
- "Add validation" → "Write tests for invalid inputs, then make them pass"
- "Fix the bug" → "Write a test that reproduces it, then make it pass"
- "Refactor X" → "Ensure tests pass before and after"
For multi-step tasks, state a brief plan:
```
1. [Step] → verify: [check]
2. [Step] → verify: [check]
3. [Step] → verify: [check]
```
Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification.
-56
View File
@@ -2,12 +2,8 @@ import type { CardType } from "./cards";
import { getCachedCard, setCachedCard } from "./cache"; import { getCachedCard, setCachedCard } from "./cache";
import { generateStructuredResponse } from "./llm"; import { generateStructuredResponse } from "./llm";
import { import {
historicalAccuracySchema,
internationalRatingsSchema, internationalRatingsSchema,
productionFactsSchema,
ratingExplainedSchema, ratingExplainedSchema,
sensitivityGuideSchema,
skipGuideSchema,
} from "./schemas"; } from "./schemas";
import { formatMovieContext, getMovieDetails } from "./tmdb"; import { formatMovieContext, getMovieDetails } from "./tmdb";
@@ -29,66 +25,14 @@ You MUST return ONLY valid JSON matching this exact structure (no extra keys, no
} }
Focus on specific scenes or content patterns that drove the rating. Be precise with the allowed category and intensity values.`, Focus on specific scenes or content patterns that drove the rating. Be precise with the allowed category and intensity values.`,
skip_guide: `Create a skip guide for families who want to watch this film with a younger audience.
You MUST return ONLY valid JSON matching this exact structure:
{
"originalRating": string,
"suggestedAudienceAge": number (integer 0-21),
"totalSkippedMinutes": number (integer),
"segments": array of {
"start": string (e.g. "0:05" or "12m"),
"end": string,
"reason": string,
"intensity": one of exactly ["mild", "moderate", "strong"],
"plotImpact": one of exactly ["none", "minor", "significant"],
"skipRecommendation": one of exactly ["recommended", "optional", "do_not_skip"],
"resumeHint": string
},
"disclaimer": string
}
Only include genuinely skippable segments. Mark plot-critical scenes as skipRecommendation "do_not_skip".
Timestamps should be approximate for the standard theatrical cut. Use only the exact enum strings listed.`,
sensitivity_guide: `Create a sensitivity guide grouping potentially upsetting content by theme.
You MUST return ONLY valid JSON:
{
"summary": string,
"themes": array of {
"theme": string,
"severity": one of exactly ["mild", "moderate", "strong"],
"description": string,
"approximateTiming": string (optional)
}
}
Cover violence, sexuality, substances, self-harm, abuse, animal harm, discrimination, and other difficult themes where relevant. Use only the exact "severity" values.`,
international_ratings: `Summarize how this film is rated across countries using the certification data provided. 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). 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.`, Include at least US, GB, ES, DE, FR when data exists. Explain notable differences.`,
production_facts: `Curate interesting behind-the-scenes production facts for cinephiles.
Return JSON with: facts (array of at least 5 {category, fact}), budget (optional string), boxOffice (optional string), filmingLocations (optional array of strings).
Prefer specific, verifiable-sounding details; note uncertainty in the fact text when needed.`,
historical_accuracy: `Evaluate historical accuracy for this biographical or historical film.
You MUST return ONLY valid JSON:
{
"accuracyScore": number (0-100),
"summary": string,
"accurateElements": string[],
"inventions": array of { "claim": string, "reality": string },
"confidence": one of exactly ["high", "medium", "low"]
}
If the film is not historical/biographical, still assess any real-world basis it claims. Use only the exact confidence value.`,
}; };
const SCHEMAS = { const SCHEMAS = {
rating_explained: ratingExplainedSchema, rating_explained: ratingExplainedSchema,
skip_guide: skipGuideSchema,
sensitivity_guide: sensitivityGuideSchema,
international_ratings: internationalRatingsSchema, international_ratings: internationalRatingsSchema,
production_facts: productionFactsSchema,
historical_accuracy: historicalAccuracySchema,
} as const; } as const;
export async function generateCard(movieId: number, cardType: CardType) { export async function generateCard(movieId: number, cardType: CardType) {
-32
View File
@@ -1,10 +1,6 @@
export const CARD_TYPES = [ export const CARD_TYPES = [
"rating_explained", "rating_explained",
"skip_guide",
"sensitivity_guide",
"international_ratings", "international_ratings",
"production_facts",
"historical_accuracy",
] as const; ] as const;
export type CardType = (typeof CARD_TYPES)[number]; export type CardType = (typeof CARD_TYPES)[number];
@@ -20,40 +16,12 @@ export const CARD_META: Record<CardType, CardMeta> = {
title: "Rating Explained", title: "Rating Explained",
subtitle: "Why this film has its age rating", subtitle: "Why this film has its age rating",
}, },
skip_guide: {
title: "Skip Guide",
subtitle: "Scenes you can skip for a younger audience",
badge: "Families",
},
sensitivity_guide: {
title: "Sensitivity Guide",
subtitle: "Content warnings by theme",
},
international_ratings: { international_ratings: {
title: "International Ratings", title: "International Ratings",
subtitle: "How ratings differ by country", subtitle: "How ratings differ by country",
}, },
production_facts: {
title: "Production Facts",
subtitle: "Behind-the-scenes facts",
},
historical_accuracy: {
title: "Historical Accuracy",
subtitle: "Fact vs fiction breakdown",
},
}; };
const HISTORICAL_GENRES = new Set([
"history",
"war",
"biography",
"documentary",
]);
export function shouldShowHistoricalAccuracy(genres: string[]): boolean {
return genres.some((genre) => HISTORICAL_GENRES.has(genre.toLowerCase()));
}
export function isCardType(value: string): value is CardType { export function isCardType(value: string): value is CardType {
return CARD_TYPES.includes(value as CardType); return CARD_TYPES.includes(value as CardType);
} }
-59
View File
@@ -26,36 +26,6 @@ export const ratingExplainedSchema = z.object({
borderlineNote: z.string().optional(), borderlineNote: z.string().optional(),
}); });
export const skipGuideSchema = z.object({
originalRating: z.string(),
suggestedAudienceAge: z.number().int().min(0).max(21),
totalSkippedMinutes: z.number().int().min(0),
segments: z.array(
z.object({
start: z.string(),
end: z.string(),
reason: z.string(),
intensity,
plotImpact: z.enum(["none", "minor", "significant"]),
skipRecommendation: z.enum(["recommended", "optional", "do_not_skip"]),
resumeHint: z.string(),
}),
),
disclaimer: z.string(),
});
export const sensitivityGuideSchema = z.object({
summary: z.string(),
themes: z.array(
z.object({
theme: z.string(),
severity: intensity,
description: z.string(),
approximateTiming: z.string().optional(),
}),
),
});
export const internationalRatingsSchema = z.object({ export const internationalRatingsSchema = z.object({
ratings: z.array( ratings: z.array(
z.object({ z.object({
@@ -70,34 +40,5 @@ export const internationalRatingsSchema = z.object({
mostLenientCountry: z.string().optional(), mostLenientCountry: z.string().optional(),
}); });
export const productionFactsSchema = z.object({
facts: z.array(
z.object({
category: z.string(),
fact: z.string(),
}),
),
budget: z.string().optional(),
boxOffice: z.string().optional(),
filmingLocations: z.array(z.string()).optional(),
});
export const historicalAccuracySchema = z.object({
accuracyScore: z.number().min(0).max(100),
summary: z.string(),
accurateElements: z.array(z.string()),
inventions: z.array(
z.object({
claim: z.string(),
reality: z.string(),
}),
),
confidence,
});
export type RatingExplained = z.infer<typeof ratingExplainedSchema>; export type RatingExplained = z.infer<typeof ratingExplainedSchema>;
export type SkipGuide = z.infer<typeof skipGuideSchema>;
export type SensitivityGuide = z.infer<typeof sensitivityGuideSchema>;
export type InternationalRatings = z.infer<typeof internationalRatingsSchema>; export type InternationalRatings = z.infer<typeof internationalRatingsSchema>;
export type ProductionFacts = z.infer<typeof productionFactsSchema>;
export type HistoricalAccuracy = z.infer<typeof historicalAccuracySchema>;
+1 -17
View File
@@ -36,10 +36,6 @@ export interface TmdbMovieDetails {
keywords?: { keywords?: {
keywords: Array<{ id: number; name: string }>; keywords: Array<{ id: number; name: string }>;
}; };
credits?: {
cast: Array<{ name: string; character: string }>;
crew: Array<{ name: string; job: string; department: string }>;
};
} }
function getApiKey(): string { function getApiKey(): string {
@@ -85,7 +81,7 @@ export async function searchMovies(query: string): Promise<TmdbSearchResult[]> {
export async function getMovieDetails(movieId: number): Promise<TmdbMovieDetails> { export async function getMovieDetails(movieId: number): Promise<TmdbMovieDetails> {
return tmdbFetch<TmdbMovieDetails>(`/movie/${movieId}`, { return tmdbFetch<TmdbMovieDetails>(`/movie/${movieId}`, {
append_to_response: "release_dates,credits,keywords", append_to_response: "release_dates,keywords",
}); });
} }
@@ -115,14 +111,6 @@ export function formatMovieContext(movie: TmdbMovieDetails): string {
const genres = movie.genres.map((g) => g.name).join(", "); const genres = movie.genres.map((g) => g.name).join(", ");
const keywords = movie.keywords?.keywords.map((k) => k.name).join(", ") ?? ""; const keywords = movie.keywords?.keywords.map((k) => k.name).join(", ") ?? "";
const certification = getUsCertification(movie); const certification = getUsCertification(movie);
const directors = movie.credits?.crew
.filter((c) => c.job === "Director")
.map((c) => c.name)
.join(", ");
const leadCast = movie.credits?.cast
.slice(0, 5)
.map((c) => `${c.name} as ${c.character}`)
.join("; ");
const releaseDates = movie.release_dates?.results const releaseDates = movie.release_dates?.results
.map((country) => { .map((country) => {
@@ -146,10 +134,6 @@ export function formatMovieContext(movie: TmdbMovieDetails): string {
`Overview: ${movie.overview}`, `Overview: ${movie.overview}`,
certification ? `US Certification: ${certification}` : null, certification ? `US Certification: ${certification}` : null,
keywords ? `Keywords: ${keywords}` : null, keywords ? `Keywords: ${keywords}` : null,
directors ? `Director(s): ${directors}` : null,
leadCast ? `Lead cast: ${leadCast}` : null,
movie.budget ? `Budget: $${movie.budget.toLocaleString("en-US")}` : null,
movie.revenue ? `Revenue: $${movie.revenue.toLocaleString("en-US")}` : null,
releaseDates ? `International certifications:\n${releaseDates}` : null, releaseDates ? `International certifications:\n${releaseDates}` : null,
] ]
.filter(Boolean) .filter(Boolean)
+2 -2
View File
@@ -2534,7 +2534,7 @@
"version": "20.19.42", "version": "20.19.42",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.42.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.42.tgz",
"integrity": "sha512-5L7SUaFC1RyDraj2yRhyBzHTobyXHmohD100CChNtyPyleoq37Mqab5Gn8XEKI04dfN/oqPdpHk38MgcQWHbZg==", "integrity": "sha512-5L7SUaFC1RyDraj2yRhyBzHTobyXHmohD100CChNtyPyleoq37Mqab5Gn8XEKI04dfN/oqPdpHk38MgcQWHbZg==",
"devOptional": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"undici-types": "~6.21.0" "undici-types": "~6.21.0"
@@ -8208,7 +8208,7 @@
"version": "6.21.0", "version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"devOptional": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/unrs-resolver": { "node_modules/unrs-resolver": {