import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { uploadToDropbox } from './dropboxService.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

/**
 * Upload the email logo to Dropbox and update all email templates
 * This provides a permanent, publicly accessible URL for email clients
 */
async function uploadEmailLogoAndUpdateTemplates() {
    try {
        console.log('📧 Uploading email logo to Dropbox...\n');

        // 1. Read the SVG logo file
        const logoPath = path.join(__dirname, '../assest/cssawwwards.svg');
        const logoContent = fs.readFileSync(logoPath, 'utf-8');

        // Convert SVG to base64 for upload
        const base64Logo = Buffer.from(logoContent).toString('base64');

        console.log('✓ Logo file read successfully');

        // 2. Upload to Dropbox
        const logoFilename = 'cssawwwards-logo.svg';
        const dropboxUrl = await uploadToDropbox(base64Logo, logoFilename, '/email-assets');

        console.log(`✓ Logo uploaded to Dropbox: ${dropboxUrl}\n`);

        // 3. Update all email templates
        const templatesDir = path.join(__dirname, '../templates');
        const templateFiles = [
            'aiWebsiteSubmissionEmail.html',
            'directorySubmissionEmail.html',
            'forgetEmail.html',
            'jobSubmissionEmail.html',
            'verificationEmail.html',
            'websiteSubmissionEmail.html',
            'welcomeEmail.html'
        ];

        let updatedCount = 0;

        templateFiles.forEach(filename => {
            const filePath = path.join(templatesDir, filename);

            if (fs.existsSync(filePath)) {
                let content = fs.readFileSync(filePath, 'utf-8');

                // Replace base64 data URI with Dropbox URL
                // Match the base64 pattern: data:image/svg+xml;base64,<long string>
                const base64Pattern = /data:image\/svg\+xml;base64,[A-Za-z0-9+/=]+/g;

                if (content.match(base64Pattern)) {
                    content = content.replace(base64Pattern, dropboxUrl);
                    fs.writeFileSync(filePath, content, 'utf-8');
                    updatedCount++;
                    console.log(`✓ Updated: ${filename}`);
                } else {
                    console.log(`⊘ Skipped: ${filename} (no base64 logo found)`);
                }
            } else {
                console.log(`✗ Not found: ${filename}`);
            }
        });

        console.log(`\n✅ Successfully updated ${updatedCount} email template(s)`);
        console.log(`📍 Logo URL: ${dropboxUrl}`);
        console.log('\n🎉 Email logos now use permanent Dropbox URL!');

        return dropboxUrl;

    } catch (error) {
        console.error('❌ Error uploading logo:', error.message);
        throw error;
    }
}

// Run the upload and update
console.log('Starting email logo upload process...\n');
uploadEmailLogoAndUpdateTemplates()
    .then(url => {
        console.log('\n✅ Process completed successfully!');
        process.exit(0);
    })
    .catch(error => {
        console.error('\n❌ Process failed:', error);
        process.exit(1);
    });

export { uploadEmailLogoAndUpdateTemplates };
