const { Command } = require('commander');

function createCLI() {
    const program = new Command();

    program
        .name('newsletter-signup')
        .description('Newsletter Signup Automation Tool')
        .version('1.0.0')
        .option('-f, --file <path>', 'Load sites from text file (one URL per line)')
        .option('-k, --keep-open', 'Keep browser tabs open after processing for verification')
        .option('-l, --log', 'Save output to timestamped log file')
        .option('-d, --dry-run', 'Test mode - detect CAPTCHA but skip solving (no API calls)')
        .option('-h, --help', 'Show help message')
        .argument('[target]', 'Site name or URL to process (filters from config.toml sites)');

    program.on('option:help', () => {
        console.log(`
 Newsletter Signup Automation Tool

 Usage: node index.js [options] [site-name-or-url]

 Options:
   -f, --file=<path>      Load sites from text file (one URL per line)
   -k, --keep-open        Keep browser tabs open after processing for verification
   -l, --log              Save output to timestamped log file
   -d, --dry-run          Test mode - detect CAPTCHA but skip solving (no API calls)
   -h, --help             Show this help message

 Examples:
   node index.js                                    Process all sites from config.toml
   node index.js --file=sites.txt                   Process sites from file
   node index.js "Dutch News"                       Process specific site
   node index.js --file=sites.txt --keep-open       Keep tabs open for verification
   node index.js --log                              Save output to log file
   node index.js --dry-run                          Test without calling 2Captcha API

 Text file format (sites.txt):
   # Lines starting with # are comments
   https://example.com/newsletter
   https://another-site.com/signup

 Configuration:
   Edit config.toml to set credentials and default sites
 `);
        process.exit(0);
    });

    return program;
}

function parseCLI(args = process.argv.slice(2)) {
    const program = createCLI();
    
    const fullArgs = ['node', 'index.js', ...args];
    program.parse(fullArgs);
    
    const opts = program.opts();
    
    return {
        target: program.args[0] || null,
        file: opts.file || null,
        keepOpen: opts.keepOpen || false,
        log: opts.log || false,
        dryRun: opts.dryRun || false,
        help: opts.help || false
    };
}

module.exports = {
    createCLI,
    parseCLI
};
