import { NextResponse } from "next/server";
import { readPage, readOcr } from "@/lib/wiki";
import { readMatches } from "@/lib/entity-index";

export async function GET(_req: Request, ctx: { params: Promise<{ docId: string; page: string }> }) {
  const { docId, page } = await ctx.params;
  const stem = /^p\d{3}$/.test(page) ? page : `p${page.padStart(3, "0")}`;
  const md = await readPage(docId, stem);
  if (!md) return NextResponse.json({ error: "not_found" }, { status: 404 });

  const pageNum = parseInt(stem.replace("p", ""), 10);
  const ocr = await readOcr(docId, pageNum);
  const matches = await readMatches(docId, stem);

  return NextResponse.json({
    doc_id: docId,
    page_id: md.fm.page_id ?? `${docId}/${stem}`,
    page_number: pageNum,
    frontmatter: md.fm,
    body: md.body,
    ocr,
    matches,
  });
}
