import { Index } from "../client_search.ts";
import { Doc, DocCollector } from "../collect.ts";

export const docCollector = new DocCollector(
  {
    dropContent: true,
    summaryOnly: true,
  },
);

export let docIndex: Index | undefined = undefined;

export async function prepareDocs() {
  const docPath = Deno.env.get("COLLECT_DOC_PATH");
  if (!docPath) {
    await docCollector.walkDir(".");
    docIndex = docCollector.makeIndex({
      watch: true,
    });
    return docIndex;
  }

  try {
    const doc_dump = await Deno.readTextFile(docPath);
    const docs = JSON.parse(doc_dump) as Doc[];
    docCollector.setDocs(docs);
  } catch (error) {
    if (error instanceof Deno.errors.NotFound) {
      await docCollector.walkDir(".");
      await Deno.writeTextFile(docPath, JSON.stringify(docCollector.getDocs()));
    } else {
      throw error;
    }
  }

  docIndex = docCollector.makeIndex({
    watch: true,
    onUpdate: async () => {
      await Deno.writeTextFile(docPath, JSON.stringify(docCollector.getDocs()));
    },
  });
  return docIndex;
}
