import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import type {
  WikiManifest,
  WikiNavigationNode,
  WikiPage,
  WikiPageSummary,
} from "../../types/wiki-model";
import type { ModuleNode } from "../../repopilot/module-tree";
import { hasNonEmptyMarkdown, normalizeManifest, normalizePage } from "./normalizer";

export function makeLegacyPageId(node: ModuleNode): string {
  return node.level === "root" ? "overview" : `module:${node.path}`;
}

export function buildLegacyNavigation(node: ModuleNode, wikiRoot: string): WikiNavigationNode | null {
  const children = node.children
    .map((child) => buildLegacyNavigation(child, wikiRoot))
    .filter((child): child is WikiNavigationNode => child !== null);

  const hasDoc = node.level === "root"
    ? hasNonEmptyMarkdown(join(wikiRoot, "overview.md"))
    : !!node.docPath && hasNonEmptyMarkdown(join(wikiRoot, node.docPath));

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

  return {
    id: node.id,
    title: node.level === "root" ? "Overview" : node.name,
    pageId: makeLegacyPageId(node),
    pageType: node.level === "root" ? "overview" : "module",
    path: node.path || "overview",
    children,
  };
}

export function collectLegacySummaries(node: ModuleNode, summaries: WikiPageSummary[]) {
  summaries.push({
    id: makeLegacyPageId(node),
    title: node.level === "root" ? "Repository Overview" : node.path,
    pageType: node.level === "root" ? "overview" : "module",
    path: node.path || "overview",
    summary: node.level === "root" ? "Legacy wiki overview page" : `Legacy wiki page for ${node.path}`,
    sourceNodeIds: [],
    sourceEdgeKeys: [],
    primaryFiles: [],
    childPageIds: node.children.map((child) => makeLegacyPageId(child)),
    markdownPath: node.level === "root" ? "overview.md" : node.docPath,
  });

  for (const child of node.children) {
    collectLegacySummaries(child, summaries);
  }
}

export function buildLegacyManifest(sourcePath: string): WikiManifest | null {
  const wikiRoot = join(sourcePath, ".codewiki");
  const treePath = join(wikiRoot, "tree.json");

  if (!existsSync(treePath)) {
    return null;
  }

  const tree = JSON.parse(readFileSync(treePath, "utf-8")) as ModuleNode;
  const navigation = buildLegacyNavigation(tree, wikiRoot);
  if (!navigation) {
    return null;
  }

  const pages: WikiPageSummary[] = [];
  collectLegacySummaries(tree, pages);

  return normalizeManifest({
    version: 0,
    generatedAt: new Date(0).toISOString(),
    rootPageId: "overview",
    navigation,
    pages,
  });
}

export function buildLegacyPage(sourcePath: string, pageId: string): WikiPage | null {
  const wikiRoot = join(sourcePath, ".codewiki");
  const manifest = buildLegacyManifest(sourcePath);
  if (!manifest) {
    return null;
  }

  const summary = manifest.pages.find((page) => page.id === pageId);
  if (!summary?.markdownPath) {
    return null;
  }

  const markdownPath = join(wikiRoot, summary.markdownPath);
  if (!hasNonEmptyMarkdown(markdownPath)) {
    return null;
  }

  const markdown = readFileSync(markdownPath, "utf-8");

  return normalizePage({
    ...summary,
    generatedAt: manifest.generatedAt,
    sections: [
      {
        id: "legacy-markdown",
        title: "Narrative",
        type: "markdown",
        markdown,
      },
      {
        id: "legacy-navigation",
        title: "Related Pages",
        type: "navigation",
        relatedPageIds: summary.childPageIds,
      },
    ],
  }, manifest);
}
