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

function processDir(dir) {
    const files = fs.readdirSync(dir, { withFileTypes: true });
    for (const file of files) {
        const fullPath = path.join(dir, file.name);
        if (file.isDirectory()) {
            processDir(fullPath);
        } else if (file.name.endsWith('.tsx') || file.name.endsWith('.ts')) {
            let content = fs.readFileSync(fullPath, 'utf8');
            let originalContent = content;

            // Pattern 1: <img src={`https://picsum.photos/seed/${p.seed}/W/H`} ...
            // We want to replace it with <img src={p.images?.[0] || `https://picsum.photos/seed/${p.seed}/W/H`}
            // But sometimes the variable is 'it', 'product', 'item'
            
            // Just replace the string literal interpolation:
            // `https://picsum.photos/seed/${varName.seed}/W/H`
            // with:
            // (varName.images?.[0] || `https://picsum.photos/seed/${varName.seed}/W/H`)
            
            const regex1 = /`https:\/\/picsum\.photos\/seed\/\$\{([a-zA-Z0-9_]+)\.seed\}\/(\d+)\/(\d+)`/g;
            content = content.replace(regex1, "($1.images?.[0] || `https://picsum.photos/seed/${$1.seed}/$2/$3`)");
            
            // product.$id.tsx special cases:
            // `https://picsum.photos/seed/${p.seed}/1200/630` -> (p?.images?.[0] || `https://picsum.photos/seed/${p?.seed}/1200/630`)
            
            // Let's just do a specific replacement for product.$id.tsx array map:
            // [0, 1, 2, 3].map((i) => `https://picsum.photos/seed/${product.seed}${i}/600/600`)
            // replaced with:
            // product.images?.length ? product.images : [0, 1, 2, 3].map((i) => `https://picsum.photos/seed/${product.seed}${i}/600/600`)
            if (file.name === 'product.$id.tsx') {
                content = content.replace(/\[0, 1, 2, 3\]\.map\(\(i\) => `https:\/\/picsum\.photos\/seed\/\$\{product\.seed\}\$\{i\}\/600\/600`\)/, "(product.images?.length ? product.images : [0, 1, 2, 3].map((i) => `https://picsum.photos/seed/${product.seed}${i}/600/600`))");
            }
            
            if (content !== originalContent) {
                fs.writeFileSync(fullPath, content, 'utf8');
                console.log('Updated', fullPath);
            }
        }
    }
}

processDir(path.join(__dirname, 'src'));
