const fs = require("fs");
const path = require("path");

// Function to extract H1 heading from markdown content
function extractH1(content) {
  const match = content.match(/^#\s+(.+)$/m);
  return match ? match[1] : null;
}

// Function to get REQ number from directory name
function getReqNumber(dirName) {
  const match = dirName.match(/REQ(\d+)/);
  return match ? parseInt(match[1]) : 0;
}

// Main function to update index
async function updateIndex() {
  try {
    const requirementsPath = __dirname;
    const dirs = fs
      .readdirSync(requirementsPath)
      .filter((item) => item.match(/^REQ\d+$/))
      .sort((a, b) => getReqNumber(a) - getReqNumber(b));

    let indexContent = "# Requirements Index\n\n";

    for (const dir of dirs) {
      const dirPath = path.join(requirementsPath, dir);
      const files = fs
        .readdirSync(dirPath)
        .filter((file) => file.endsWith(".md"));

      for (const file of files) {
        const filePath = path.join(dirPath, file);
        const content = fs.readFileSync(filePath, "utf8");
        const heading = extractH1(content);

        if (heading) {
          indexContent += `## ${dir}: ${heading}\n\n`;
          indexContent += `[View Requirement](./${dir}/${file})\n\n`;
        }
      }
    }

    // Write to index.md
    fs.writeFileSync(
      path.join(requirementsPath, "index.md"),
      indexContent,
      "utf8"
    );

    console.log("Index updated successfully!");
    console.log("project/001_documentation/Requirements/index.md");
  } catch (error) {
    console.error("Error updating index:", error);
  }
}

// Run the update
updateIndex();
