const fs = require('fs');
const postcss = require('postcss');
const tailwindcss = require('tailwindcss');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');

const inputPath = './public/css/tailwind.css';
const outputPath = './public/css/output.css';
const isProduction = process.env.NODE_ENV === 'production';

async function buildCSS() {
    console.log('[CSS Build] Reading input file...');
    const css = fs.readFileSync(inputPath, 'utf8');
    
    console.log(`[CSS Build] Processing with PostCSS and Tailwind... (${isProduction ? 'production' : 'development'} mode)`);
    
    const plugins = [
        tailwindcss(),
        autoprefixer()
    ];
    
    // Only minify in production
    if (isProduction) {
        plugins.push(cssnano({
            preset: ['default', {
                discardComments: {
                    removeAll: true,
                },
                normalizeWhitespace: true,
            }]
        }));
    }
    
    const result = await postcss(plugins).process(css, { 
        from: inputPath, 
        to: outputPath,
        map: !isProduction ? { inline: false } : false
    });
    
    console.log('[CSS Build] Writing output file...');
    fs.writeFileSync(outputPath, result.css);
    
    if (result.map && !isProduction) {
        fs.writeFileSync(outputPath + '.map', result.map.toString());
    }
    
    const sizeKB = (Buffer.byteLength(result.css, 'utf8') / 1024).toFixed(2);
    console.log('[CSS Build] ✓ CSS build complete!');
    console.log(`[CSS Build] Output: ${outputPath} (${sizeKB} KB)`);
}

buildCSS().catch(err => {
    console.error('[CSS Build] Error:', err);
    process.exit(1);
});

