import { readFileSync, existsSync, writeFileSync } from "fs";

import { fileURLToPath } from "url";
import path, { dirname } from "path";
import { CommandParser } from "./parser/command-parser";
import { ApiDocParser } from "./parser/apidoc/apidoc-parser";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const profanityPath = path.join(__dirname, "..", "..", "profanity");
const appPath = path.join(__dirname, "..", "content", "docs");

const commandsPath = path.join(profanityPath, "src", "command", "cmd_defs.c");
const apiDocsCPath = path.join(profanityPath, "apidocs", "c", "xml");

const apiDocsPythonPath = path.join(profanityPath, "apidocs", "python", "_build", "xml");

const writeCommandDocs = () => {
  if (!existsSync(commandsPath)) {
    console.error(`File not found: ${commandsPath}`);
    process.exit(1);
  }
  const fileContent = readFileSync(commandsPath, "utf-8");
  const commandParser = new CommandParser(fileContent);
  const output = commandParser.toMD();
  const outputPath = path.join(appPath, output.filename);
  writeFileSync(outputPath, output.buffer);
};

const writeApiDocs = () => {
  const apiCDocsEntryFilePath = path.join(apiDocsCPath, "index.xml");
  const apiDocsPythonEntryFilePath = path.join(apiDocsPythonPath, "index.xml");
  if (!existsSync(apiCDocsEntryFilePath)) {
    console.error(`File not found: ${apiDocsCPath}`);
    process.exit(1);
  }
  if (!existsSync(apiDocsPythonEntryFilePath)) {
    console.error(`File not found: ${apiDocsPythonPath}`);
    process.exit(1);
  }
  const cDocsEntryFileContent = readFileSync(apiCDocsEntryFilePath, "utf-8");
  const pythonDocsEntryFileContent = readFileSync(apiDocsPythonEntryFilePath, "utf-8");
  const parser = new ApiDocParser(
    {
      buffer: cDocsEntryFileContent,
      docPath: apiDocsCPath,
      repoPath: profanityPath
    },
    {
      buffer: pythonDocsEntryFileContent,
      docPath: apiDocsPythonPath,
      repoPath: profanityPath
    }
  );
  const output = parser.toMD();
  const cApiDocs = output.cApiDocs;
  for (const cApiDoc of cApiDocs) {
    const outputPath = path.join(appPath, "api-reference", "c", cApiDoc.filename);
    writeFileSync(outputPath, cApiDoc.buffer);
  }

  const pythonApiDocs = output.pythonApiDocs;
  for (const pythonApiDoc of pythonApiDocs) {
    const outputPath = path.join(appPath, "api-reference", "python", pythonApiDoc.filename);
    writeFileSync(outputPath, pythonApiDoc.buffer);
  }
};

writeCommandDocs();

writeApiDocs();
