import { notFound } from "next/navigation"
import { ChapterContent } from "@/components/chapter-content"
import { getSectionBySlug, getChapterBySectionSlug } from "@/lib/book-file-system"
import { specialSections, getSectionById } from "@/lib/book-data"

interface ReadPageProps {
  params: Promise<{ id: string }>
}

export const dynamic = "force-dynamic"
export const runtime = "nodejs"

export default async function ReadPage({ params }: ReadPageProps) {
  const { id } = await params

  if (id === "preface") {
    return <ChapterContent section={specialSections.preface as any} partTitle="序言" chapterTitle="" />
  }

  if (id === "epilogue") {
    return <ChapterContent section={specialSections.epilogue as any} partTitle="尾声" chapterTitle="" />
  }

  if (id.startsWith("appendix-")) {
    const appendixSection = specialSections.appendix.find((a) => a.id === id)
    if (appendixSection) {
      return <ChapterContent section={appendixSection as any} partTitle="附录" chapterTitle="" />
    }
  }

  try {
    // 先从文件系统获取
    const section = getSectionBySlug(id)
    if (section) {
      const context = getChapterBySectionSlug(id)
      if (context) {
        return <ChapterContent section={section} partTitle={context.part.title} chapterTitle={context.chapter.title} />
      }
    }

    // 再从book-data获取
    const bookSection = getSectionById(id)
    if (bookSection) {
      return <ChapterContent section={bookSection as any} partTitle="" chapterTitle="" />
    }

    notFound()
  } catch (error) {
    console.error("[Karuo] Error in ReadPage:", error)
    notFound()
  }
}
