const { program } = require('commander');
const fs = require('fs');
const path = require('path');
const glob = require('glob');
const cheerio = require('cheerio');

program
  .description('Process Blink test HTML files and output to specified directory')
  .requiredOption('-i, --input <path>', 'input HTML file path pattern')
  .requiredOption('-o, --output <dir>', 'output directory')
  .option('-t, --transform <type>', 'transform type', 'default')
  .action(async (options) => {
    let { input, output, transform } = options;

    // Convert relative input path to absolute path
    if (!path.isAbsolute(input)) {
      const absoluteBasePath = path.join(process.cwd(), path.dirname(input));
      const pattern = path.basename(input);
      input = path.join(absoluteBasePath, pattern);
    }

    // Convert output path to absolute path
    if (!path.isAbsolute(output)) {
      output = path.join(process.cwd(), output);
    }

    // Ensure output directory exists, clear it if it exists
    if (fs.existsSync(output)) {
      fs.rmSync(output, { recursive: true, force: true });
    }
    fs.mkdirSync(output, { recursive: true });

    // Use glob to find all matching files
    const files = glob.sync(input, {
      nodir: true,
      dot: true
    });
    console.log(`Found ${files.length} files matching pattern: ${input}`);
    // Get input base path (for calculating relative paths)
    const inputBasePath = input.split('*')[0];

    for (const file of files) {
      const absolutePath = path.isAbsolute(file) ? file : path.join(process.cwd(), file);
      const relativePath = path.relative(inputBasePath, absolutePath);
      const targetPath = path.join(output, relativePath);

      const html = fs.readFileSync(absolutePath, 'utf-8');
      const $ = cheerio.load(html, {
        lowerCaseTags: false,
        lowerCaseAttributeNames: false,
        decodeEntities: false,
        _useHtmlParser2: true,
        xmlMode: true
      });

      // 1. Delete scripts which contain base.js
      $('script, SCRIPT').each((i, elem) => {
        const src = $(elem).attr('src');
        if (src && src.includes('base.js')) {
          $(elem).remove();
        }
      });

      // 2. Delete all the tables
      $('table, TABLE').remove();

      const targetDir = path.dirname(targetPath);
      if (!fs.existsSync(targetDir)) {
        fs.mkdirSync(targetDir, { recursive: true });
      }

      const finalOutput = $.html()
        .replace(/\r\n/g, '\n')
        .replace(/\n+$/, '\n');

      fs.writeFileSync(targetPath, finalOutput);
      console.log(`Processed: ${relativePath} -> ${targetPath}`);
    }

    console.log(`\nProcessing complete. Files copied to: ${output}`);
  });

program.parse(process.argv);
