first commit
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
node_modules
|
||||
.next
|
||||
.git
|
||||
.env
|
||||
.env.local
|
||||
*.md
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
FROM node:22-alpine AS deps
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
FROM node:22-alpine AS builder
|
||||
WORKDIR /app
|
||||
COPY --from=deps /app/node_modules ./node_modules
|
||||
COPY . .
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
RUN npm run build
|
||||
|
||||
FROM node:22-alpine AS runner
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
|
||||
RUN addgroup --system --gid 1001 nodejs && \
|
||||
adduser --system --uid 1001 nextjs
|
||||
|
||||
COPY --from=builder /app/public ./public
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
||||
COPY --from=builder /app/package.json ./package.json
|
||||
COPY --from=builder /app/drizzle ./drizzle
|
||||
COPY --from=builder /app/scripts ./scripts
|
||||
COPY --from=builder /app/node_modules ./node_modules
|
||||
COPY docker-entrypoint.sh ./docker-entrypoint.sh
|
||||
|
||||
RUN chmod +x docker-entrypoint.sh
|
||||
|
||||
USER nextjs
|
||||
EXPOSE 3000
|
||||
ENV PORT=3000
|
||||
ENV HOSTNAME=0.0.0.0
|
||||
|
||||
ENTRYPOINT ["./docker-entrypoint.sh"]
|
||||
@@ -0,0 +1,30 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { isCardType } from "@/lib/cards";
|
||||
import { generateCard } from "@/lib/card-generator";
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ type: string }> },
|
||||
) {
|
||||
const { type } = await params;
|
||||
const movieId = Number(request.nextUrl.searchParams.get("movieId"));
|
||||
|
||||
if (!isCardType(type)) {
|
||||
return NextResponse.json({ error: "Unknown card type" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!Number.isFinite(movieId) || movieId <= 0) {
|
||||
return NextResponse.json({ error: "Invalid movie ID" }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await generateCard(movieId, type);
|
||||
return NextResponse.json(result);
|
||||
} catch (error) {
|
||||
console.error(`Card generation failed (${type}):`, error);
|
||||
return NextResponse.json(
|
||||
{ error: "Something went wrong. Try again." },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { checkDbConnection } from "@/lib/db";
|
||||
|
||||
export async function GET() {
|
||||
const dbHealthy = await checkDbConnection();
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: dbHealthy ? "ok" : "degraded",
|
||||
db: dbHealthy ? "connected" : "unavailable",
|
||||
},
|
||||
{ status: dbHealthy ? 200 : 503 },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { searchMovies } from "@/lib/tmdb";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const query = request.nextUrl.searchParams.get("q") ?? "";
|
||||
|
||||
if (!query.trim()) {
|
||||
return NextResponse.json({ results: [] });
|
||||
}
|
||||
|
||||
try {
|
||||
const results = await searchMovies(query);
|
||||
return NextResponse.json({ results });
|
||||
} catch (error) {
|
||||
console.error("Search failed:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Something went wrong. Try again." },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
+7
-10
@@ -1,8 +1,8 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #171717;
|
||||
--background: #020617;
|
||||
--foreground: #f8fafc;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
@@ -12,15 +12,12 @@
|
||||
--font-mono: var(--font-geist-mono);
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
font-family: var(--font-geist-sans), system-ui, sans-serif;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
+6
-4
@@ -13,8 +13,8 @@ const geistMono = Geist_Mono({
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Create Next App",
|
||||
description: "Generated by create next app",
|
||||
title: "Film Intel",
|
||||
description: "Advanced movie insight you won't find in one click",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
@@ -27,7 +27,9 @@ export default function RootLayout({
|
||||
lang="en"
|
||||
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
|
||||
>
|
||||
<body className="min-h-full flex flex-col">{children}</body>
|
||||
<body className="min-h-full flex flex-col bg-slate-950 text-slate-100">
|
||||
{children}
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
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-white/10 pt-6 text-center text-xs text-slate-500">
|
||||
AI-generated content for informational purposes. Verify timestamps on
|
||||
your copy.
|
||||
</footer>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+23
-59
@@ -1,65 +1,29 @@
|
||||
import Image from "next/image";
|
||||
import { SearchBar } from "@/components/SearchBar";
|
||||
|
||||
export default function Home() {
|
||||
export default function HomePage() {
|
||||
return (
|
||||
<div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black">
|
||||
<main className="flex flex-1 w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src="/next.svg"
|
||||
alt="Next.js logo"
|
||||
width={100}
|
||||
height={20}
|
||||
priority
|
||||
/>
|
||||
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
|
||||
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
|
||||
To get started, edit the page.tsx file.
|
||||
<main className="mx-auto flex min-h-screen w-full max-w-5xl flex-col items-center justify-center px-6 py-16">
|
||||
<div className="relative z-10 w-full max-w-2xl space-y-8 text-center">
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm font-medium uppercase tracking-[0.2em] text-amber-300/80">
|
||||
Film Intel
|
||||
</p>
|
||||
<h1 className="text-4xl font-semibold tracking-tight text-white md:text-5xl">
|
||||
Movie insight you won't find in one click
|
||||
</h1>
|
||||
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
|
||||
Looking for a starting point or more instructions? Head over to{" "}
|
||||
<a
|
||||
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
className="font-medium text-zinc-950 dark:text-zinc-50"
|
||||
>
|
||||
Templates
|
||||
</a>{" "}
|
||||
or the{" "}
|
||||
<a
|
||||
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
className="font-medium text-zinc-950 dark:text-zinc-50"
|
||||
>
|
||||
Learning
|
||||
</a>{" "}
|
||||
center.
|
||||
<p className="text-slate-400">
|
||||
Ratings explained, skip guides, sensitivity warnings, and deep
|
||||
production context for any film.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
|
||||
<a
|
||||
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
|
||||
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src="/vercel.svg"
|
||||
alt="Vercel logomark"
|
||||
width={16}
|
||||
height={16}
|
||||
/>
|
||||
Deploy Now
|
||||
</a>
|
||||
<a
|
||||
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
|
||||
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Documentation
|
||||
</a>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<SearchBar autoFocus />
|
||||
</div>
|
||||
|
||||
<footer className="mt-auto pt-16 text-center text-xs text-slate-500">
|
||||
AI-generated content for informational purposes. Verify timestamps on
|
||||
your copy.
|
||||
</footer>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
"use client";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { CardMeta } from "@/lib/cards";
|
||||
|
||||
interface InfoCardProps {
|
||||
meta: CardMeta;
|
||||
selected: boolean;
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
export function InfoCard({ meta, selected, onClick }: InfoCardProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
"group rounded-2xl border p-5 text-left transition",
|
||||
selected
|
||||
? "border-amber-400/40 bg-amber-400/10 shadow-lg shadow-amber-500/10"
|
||||
: "border-white/10 bg-white/[0.03] hover:border-white/20 hover:bg-white/[0.06]",
|
||||
)}
|
||||
>
|
||||
<div className="mb-2 flex items-center gap-2">
|
||||
<h3 className="font-medium text-white">{meta.title}</h3>
|
||||
{meta.badge ? (
|
||||
<span className="rounded-full bg-emerald-400/15 px-2 py-0.5 text-[11px] font-medium uppercase tracking-wide text-emerald-300">
|
||||
{meta.badge}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<p className="text-sm text-slate-400">{meta.subtitle}</p>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { ArrowLeft } from "lucide-react";
|
||||
import { getPosterUrl, getUsCertification, type TmdbMovieDetails } from "@/lib/tmdb";
|
||||
|
||||
export function MovieHeader({ movie }: { movie: TmdbMovieDetails }) {
|
||||
const poster = getPosterUrl(movie.poster_path, "w500");
|
||||
const year = movie.release_date?.slice(0, 4);
|
||||
const certification = getUsCertification(movie);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Link
|
||||
href="/"
|
||||
className="inline-flex w-fit items-center gap-2 text-sm text-slate-400 transition hover:text-amber-200"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
Back to search
|
||||
</Link>
|
||||
|
||||
<div className="flex flex-col gap-6 sm:flex-row sm:items-end">
|
||||
<div className="relative mx-auto h-56 w-36 shrink-0 overflow-hidden rounded-2xl border border-white/10 bg-slate-900 shadow-2xl sm:mx-0">
|
||||
{poster ? (
|
||||
<Image
|
||||
src={poster}
|
||||
alt={movie.title}
|
||||
fill
|
||||
className="object-cover"
|
||||
sizes="144px"
|
||||
priority
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full items-center justify-center text-sm text-slate-500">
|
||||
No poster
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 text-center sm:text-left">
|
||||
<div>
|
||||
<h1 className="text-3xl font-semibold tracking-tight text-white md:text-4xl">
|
||||
{movie.title}
|
||||
</h1>
|
||||
<p className="mt-1 text-slate-400">
|
||||
{[year, movie.runtime ? `${movie.runtime} min` : null]
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap justify-center gap-2 sm:justify-start">
|
||||
{certification ? (
|
||||
<span className="rounded-full border border-amber-400/30 bg-amber-400/10 px-3 py-1 text-sm font-medium text-amber-200">
|
||||
{certification}
|
||||
</span>
|
||||
) : null}
|
||||
{movie.genres.map((genre) => (
|
||||
<span
|
||||
key={genre.id}
|
||||
className="rounded-full border border-white/10 bg-white/5 px-3 py-1 text-sm text-slate-300"
|
||||
>
|
||||
{genre.name}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{movie.overview ? (
|
||||
<p className="max-w-3xl text-sm leading-relaxed text-slate-400 md:text-base">
|
||||
{movie.overview}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import {
|
||||
CARD_META,
|
||||
CARD_TYPES,
|
||||
shouldShowHistoricalAccuracy,
|
||||
type CardType,
|
||||
} from "@/lib/cards";
|
||||
import { CardContent } from "./cards/CardContent";
|
||||
import { InfoCard } from "./InfoCard";
|
||||
|
||||
export function MovieInsightPanel({
|
||||
movieId,
|
||||
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 (
|
||||
<div className="space-y-6">
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
|
||||
{visibleCards.map((type) => (
|
||||
<InfoCard
|
||||
key={type}
|
||||
meta={CARD_META[type]}
|
||||
selected={selected === type}
|
||||
onClick={() => setSelected(type)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<CardContent
|
||||
key={`${movieId}-${selected}`}
|
||||
movieId={movieId}
|
||||
cardType={selected}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
"use client";
|
||||
|
||||
import { Search } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { getPosterUrl } from "@/lib/tmdb";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface SearchResult {
|
||||
id: number;
|
||||
title: string;
|
||||
release_date: string;
|
||||
poster_path: string | null;
|
||||
overview: string;
|
||||
}
|
||||
|
||||
export function SearchBar({ autoFocus = false }: { autoFocus?: boolean }) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [query, setQuery] = useState("");
|
||||
const [results, setResults] = useState<SearchResult[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!query.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/search?q=${encodeURIComponent(query)}`,
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
const data = (await response.json()) as { results: SearchResult[] };
|
||||
setResults(data.results ?? []);
|
||||
setOpen(true);
|
||||
} catch (error) {
|
||||
if ((error as Error).name !== "AbortError") {
|
||||
setResults([]);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, 300);
|
||||
|
||||
return () => {
|
||||
clearTimeout(timeout);
|
||||
controller.abort();
|
||||
};
|
||||
}, [query]);
|
||||
|
||||
useEffect(() => {
|
||||
function handleClickOutside(event: MouseEvent) {
|
||||
if (!containerRef.current?.contains(event.target as Node)) {
|
||||
setOpen(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (open) {
|
||||
document.addEventListener("click", handleClickOutside);
|
||||
}
|
||||
|
||||
return () => document.removeEventListener("click", handleClickOutside);
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={cn("relative w-full max-w-2xl", open && "z-50")}
|
||||
>
|
||||
<div className="relative">
|
||||
<Search className="pointer-events-none absolute left-4 top-1/2 h-5 w-5 -translate-y-1/2 text-amber-200/50" />
|
||||
<input
|
||||
autoFocus={autoFocus}
|
||||
type="search"
|
||||
name="movie-search"
|
||||
autoComplete="off"
|
||||
autoCorrect="off"
|
||||
autoCapitalize="off"
|
||||
spellCheck={false}
|
||||
data-1p-ignore
|
||||
data-lpignore="true"
|
||||
data-bwignore
|
||||
data-form-type="other"
|
||||
value={query}
|
||||
onChange={(event) => {
|
||||
const value = event.target.value;
|
||||
setQuery(value);
|
||||
if (!value.trim()) {
|
||||
setResults([]);
|
||||
setOpen(false);
|
||||
}
|
||||
}}
|
||||
onFocus={() => query.trim() && setOpen(true)}
|
||||
placeholder="Search for a movie..."
|
||||
className="w-full rounded-2xl border border-white/10 bg-white/5 py-4 pl-12 pr-4 text-base text-white outline-none transition focus:border-amber-400/40 focus:bg-white/[0.07] focus:ring-2 focus:ring-amber-400/20"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{open && (
|
||||
<ul
|
||||
role="listbox"
|
||||
className="absolute z-50 mt-2 w-full overflow-hidden rounded-2xl border border-white/10 bg-slate-950 shadow-2xl"
|
||||
>
|
||||
{loading && (
|
||||
<li className="px-4 py-3 text-sm text-slate-400">Searching...</li>
|
||||
)}
|
||||
{!loading && results.length === 0 && (
|
||||
<li className="px-4 py-3 text-sm text-slate-400">No results found</li>
|
||||
)}
|
||||
{!loading &&
|
||||
results.map((result) => {
|
||||
const poster = getPosterUrl(result.poster_path, "w185");
|
||||
const year = result.release_date?.slice(0, 4);
|
||||
|
||||
return (
|
||||
<li key={result.id} role="option" aria-selected={false}>
|
||||
<Link
|
||||
href={`/movie/${result.id}`}
|
||||
prefetch
|
||||
onClick={() => setOpen(false)}
|
||||
className="flex items-center gap-3 border-b border-white/5 px-4 py-3 transition hover:bg-white/5 last:border-b-0"
|
||||
>
|
||||
<div className="relative h-14 w-10 shrink-0 overflow-hidden rounded-md bg-slate-800">
|
||||
{poster ? (
|
||||
<img
|
||||
src={poster}
|
||||
alt=""
|
||||
className="absolute inset-0 h-full w-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full items-center justify-center text-[10px] text-slate-500">
|
||||
N/A
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate font-medium text-white">
|
||||
{result.title}
|
||||
{year ? (
|
||||
<span className="ml-2 font-normal text-slate-400">
|
||||
({year})
|
||||
</span>
|
||||
) : null}
|
||||
</p>
|
||||
<p className="line-clamp-1 text-sm text-slate-400">
|
||||
{result.overview || "No overview available"}
|
||||
</p>
|
||||
</div>
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import type { CardType } from "@/lib/cards";
|
||||
import { HistoricalAccuracyView } from "./HistoricalAccuracy";
|
||||
import { InternationalRatingsView } from "./InternationalRatings";
|
||||
import { ProductionFactsView } from "./ProductionFacts";
|
||||
import { RatingExplainedView } from "./RatingExplained";
|
||||
import { SensitivityGuideView } from "./SensitivityGuide";
|
||||
import { SkipGuideView } from "./SkipGuide";
|
||||
|
||||
interface CardContentProps {
|
||||
movieId: number;
|
||||
cardType: CardType;
|
||||
}
|
||||
|
||||
export function CardContent({ movieId, cardType }: CardContentProps) {
|
||||
const [data, setData] = useState<unknown>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [retryToken, setRetryToken] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
let cancelled = false;
|
||||
|
||||
async function fetchCard() {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/cards/${cardType}?movieId=${movieId}`,
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
const payload = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(payload.error ?? "Something went wrong. Try again.");
|
||||
}
|
||||
|
||||
if (!cancelled) {
|
||||
setData(payload.data);
|
||||
setError(null);
|
||||
}
|
||||
} catch (err) {
|
||||
if ((err as Error).name === "AbortError" || cancelled) {
|
||||
return;
|
||||
}
|
||||
setError(
|
||||
err instanceof Error ? err.message : "Something went wrong. Try again.",
|
||||
);
|
||||
setData(null);
|
||||
} finally {
|
||||
if (!cancelled) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void fetchCard();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
controller.abort();
|
||||
};
|
||||
}, [cardType, movieId, retryToken]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="space-y-3 rounded-2xl border border-white/10 bg-white/[0.03] p-6">
|
||||
<div className="h-4 w-40 animate-pulse rounded bg-white/10" />
|
||||
<div className="h-4 w-full animate-pulse rounded bg-white/10" />
|
||||
<div className="h-4 w-5/6 animate-pulse rounded bg-white/10" />
|
||||
<p className="text-sm text-slate-400">Generating insight...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="rounded-2xl border border-red-400/20 bg-red-400/5 p-6">
|
||||
<p className="text-red-200">{error}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setLoading(true);
|
||||
setRetryToken((token) => token + 1);
|
||||
}}
|
||||
className="mt-4 rounded-lg border border-white/10 px-4 py-2 text-sm text-white transition hover:bg-white/5"
|
||||
>
|
||||
Try again
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
switch (cardType) {
|
||||
case "rating_explained":
|
||||
return <RatingExplainedView data={data} />;
|
||||
case "skip_guide":
|
||||
return <SkipGuideView data={data} />;
|
||||
case "sensitivity_guide":
|
||||
return <SensitivityGuideView data={data} />;
|
||||
case "international_ratings":
|
||||
return <InternationalRatingsView data={data} />;
|
||||
case "production_facts":
|
||||
return <ProductionFactsView data={data} />;
|
||||
case "historical_accuracy":
|
||||
return <HistoricalAccuracyView data={data} />;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
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-white/10 bg-white/[0.03] p-6 text-sm text-slate-400">
|
||||
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-white/10 bg-white/[0.03] p-6">
|
||||
<div className="flex items-end gap-4">
|
||||
<div>
|
||||
<p className="text-xs uppercase tracking-wide text-slate-500">
|
||||
Accuracy score
|
||||
</p>
|
||||
<p className="text-4xl font-semibold text-amber-200">
|
||||
{parsed.accuracyScore}
|
||||
<span className="text-lg text-slate-500">/100</span>
|
||||
</p>
|
||||
</div>
|
||||
<p className="pb-1 text-sm capitalize text-slate-400">
|
||||
Confidence: {parsed.confidence}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p className="text-slate-300">{parsed.summary}</p>
|
||||
|
||||
{parsed.accurateElements.length > 0 && (
|
||||
<div>
|
||||
<p className="mb-2 text-sm font-medium text-white">What holds up</p>
|
||||
<ul className="space-y-2">
|
||||
{parsed.accurateElements.map((item) => (
|
||||
<li
|
||||
key={item}
|
||||
className="rounded-lg border border-emerald-400/20 bg-emerald-400/5 px-3 py-2 text-sm text-slate-300"
|
||||
>
|
||||
{item}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{parsed.inventions.length > 0 && (
|
||||
<div>
|
||||
<p className="mb-2 text-sm font-medium text-white">
|
||||
Dramatizations & inventions
|
||||
</p>
|
||||
<div className="space-y-3">
|
||||
{parsed.inventions.map((item, index) => (
|
||||
<div
|
||||
key={`${item.claim}-${index}`}
|
||||
className="rounded-xl border border-white/10 bg-slate-950/40 p-4"
|
||||
>
|
||||
<p className="text-sm text-slate-300">
|
||||
<span className="text-slate-500">Film claim:</span> {item.claim}
|
||||
</p>
|
||||
<p className="mt-2 text-sm text-slate-300">
|
||||
<span className="text-slate-500">Reality:</span> {item.reality}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import {
|
||||
internationalRatingsSchema,
|
||||
type InternationalRatings,
|
||||
} from "@/lib/schemas";
|
||||
|
||||
export function InternationalRatingsView({ data }: { data: unknown }) {
|
||||
const result = internationalRatingsSchema.safeParse(data);
|
||||
if (!result.success) {
|
||||
return (
|
||||
<div className="rounded-2xl border border-white/10 bg-white/[0.03] p-6 text-sm text-slate-400">
|
||||
Could not display this insight (data format issue). Try another card or refresh later.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const parsed = result.data as InternationalRatings;
|
||||
|
||||
return (
|
||||
<div className="space-y-5 rounded-2xl border border-white/10 bg-white/[0.03] p-6">
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{parsed.ratings.map((rating) => (
|
||||
<div
|
||||
key={rating.countryCode}
|
||||
className="rounded-xl border border-white/10 bg-slate-950/40 p-4"
|
||||
>
|
||||
<p className="text-xs uppercase tracking-wide text-slate-500">
|
||||
{rating.country} ({rating.countryCode})
|
||||
</p>
|
||||
<p className="mt-1 text-xl font-semibold text-amber-200">
|
||||
{rating.rating}
|
||||
</p>
|
||||
{rating.descriptors?.length ? (
|
||||
<p className="mt-2 text-sm text-slate-400">
|
||||
{rating.descriptors.join(" · ")}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border border-white/10 bg-slate-950/40 p-4">
|
||||
<p className="text-sm leading-relaxed text-slate-300">
|
||||
{parsed.discrepancyNote}
|
||||
</p>
|
||||
{(parsed.strictestCountry || parsed.mostLenientCountry) && (
|
||||
<div className="mt-3 flex flex-wrap gap-4 text-sm text-slate-400">
|
||||
{parsed.strictestCountry ? (
|
||||
<span>Strictest: {parsed.strictestCountry}</span>
|
||||
) : null}
|
||||
{parsed.mostLenientCountry ? (
|
||||
<span>Most lenient: {parsed.mostLenientCountry}</span>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
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-white/10 bg-white/[0.03] p-6 text-sm text-slate-400">
|
||||
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-white/10 bg-white/[0.03] 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-slate-400">Filming locations</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{parsed.filmingLocations.map((location) => (
|
||||
<span
|
||||
key={location}
|
||||
className="rounded-full border border-white/10 bg-white/5 px-3 py-1 text-sm text-slate-300"
|
||||
>
|
||||
{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-white/10 bg-slate-950/40 p-4"
|
||||
>
|
||||
<p className="text-xs uppercase tracking-wide text-amber-200/80">
|
||||
{item.category}
|
||||
</p>
|
||||
<p className="mt-2 text-sm leading-relaxed text-slate-300">
|
||||
{item.fact}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Stat({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="rounded-xl border border-white/10 bg-slate-950/40 p-4">
|
||||
<p className="text-xs uppercase tracking-wide text-slate-500">{label}</p>
|
||||
<p className="mt-1 text-lg font-medium text-white">{value}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import {
|
||||
ratingExplainedSchema,
|
||||
type RatingExplained,
|
||||
} from "@/lib/schemas";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const intensityColors = {
|
||||
mild: "text-emerald-300 bg-emerald-400/10 border-emerald-400/20",
|
||||
moderate: "text-amber-300 bg-amber-400/10 border-amber-400/20",
|
||||
strong: "text-red-300 bg-red-400/10 border-red-400/20",
|
||||
};
|
||||
|
||||
export function RatingExplainedView({ data }: { data: unknown }) {
|
||||
const result = ratingExplainedSchema.safeParse(data);
|
||||
if (!result.success) {
|
||||
return (
|
||||
<div className="rounded-2xl border border-white/10 bg-white/[0.03] p-6 text-sm text-slate-400">
|
||||
Could not display this insight (data format issue). Try another card or refresh later.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const parsed = result.data as RatingExplained;
|
||||
|
||||
return (
|
||||
<div className="space-y-5 rounded-2xl border border-white/10 bg-white/[0.03] p-6">
|
||||
<div>
|
||||
<p className="text-sm uppercase tracking-wide text-slate-500">
|
||||
{parsed.region} rating
|
||||
</p>
|
||||
<h3 className="mt-1 text-2xl font-semibold text-amber-200">
|
||||
{parsed.officialRating}
|
||||
</h3>
|
||||
<p className="mt-3 text-slate-300">{parsed.summary}</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
{parsed.factors.map((factor, index) => (
|
||||
<div
|
||||
key={`${factor.category}-${index}`}
|
||||
className="rounded-xl border border-white/10 bg-slate-950/40 p-4"
|
||||
>
|
||||
<div className="mb-2 flex flex-wrap items-center gap-2">
|
||||
<span className="text-sm font-medium capitalize text-white">
|
||||
{factor.category}
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
"rounded-full border px-2 py-0.5 text-xs capitalize",
|
||||
intensityColors[factor.intensity],
|
||||
)}
|
||||
>
|
||||
{factor.intensity}
|
||||
</span>
|
||||
{factor.approximateTiming ? (
|
||||
<span className="text-xs text-slate-500">
|
||||
~{factor.approximateTiming}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<p className="text-sm leading-relaxed text-slate-300">
|
||||
{factor.description}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{parsed.borderlineNote ? (
|
||||
<p className="rounded-xl border border-amber-400/20 bg-amber-400/5 p-4 text-sm text-amber-100/90">
|
||||
{parsed.borderlineNote}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
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-white/10 bg-white/[0.03] p-6 text-sm text-slate-400">
|
||||
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-white/10 bg-white/[0.03] p-6">
|
||||
<p className="text-slate-300">{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-white">{theme.theme}</h4>
|
||||
<span className="text-xs capitalize text-slate-400">
|
||||
{theme.severity}
|
||||
</span>
|
||||
{theme.approximateTiming ? (
|
||||
<span className="text-xs text-slate-500">
|
||||
~{theme.approximateTiming}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<p className="text-sm leading-relaxed text-slate-300">
|
||||
{theme.description}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { skipGuideSchema, type SkipGuide } from "@/lib/schemas";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const recommendationStyles = {
|
||||
recommended: "bg-red-400/15 text-red-200 border-red-400/25",
|
||||
optional: "bg-amber-400/15 text-amber-200 border-amber-400/25",
|
||||
do_not_skip: "bg-slate-400/15 text-slate-200 border-slate-400/25",
|
||||
};
|
||||
|
||||
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-white/10 bg-white/[0.03] p-6 text-sm text-slate-400">
|
||||
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-white/10 bg-white/[0.03] 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-slate-400">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-slate-500/70"
|
||||
: "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-slate-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-white/10 bg-slate-950/40 p-4"
|
||||
>
|
||||
<div className="mb-2 flex flex-wrap items-center gap-2">
|
||||
<span className="font-medium text-white">
|
||||
{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-slate-500">
|
||||
Plot impact: {segment.plotImpact.replace("_", " ")}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-slate-300">{segment.reason}</p>
|
||||
<p className="mt-2 text-sm text-slate-400">
|
||||
<span className="text-slate-500">Resume hint:</span>{" "}
|
||||
{segment.resumeHint}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-slate-500">{parsed.disclaimer}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Stat({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="rounded-xl border border-white/10 bg-slate-950/40 p-4">
|
||||
<p className="text-xs uppercase tracking-wide text-slate-500">{label}</p>
|
||||
<p className="mt-1 text-lg font-medium text-white">{value}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
target: deps
|
||||
command: npm run dev
|
||||
working_dir: /app
|
||||
volumes:
|
||||
- .:/app
|
||||
- /app/node_modules
|
||||
ports:
|
||||
- "3000:3000"
|
||||
environment:
|
||||
DATABASE_URL: postgresql://film:film@db:5432/film
|
||||
TMDB_API_KEY: ${TMDB_API_KEY}
|
||||
LLM_API_KEY: ${LLM_API_KEY}
|
||||
LLM_BASE_URL: ${LLM_BASE_URL:-https://openrouter.ai/api/v1}
|
||||
LLM_MODEL: ${LLM_MODEL:-openai/gpt-4o-mini}
|
||||
LLM_HTTP_REFERER: ${LLM_HTTP_REFERER:-http://localhost:3000}
|
||||
LLM_APP_TITLE: ${LLM_APP_TITLE:-Film Intel}
|
||||
WATCHPACK_POLLING: "true"
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
@@ -0,0 +1,35 @@
|
||||
services:
|
||||
app:
|
||||
build: .
|
||||
ports:
|
||||
- "3000:3000"
|
||||
environment:
|
||||
DATABASE_URL: postgresql://film:film@db:5432/film
|
||||
TMDB_API_KEY: ${TMDB_API_KEY}
|
||||
LLM_API_KEY: ${LLM_API_KEY}
|
||||
LLM_BASE_URL: ${LLM_BASE_URL:-https://openrouter.ai/api/v1}
|
||||
LLM_MODEL: ${LLM_MODEL:-openai/gpt-4o-mini}
|
||||
LLM_HTTP_REFERER: ${LLM_HTTP_REFERER:-http://localhost:3000}
|
||||
LLM_APP_TITLE: ${LLM_APP_TITLE:-Film Intel}
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
|
||||
db:
|
||||
image: postgres:16-alpine
|
||||
environment:
|
||||
POSTGRES_USER: film
|
||||
POSTGRES_PASSWORD: film
|
||||
POSTGRES_DB: film
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U film -d film"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
if [ -n "$DATABASE_URL" ]; then
|
||||
echo "Running database migrations..."
|
||||
node scripts/migrate.mjs
|
||||
fi
|
||||
|
||||
exec node server.js
|
||||
@@ -0,0 +1,10 @@
|
||||
import { defineConfig } from "drizzle-kit";
|
||||
|
||||
export default defineConfig({
|
||||
schema: "./lib/db/schema.ts",
|
||||
out: "./drizzle/migrations",
|
||||
dialect: "postgresql",
|
||||
dbCredentials: {
|
||||
url: process.env.DATABASE_URL!,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
CREATE TABLE IF NOT EXISTS "card_cache" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"movie_id" integer NOT NULL,
|
||||
"card_type" varchar(50) NOT NULL,
|
||||
"payload" jsonb NOT NULL,
|
||||
"created_at" timestamptz DEFAULT now() NOT NULL
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "card_cache_movie_card_unique" ON "card_cache" ("movie_id", "card_type");
|
||||
@@ -0,0 +1,47 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import type { CardType } from "./cards";
|
||||
import { getDb } from "./db";
|
||||
import { cardCache } from "./db/schema";
|
||||
|
||||
export async function getCachedCard<T>(
|
||||
movieId: number,
|
||||
cardType: CardType,
|
||||
): Promise<T | null> {
|
||||
const db = getDb();
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(cardCache)
|
||||
.where(
|
||||
and(eq(cardCache.movieId, movieId), eq(cardCache.cardType, cardType)),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return rows[0].payload as T;
|
||||
}
|
||||
|
||||
export async function setCachedCard<T>(
|
||||
movieId: number,
|
||||
cardType: CardType,
|
||||
payload: T,
|
||||
): Promise<void> {
|
||||
const db = getDb();
|
||||
|
||||
await db
|
||||
.insert(cardCache)
|
||||
.values({
|
||||
movieId,
|
||||
cardType,
|
||||
payload,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: [cardCache.movieId, cardCache.cardType],
|
||||
set: {
|
||||
payload,
|
||||
createdAt: new Date(),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import type { CardType } from "./cards";
|
||||
import { getCachedCard, setCachedCard } from "./cache";
|
||||
import { generateStructuredResponse } from "./llm";
|
||||
import {
|
||||
historicalAccuracySchema,
|
||||
internationalRatingsSchema,
|
||||
productionFactsSchema,
|
||||
ratingExplainedSchema,
|
||||
sensitivityGuideSchema,
|
||||
skipGuideSchema,
|
||||
} 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.`,
|
||||
|
||||
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.
|
||||
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.`,
|
||||
|
||||
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 = {
|
||||
rating_explained: ratingExplainedSchema,
|
||||
skip_guide: skipGuideSchema,
|
||||
sensitivity_guide: sensitivityGuideSchema,
|
||||
international_ratings: internationalRatingsSchema,
|
||||
production_facts: productionFactsSchema,
|
||||
historical_accuracy: historicalAccuracySchema,
|
||||
} 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 };
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
export const CARD_TYPES = [
|
||||
"rating_explained",
|
||||
"skip_guide",
|
||||
"sensitivity_guide",
|
||||
"international_ratings",
|
||||
"production_facts",
|
||||
"historical_accuracy",
|
||||
] as const;
|
||||
|
||||
export type CardType = (typeof CARD_TYPES)[number];
|
||||
|
||||
export interface CardMeta {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
badge?: string;
|
||||
}
|
||||
|
||||
export const CARD_META: Record<CardType, CardMeta> = {
|
||||
rating_explained: {
|
||||
title: "Rating Explained",
|
||||
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: {
|
||||
title: "International Ratings",
|
||||
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 {
|
||||
return CARD_TYPES.includes(value as CardType);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { drizzle } from "drizzle-orm/postgres-js";
|
||||
import postgres from "postgres";
|
||||
import * as schema from "./schema";
|
||||
|
||||
const connectionString = process.env.DATABASE_URL;
|
||||
|
||||
let client: ReturnType<typeof postgres> | null = null;
|
||||
let db: ReturnType<typeof drizzle<typeof schema>> | null = null;
|
||||
|
||||
export function getDb() {
|
||||
if (!connectionString) {
|
||||
throw new Error("DATABASE_URL is not set");
|
||||
}
|
||||
|
||||
if (!client) {
|
||||
client = postgres(connectionString, { max: 10 });
|
||||
db = drizzle(client, { schema });
|
||||
}
|
||||
|
||||
return db!;
|
||||
}
|
||||
|
||||
export async function checkDbConnection(): Promise<boolean> {
|
||||
if (!connectionString) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const probe = postgres(connectionString, { max: 1 });
|
||||
await probe`SELECT 1`;
|
||||
await probe.end();
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import {
|
||||
integer,
|
||||
jsonb,
|
||||
pgTable,
|
||||
serial,
|
||||
timestamp,
|
||||
uniqueIndex,
|
||||
varchar,
|
||||
} from "drizzle-orm/pg-core";
|
||||
|
||||
export const cardCache = pgTable(
|
||||
"card_cache",
|
||||
{
|
||||
id: serial("id").primaryKey(),
|
||||
movieId: integer("movie_id").notNull(),
|
||||
cardType: varchar("card_type", { length: 50 }).notNull(),
|
||||
payload: jsonb("payload").notNull(),
|
||||
createdAt: timestamp("created_at", { withTimezone: true })
|
||||
.defaultNow()
|
||||
.notNull(),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("card_cache_movie_card_unique").on(
|
||||
table.movieId,
|
||||
table.cardType,
|
||||
),
|
||||
],
|
||||
);
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const SYSTEM_PROMPT = `You are a film research assistant for an international audience.
|
||||
You MUST respond in English with valid JSON only — no markdown fences, no commentary.
|
||||
Use a clear, neutral tone. If uncertain about a scene or timestamp, state uncertainty and set confidence to "low".
|
||||
Do not invent scenes, quotes, or timestamps. Base answers on the movie context provided.`;
|
||||
|
||||
export async function generateStructuredResponse<T extends z.ZodType>(
|
||||
schema: T,
|
||||
userPrompt: string,
|
||||
): Promise<z.infer<T>> {
|
||||
const apiKey = process.env.LLM_API_KEY;
|
||||
if (!apiKey) {
|
||||
throw new Error("LLM_API_KEY is not set");
|
||||
}
|
||||
|
||||
const baseUrl = process.env.LLM_BASE_URL ?? "https://api.openai.com/v1";
|
||||
const model = process.env.LLM_MODEL ?? "gpt-4o-mini";
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
|
||||
if (process.env.LLM_HTTP_REFERER) {
|
||||
headers["HTTP-Referer"] = process.env.LLM_HTTP_REFERER;
|
||||
}
|
||||
|
||||
if (process.env.LLM_APP_TITLE) {
|
||||
headers["X-Title"] = process.env.LLM_APP_TITLE;
|
||||
}
|
||||
|
||||
const response = await fetch(`${baseUrl}/chat/completions`, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
temperature: 0.2,
|
||||
response_format: { type: "json_object" },
|
||||
messages: [
|
||||
{ role: "system", content: SYSTEM_PROMPT },
|
||||
{ role: "user", content: userPrompt },
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`LLM request failed: ${response.status} ${errorText}`);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as {
|
||||
choices: Array<{ message: { content: string } }>;
|
||||
};
|
||||
|
||||
const content = data.choices[0]?.message?.content;
|
||||
if (!content) {
|
||||
throw new Error("LLM returned empty content");
|
||||
}
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(content);
|
||||
} catch {
|
||||
throw new Error("LLM returned invalid JSON");
|
||||
}
|
||||
|
||||
return schema.parse(parsed);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const intensity = z.enum(["mild", "moderate", "strong"]);
|
||||
const confidence = z.enum(["high", "medium", "low"]);
|
||||
|
||||
export const ratingExplainedSchema = z.object({
|
||||
officialRating: z.string(),
|
||||
region: z.string(),
|
||||
summary: z.string(),
|
||||
factors: z.array(
|
||||
z.object({
|
||||
category: z.enum([
|
||||
"violence",
|
||||
"language",
|
||||
"sexuality",
|
||||
"substances",
|
||||
"frightening",
|
||||
"other",
|
||||
]),
|
||||
intensity,
|
||||
description: z.string(),
|
||||
approximateTiming: z.string().optional(),
|
||||
confidence: confidence.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({
|
||||
ratings: z.array(
|
||||
z.object({
|
||||
country: z.string(),
|
||||
countryCode: z.string(),
|
||||
rating: z.string(),
|
||||
descriptors: z.array(z.string()).optional(),
|
||||
}),
|
||||
),
|
||||
discrepancyNote: z.string(),
|
||||
strictestCountry: 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 SkipGuide = z.infer<typeof skipGuideSchema>;
|
||||
export type SensitivityGuide = z.infer<typeof sensitivityGuideSchema>;
|
||||
export type InternationalRatings = z.infer<typeof internationalRatingsSchema>;
|
||||
export type ProductionFacts = z.infer<typeof productionFactsSchema>;
|
||||
export type HistoricalAccuracy = z.infer<typeof historicalAccuracySchema>;
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
const TMDB_BASE = "https://api.themoviedb.org/3";
|
||||
const LANGUAGE = "en-US";
|
||||
|
||||
export interface TmdbSearchResult {
|
||||
id: number;
|
||||
title: string;
|
||||
release_date: string;
|
||||
poster_path: string | null;
|
||||
overview: string;
|
||||
}
|
||||
|
||||
export interface TmdbMovieDetails {
|
||||
id: number;
|
||||
title: string;
|
||||
release_date: string;
|
||||
runtime: number | null;
|
||||
overview: string;
|
||||
poster_path: string | null;
|
||||
backdrop_path: string | null;
|
||||
genres: Array<{ id: number; name: string }>;
|
||||
budget: number;
|
||||
revenue: number;
|
||||
production_countries: Array<{ iso_3166_1: string; name: string }>;
|
||||
production_companies: Array<{ name: string }>;
|
||||
spoken_languages: Array<{ english_name: string }>;
|
||||
release_dates?: {
|
||||
results: Array<{
|
||||
iso_3166_1: string;
|
||||
release_dates: Array<{
|
||||
certification: string;
|
||||
type: number;
|
||||
note: string;
|
||||
}>;
|
||||
}>;
|
||||
};
|
||||
keywords?: {
|
||||
keywords: Array<{ id: number; name: string }>;
|
||||
};
|
||||
credits?: {
|
||||
cast: Array<{ name: string; character: string }>;
|
||||
crew: Array<{ name: string; job: string; department: string }>;
|
||||
};
|
||||
}
|
||||
|
||||
function getApiKey(): string {
|
||||
const key = process.env.TMDB_API_KEY;
|
||||
if (!key) {
|
||||
throw new Error("TMDB_API_KEY is not set");
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
async function tmdbFetch<T>(path: string, params: Record<string, string> = {}) {
|
||||
const url = new URL(`${TMDB_BASE}${path}`);
|
||||
url.searchParams.set("api_key", getApiKey());
|
||||
url.searchParams.set("language", LANGUAGE);
|
||||
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
url.searchParams.set(key, value);
|
||||
}
|
||||
|
||||
const response = await fetch(url.toString(), {
|
||||
next: { revalidate: 3600 },
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`TMDB request failed: ${response.status}`);
|
||||
}
|
||||
|
||||
return response.json() as Promise<T>;
|
||||
}
|
||||
|
||||
export async function searchMovies(query: string): Promise<TmdbSearchResult[]> {
|
||||
if (!query.trim()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const data = await tmdbFetch<{ results: TmdbSearchResult[] }>("/search/movie", {
|
||||
query: query.trim(),
|
||||
include_adult: "false",
|
||||
});
|
||||
|
||||
return data.results.slice(0, 8);
|
||||
}
|
||||
|
||||
export async function getMovieDetails(movieId: number): Promise<TmdbMovieDetails> {
|
||||
return tmdbFetch<TmdbMovieDetails>(`/movie/${movieId}`, {
|
||||
append_to_response: "release_dates,credits,keywords",
|
||||
});
|
||||
}
|
||||
|
||||
export function getPosterUrl(path: string | null, size: "w185" | "w500" | "original" = "w500") {
|
||||
if (!path) {
|
||||
return null;
|
||||
}
|
||||
return `https://image.tmdb.org/t/p/${size}${path}`;
|
||||
}
|
||||
|
||||
export function getUsCertification(movie: TmdbMovieDetails): string | null {
|
||||
const us = movie.release_dates?.results.find((r) => r.iso_3166_1 === "US");
|
||||
if (!us) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const theatrical = us.release_dates.find((r) => r.type === 3 && r.certification);
|
||||
if (theatrical?.certification) {
|
||||
return theatrical.certification;
|
||||
}
|
||||
|
||||
const any = us.release_dates.find((r) => r.certification);
|
||||
return any?.certification ?? null;
|
||||
}
|
||||
|
||||
export function formatMovieContext(movie: TmdbMovieDetails): string {
|
||||
const genres = movie.genres.map((g) => g.name).join(", ");
|
||||
const keywords = movie.keywords?.keywords.map((k) => k.name).join(", ") ?? "";
|
||||
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
|
||||
.map((country) => {
|
||||
const certs = country.release_dates
|
||||
.filter((r) => r.certification)
|
||||
.map((r) => r.certification);
|
||||
const unique = [...new Set(certs)];
|
||||
if (unique.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return `${country.iso_3166_1}: ${unique.join(", ")}`;
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
|
||||
return [
|
||||
`Title: ${movie.title}`,
|
||||
`Year: ${movie.release_date?.slice(0, 4) ?? "Unknown"}`,
|
||||
`Runtime: ${movie.runtime ?? "Unknown"} minutes`,
|
||||
`Genres: ${genres}`,
|
||||
`Overview: ${movie.overview}`,
|
||||
certification ? `US Certification: ${certification}` : 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,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
+11
-2
@@ -1,7 +1,16 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
/* config options here */
|
||||
output: "standalone",
|
||||
images: {
|
||||
remotePatterns: [
|
||||
{
|
||||
protocol: "https",
|
||||
hostname: "image.tmdb.org",
|
||||
pathname: "/t/p/**",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
export default nextConfig;
|
||||
Generated
+1779
-4
File diff suppressed because it is too large
Load Diff
+13
-2
@@ -6,21 +6,32 @@
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "eslint"
|
||||
"lint": "eslint",
|
||||
"db:migrate": "tsx scripts/migrate.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"drizzle-orm": "^0.45.2",
|
||||
"lucide-react": "^1.17.0",
|
||||
"next": "16.2.9",
|
||||
"postgres": "^3.4.9",
|
||||
"react": "19.2.4",
|
||||
"react-dom": "19.2.4"
|
||||
"react-dom": "19.2.4",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/node": "^20",
|
||||
"@types/pg": "^8.20.0",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"drizzle-kit": "^0.31.10",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "16.2.9",
|
||||
"tailwindcss": "^4",
|
||||
"tsx": "^4.22.4",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { readFileSync } from "fs";
|
||||
import { join } from "path";
|
||||
import postgres from "postgres";
|
||||
|
||||
const connectionString = process.env.DATABASE_URL;
|
||||
if (!connectionString) {
|
||||
console.error("DATABASE_URL is not set");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const sql = postgres(connectionString, { max: 1 });
|
||||
const migrationPath = join(process.cwd(), "drizzle/migrations/0000_init.sql");
|
||||
const migration = readFileSync(migrationPath, "utf-8");
|
||||
|
||||
try {
|
||||
await sql.unsafe(migration);
|
||||
await sql.end();
|
||||
console.log("Migrations applied successfully");
|
||||
} catch (error) {
|
||||
console.error("Migration failed:", error);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { readFileSync } from "fs";
|
||||
import { join } from "path";
|
||||
import postgres from "postgres";
|
||||
|
||||
async function migrate() {
|
||||
const connectionString = process.env.DATABASE_URL;
|
||||
if (!connectionString) {
|
||||
throw new Error("DATABASE_URL is not set");
|
||||
}
|
||||
|
||||
const sql = postgres(connectionString, { max: 1 });
|
||||
const migrationPath = join(process.cwd(), "drizzle/migrations/0000_init.sql");
|
||||
const migration = readFileSync(migrationPath, "utf-8");
|
||||
|
||||
await sql.unsafe(migration);
|
||||
await sql.end();
|
||||
|
||||
console.log("Migrations applied successfully");
|
||||
}
|
||||
|
||||
migrate().catch((error) => {
|
||||
console.error("Migration failed:", error);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in New Issue
Block a user