const fs = require('fs');
const path = require('path');

function fixCSSFile(filePath) {
    console.log(`Fixing CSS syntax in ${filePath}...`);
    
    let css = fs.readFileSync(filePath, 'utf8');
    let lines = css.split('\n');
    let fixedLines = [];
    let openBraces = 0;
    let inComment = false;
    let currentRule = '';
    
    for (let i = 0; i < lines.length; i++) {
        let line = lines[i];
        let trimmed = line.trim();
        
        // Track comments
        if (trimmed.includes('/*') && !trimmed.includes('*/')) {
            inComment = true;
        }
        if (trimmed.includes('*/')) {
            inComment = false;
        }
        
        // Skip empty lines inside rules but keep them between rules
        if (trimmed === '' && openBraces > 0 && !inComment) {
            continue;
        }
        
        // Count braces
        if (!inComment) {
            for (let char of line) {
                if (char === '{') {
                    openBraces++;
                    currentRule = lines[i-1] || '';
                } else if (char === '}') {
                    openBraces--;
                }
            }
        }
        
        // Check if we need to add a closing brace
        if (openBraces > 0 && i < lines.length - 1) {
            let nextLine = lines[i + 1].trim();
            // If next line starts a new rule and we have open braces, close them
            if (nextLine && 
                !nextLine.startsWith('/*') && 
                !nextLine.startsWith('*') && 
                !nextLine.startsWith('}') &&
                (nextLine.includes('{') || nextLine.match(/^[.#:][\w-]/))) {
                
                // Check if current line should have closing brace
                if (!trimmed.endsWith('}') && !trimmed.endsWith('{') && trimmed !== '') {
                    // Add missing closing braces
                    while (openBraces > 0) {
                        fixedLines.push(line);
                        line = '}';
                        openBraces--;
                    }
                }
            }
        }
        
        fixedLines.push(line);
    }
    
    // Close any remaining open braces at the end
    while (openBraces > 0) {
        fixedLines.push('}');
        openBraces--;
    }
    
    // Join and clean up extra blank lines
    let fixed = fixedLines.join('\n');
    fixed = fixed.replace(/\n{3,}/g, '\n\n');
    
    // Save the fixed file
    fs.writeFileSync(filePath, fixed);
    console.log(`Fixed ${filePath}`);
}

// Fix the dashboard CSS file
const cssPath = path.join(__dirname, 'assets/css/hvac-dashboard.css');
fixCSSFile(cssPath);

// Also fix the enhanced dashboard CSS
const enhancedPath = path.join(__dirname, 'assets/css/hvac-dashboard-enhanced.css');
if (fs.existsSync(enhancedPath)) {
    fixCSSFile(enhancedPath);
}

console.log('CSS syntax fixing complete!');