import { redirect, notFound } from 'next/navigation';
import Link from 'next/link';
import { ChevronLeft } from 'lucide-react';
import { getCurrentUser } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import GenerationDetail from '@/components/ai/GenerationDetail';

export const dynamic = 'force-dynamic';

/**
 * v1.1.0:4 — Detail view for a single AIGeneration row.
 *
 * Why: previously a generation that finished while you weren't watching
 * disappeared into a List that only showed metadata. To re-examine the
 * model's output you had to apply it (which committed a Program). This
 * page lets you see the parsed program tree first, then either:
 *   - Apply it (creates a Program — same flow as Generate's preview)
 *   - Re-generate from the same prompt
 *   - View the raw model response + the exact system/user prompts sent
 *
 * Status flows:
 *   pending   → progress + stream attach (so reloading the page during
 *               a long Ollama run picks up where it left off)
 *   completed → static program tree + Apply
 *   applied   → "View applied program" link
 *   failed    → error + raw response details
 */
export default async function GenerationDetailPage({
  params,
}: {
  params: { id: string };
}) {
  const user = await getCurrentUser();
  if (!user) redirect('/auth/login');

  const [row, exercises] = await Promise.all([
    prisma.aIGeneration.findFirst({
      where: { id: params.id, userId: user.id },
    }),
    prisma.exercise.findMany({
      where: { userId: user.id },
      select: { id: true, name: true, type: true },
      orderBy: [{ type: 'asc' }, { name: 'asc' }],
    }),
  ]);
  if (!row) notFound();

  return (
    <div className="min-h-screen bg-[#0A0A0A]">
      <div className="border-b border-zinc-800">
        <div className="max-w-3xl mx-auto px-4 py-4 sm:py-6 flex items-center gap-3">
          <Link
            href="/main/ai/history"
            className="text-zinc-400 hover:text-white"
            aria-label="Back to history"
          >
            <ChevronLeft className="w-5 h-5" />
          </Link>
          <h1 className="text-2xl sm:text-3xl font-bold text-white">
            AI · Generation
          </h1>
        </div>
      </div>
      <div className="max-w-3xl mx-auto px-4 py-6">
        <GenerationDetail
          row={{
            id: row.id,
            templateName: row.templateName,
            userInput: row.userInput,
            systemPrompt: row.systemPrompt,
            userPrompt: row.userPrompt,
            rawResponse: row.rawResponse,
            parsedProgram: row.parsedProgram,
            progressText: row.progressText,
            provider: row.provider,
            model: row.model,
            tokensIn: row.tokensIn,
            tokensOut: row.tokensOut,
            durationMs: row.durationMs,
            status: row.status,
            errorMessage: row.errorMessage,
            appliedProgramId: row.appliedProgramId,
            createdAt: row.createdAt.toISOString(),
          }}
          exercises={exercises}
        />
      </div>
    </div>
  );
}
