const fs = require('fs');
const { replaceInFile } = require('replace-in-file');

const packageJson = JSON.parse(fs.readFileSync('package.json'));
const pluginFiles = [
    `./release/${packageJson.name}.php`
];

const isEnvatoRelease = process.argv.includes('--envato') || process.env.npm_lifecycle_event === 'release:envato';

// Configuration
const CLIENT_IDS = {
    original: '9e8529b7-9cda-4ff6-9884-952a86cbe566',
    envato: '85a75e23-c7d3-4fdb-a005-eb8a0901e59b'
};

// Validate that target files exist
const missingFiles = pluginFiles.filter(file => !fs.existsSync(file));
if (missingFiles.length > 0) {
    console.error(`❌ Missing files: ${missingFiles.join(', ')}`);
    process.exit(1);
}

async function updateAppseroClientId() {
    try {

        const options = {
            files: pluginFiles,
            from: /(\$client\s*=\s*new\s+Appsero\\Client\(\s*['"])([^'"]+)(['"])/g,
            to: (match, prefix, clientId, suffix) => {
                if (isEnvatoRelease && clientId === CLIENT_IDS.original) {
                    return `${prefix}${CLIENT_IDS.envato}${suffix}`;
                } else if (!isEnvatoRelease && clientId === CLIENT_IDS.envato) {
                    return `${prefix}${CLIENT_IDS.original}${suffix}`;
                }
                return match;
            },
        };

        const results = await replaceInFile(options);


    } catch (error) {
        console.error('❌ Error occurred during replacement:', error.message);
        process.exit(1);
    }
}

// Execute the replacement
updateAppseroClientId();
