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

const bundle = process.argv[2];
if (!bundle) {
  console.error("Please specify a bundle name (e.g., node sweep_step4.js dev)");
  process.exit(1);
}

const bundleRoot = process.env.IRIS_BUNDLE_ROOT;
if (!bundleRoot) {
  console.error("Error: Environment variable IRIS_BUNDLE_ROOT is not defined.");
  process.exit(1);
}

const bundleDir = path.join(bundleRoot, bundle);
const wikiDir = path.join(bundleDir, 'wiki');
const sweepFile = path.join(bundleDir, '.bundle/sweep.md');
const indexFile = path.join(wikiDir, 'index.md');

if (!fs.existsSync(sweepFile)) {
  console.error(`Sweep report not found: ${sweepFile}. Please run sweep_step2 first.`);
  process.exit(1);
}

// 1. Parse sweep.md to get list of files to delete
const sweepContent = fs.readFileSync(sweepFile, 'utf8');
const lines = sweepContent.split('\n');
const filesToDelete = [];

lines.forEach(line => {
  // Pattern to match markdown table row: | `id` | `wiki/path.md` | reason |
  const match = line.match(/\|\s*`[^`]+`\s*\|\s*`(wiki\/[^`]+)`/);
  if (match) {
    const wikiRelPath = match[1]; // e.g., "wiki/asp.net/aspnet.md"
    const fullPath = path.join(bundleDir, wikiRelPath);
    // Relative path under wiki/ for index.md search (e.g. "asp.net/aspnet.md")
    const indexRelPath = wikiRelPath.replace(/^wiki\//, '');
    filesToDelete.push({
      fullPath,
      indexRelPath,
      wikiRelPath
    });
  }
});

if (filesToDelete.length === 0) {
  console.log("No files to delete listed in the sweep report.");
  process.exit(0);
}

console.log(`Starting cleanup of ${filesToDelete.length} files...`);

// 2. Delete the files from disk
filesToDelete.forEach(file => {
  if (fs.existsSync(file.fullPath)) {
    fs.unlinkSync(file.fullPath);
    console.log(`Deleted: ${file.wikiRelPath}`);
    
    // Also try to delete empty parent directories under wiki/
    let parentDir = path.dirname(file.fullPath);
    while (parentDir !== wikiDir && parentDir.startsWith(wikiDir)) {
      if (fs.readdirSync(parentDir).length === 0) {
        fs.rmdirSync(parentDir);
        console.log(`Deleted empty directory: ${path.relative(bundleDir, parentDir)}`);
        parentDir = path.dirname(parentDir);
      } else {
        break;
      }
    }
  } else {
    console.log(`Warning: File not found on disk: ${file.wikiRelPath}`);
  }
});

// 3. Update index.md
if (fs.existsSync(indexFile)) {
  let indexContent = fs.readFileSync(indexFile, 'utf8');
  const indexLines = indexContent.split('\n');
  const updatedIndexLines = indexLines.filter(line => {
    // Check if line contains links to deleted files
    for (const file of filesToDelete) {
      // Escape for regex (e.g. "asp.net/aspnet.md" -> "asp\.net/aspnet\.md")
      const escapedPath = file.indexRelPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      const regex = new RegExp(`\\(${escapedPath}\\)`);
      if (regex.test(line)) {
        console.log(`Removed link from index.md: ${line.trim()}`);
        return false; // Exclude this line
      }
    }
    return true; // Keep this line
  });

  fs.writeFileSync(indexFile, updatedIndexLines.join('\n'), 'utf8');
  console.log("Updated index.md");
}

// 4. Delete sweep.md report
fs.unlinkSync(sweepFile);
console.log("Removed sweep report (.bundle/sweep.md)");
console.log("Sweep process completed successfully.");
