with open("public_html/supercerebro/api/proposals.php", "r") as f:
    content = f.read()

old_validation = """        // Validar completitud — asegurar que el HTML cierra correctamente
        if (stripos($html, '</html>') === false) {
            if (stripos($html, '</body>') !== false) {
                $html .= '</html>';
            } else {
                // HTML truncado — cerrar lo que haya
                $html .= '</div></section></main></body></html>';
            }
        }

        // Garantizar que el footer de DIMARK esté presente
        $dimark_credit = '<div style="text-align:center;padding:10px;background:rgba(0,0,0,0.25);font-size:11px;opacity:0.6">Propuesta creada con <a href="https://dimark.co" target="_blank" style="color:inherit;font-weight:700;text-decoration:none">Super Cerebro by DIMARK</a></div>';
        if (stripos($html, 'dimark.co') === false) {
            $html = str_ireplace('</body>', $dimark_credit . '</body>', $html);
        }"""

new_validation = """        // Validar completitud — asegurar que el HTML cierra correctamente
        if (stripos($html, '</html>') === false) {
            if (stripos($html, '</body>') !== false) {
                $html .= '</html>';
            } else {
                $html .= '</div></section></main></body></html>';
            }
        }

        // Garantizar lang attribute en <html>
        if (preg_match('/<html(?![^>]*lang=)/i', $html)) {
            $html = preg_replace('/<html/i', '<html lang="es"', $html, 1);
        }

        // Garantizar meta charset si falta
        if (stripos($html, 'charset') === false) {
            $html = str_ireplace('<head>', '<head><meta charset="UTF-8">', $html);
        }

        // Garantizar meta viewport si falta
        if (stripos($html, 'viewport') === false) {
            $html = str_ireplace('<head>', '<head><meta name="viewport" content="width=device-width, initial-scale=1">', $html);
        }

        // Garantizar preconnect Google Fonts si se usan Google Fonts
        if (stripos($html, 'fonts.googleapis.com') !== false && stripos($html, 'preconnect') === false) {
            $preconnects = '<link rel="preconnect" href="https://fonts.googleapis.com">' . "\n" .
                           '<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>';
            $html = str_ireplace('<link', $preconnects . "\n<link", $html, 1);
        }

        // Garantizar fetchpriority en hero image (primera imagen encontrada en hero/header)
        $html = preg_replace_callback('/<img([^>]+?)(loading=["\']lazy["\'])([^>]*?)>/i', function($m) {
            // Solo aplicar eager al primer img que esté en hero/banner section
            return '<img' . $m[1] . $m[2] . $m[3] . '>';
        }, $html, -1);
        // Hero: primera img con src que sea IMG1 o esté en un section hero/banner — marcar LCP
        $html = preg_replace('/<img([^>]*?)loading=["\']lazy["\']([^>]*?)(class=["\'][^"\']*?(hero|banner|jumbotron)[^"\']*?["\'])/i',
            '<img$1loading="eager" fetchpriority="high"$2$3', $html, 1);

        // Garantizar que el footer de DIMARK esté presente
        $dimark_credit = '<div style="text-align:center;padding:10px;background:rgba(0,0,0,0.25);font-size:11px;opacity:0.6">Propuesta creada con <a href="https://dimark.co" target="_blank" style="color:inherit;font-weight:700;text-decoration:none">Super Cerebro by DIMARK</a></div>';
        if (stripos($html, 'dimark.co') === false) {
            $html = str_ireplace('</body>', $dimark_credit . '</body>', $html);
        }

        // Log calidad de la propuesta generada
        $quality_checks = [
            'has_title'       => (int)(stripos($html, '<title') !== false),
            'has_meta_desc'   => (int)(stripos($html, 'name="description"') !== false),
            'has_og'          => (int)(stripos($html, 'og:title') !== false),
            'has_schema'      => (int)(stripos($html, 'application/ld+json') !== false),
            'has_preconnect'  => (int)(stripos($html, 'preconnect') !== false),
            'has_whatsapp'    => (int)(stripos($html, 'wa.me') !== false),
            'has_canonical'   => (int)(stripos($html, 'canonical') !== false),
            'html_length'     => strlen($html),
        ];
        file_put_contents($log_dir . 'quality.log',
            date('Y-m-d H:i:s') . " | id:{$id} style:{$style} | " . json_encode($quality_checks) . "\n",
            FILE_APPEND);"""

if old_validation in content:
    content = content.replace(old_validation, new_validation, 1)
    with open("public_html/supercerebro/api/proposals.php", "w") as f:
        f.write(content)
    print("OK patch: validation enhanced")
else:
    print("ERROR: validation anchor not found")
    # debug
    idx = content.find("// Validar completitud")
    print("anchor position:", idx)
