import { notFound } from "next/navigation";
import { prisma } from "../../../lib/db/client";
import { EditorShell } from "../../../components/editor/EditorShell";
import { aristotleFixture } from "../../../lib/fixtures/aristotle";
import { loadProject, ensureAristotleSeeded, ProjectNotFoundError } from "../../../lib/db/repo";

// Server component: loads the latest model + project metadata. Auto-seeds the
// Aristotle demo for the literal "aristotle" id; any other unknown id 404s.
export default async function EditorPage(props: { params: Promise<{ projectId: string }> }) {
  const { projectId } = await props.params;

  if (projectId === "aristotle") await ensureAristotleSeeded();

  let model, version;
  try {
    ({ model, version } = await loadProject(projectId));
  } catch (err) {
    if (err instanceof ProjectNotFoundError) notFound();
    throw err;
  }

  const projectRow = await prisma.project.findUnique({ where: { id: projectId } });
  if (!projectRow) notFound();

  // The narrative is fixture-derived for the Aristotle demo only. For any
  // other project we render a near-empty fixture so the prose surface
  // doesn't lie about the project's actual content. (Future polish: have
  // the seed-finalize step also produce an opening narrative.)
  const isAristotle = projectId === "aristotle";
  const fixtureForUi = isAristotle
    ? aristotleFixture
    : {
        ...aristotleFixture,
        project: {
          ...aristotleFixture.project,
          name: projectRow.name,
          scope: projectRow.scope,
          tagline: projectRow.tagline,
        },
        narrative: [
          { type: "h1" as const, text: projectRow.name },
          {
            type: "p" as const,
            children: [
              { t: "text" as const, v: projectRow.tagline },
            ],
          },
          { type: "h2" as const, text: "Notes" },
          {
            type: "p" as const,
            children: [
              { t: "text" as const, v: "Start writing — slash to insert chips that reference your blocks, requirements, and constraints." },
            ],
          },
        ],
        socratesThread: [], // dock loads from DB anyway
      };

  return (
    <EditorShell
      data={fixtureForUi}
      initialModel={model}
      initialVersion={version}
      projectId={projectId}
    />
  );
}
