const fs = require('fs');
const path = require('path');
const toml = require('@iarna/toml');

function loadConfig() {
    try {
        const configPath = path.join(__dirname, '..', 'config.toml');
        const tomlString = fs.readFileSync(configPath, 'utf-8');
        const config = toml.parse(tomlString);
        console.log('Configuration loaded successfully.');
        return config;
    } catch (error) {
        console.error('Failed to load or parse config.toml:', error.message);
        process.exit(1);
    }
}

function generateRandomData() {
    const randomString = Math.random().toString(36).substring(2, 10);
    const username = `user${randomString}`;
    const email = `${username}@gmail.com`;
    const password = `pass${randomString}`;
    const age = Math.floor(Math.random() * 30 + 20).toString();
    const firstName = 'John';
    const lastName = 'Doe';
    const phone = '+31610488717';
    const company = 'Example Corp';
    return { username, email, password, age, firstName, lastName, phone, company };
}

function parseLocator(locatorStr) {
    locatorStr = locatorStr.trim();
    if (!locatorStr.startsWith('<')) {
        return locatorStr;
    }

    const getAttr = (attr) => {
        const match = locatorStr.match(new RegExp(`${attr}=["']([^"']+)["']`));
        return match ? match[1] : null;
    };

    const tagName = (locatorStr.match(/^<([a-zA-Z0-9]+)/) || [])[1] || '';
    const id = getAttr('id');
    if (id) {
        if (/^\d/.test(id)) {
            return `${tagName}[id='${id}']`;
        }
        return `${tagName}#${id}`;
    }

    const name = getAttr('name');
    if (name) return `${tagName}[name='${name}']`;

    const placeholder = getAttr('placeholder');
    if (placeholder) return `${tagName}[placeholder='${placeholder}']`;
    
    const type = getAttr('type');
    if (type) return `${tagName}[type='${type}']`;

    return tagName;
}

function loadSitesFromFile(filePath) {
    const fullPath = path.isAbsolute(filePath) ? filePath : path.join(__dirname, '..', filePath);
    const content = fs.readFileSync(fullPath, 'utf-8');
    const urls = content.split('\n').filter(line => line.trim() && !line.startsWith('#'));
    return urls.map((url, index) => ({
        name: `Site_${index + 1}`,
        url: url.trim(),
        category: 'Newsletter',
        needsPreSubmitAction: false
    }));
}

module.exports = {
    loadConfig,
    generateRandomData,
    parseLocator,
    loadSitesFromFile
};
