import { NextResponse } from "next/server";
import { getDb } from "@/lib/db";
import { readFileSync, existsSync } from "node:fs";
import { join } from "node:path";
import type { ModuleNode } from "@optage/sdk";
import { WIKI_DIR_NAME } from "@optage/sdk";

function hasNonEmptyMarkdown(filePath: string): boolean {
  if (!existsSync(filePath)) return false;
  try {
    return readFileSync(filePath, "utf-8").trim().length > 0;
  } catch {
    return false;
  }
}

function pruneToGeneratedDocs(
  node: ModuleNode,
  wikiRoot: string,
  overviewExists: boolean,
): ModuleNode | null {
  const prunedChildren = node.children
    .map((child) => pruneToGeneratedDocs(child, wikiRoot, overviewExists))
    .filter((child): child is ModuleNode => child !== null);

  if (node.level === "root") {
    return {
      ...node,
      docPath: overviewExists ? "overview.md" : undefined,
      children: prunedChildren,
    };
  }

  const hasDoc =
    typeof node.docPath === "string" &&
    node.docPath.length > 0 &&
    hasNonEmptyMarkdown(join(wikiRoot, node.docPath));

  if (!hasDoc && prunedChildren.length === 0) {
    return null;
  }

  return {
    ...node,
    docPath: hasDoc ? node.docPath : undefined,
    children: prunedChildren,
  };
}

export async function GET(
  _request: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const { id } = await params;
  const db = await getDb();
  const { rows } = await db.query(
    "SELECT source_path FROM repositories WHERE id = $1",
    [id],
  );
  if (rows.length === 0) {
    return NextResponse.json({ error: "Repository not found" }, { status: 404 });
  }

  const wikiRoot = join(rows[0].source_path, WIKI_DIR_NAME);
  const treePath = join(wikiRoot, "tree.json");
  const overviewPath = join(wikiRoot, "overview.md");
  if (!existsSync(treePath)) {
    return NextResponse.json({ error: "Wiki not generated yet" }, { status: 404 });
  }

  const tree = JSON.parse(readFileSync(treePath, "utf-8")) as ModuleNode;
  const prunedTree = pruneToGeneratedDocs(tree, wikiRoot, existsSync(overviewPath));
  if (!prunedTree || (prunedTree.children.length === 0 && !prunedTree.docPath)) {
    return NextResponse.json({ error: "Wiki generation in progress" }, { status: 404 });
  }

  return NextResponse.json(prunedTree);
}
