# Force HTTPS — Cloudflare-aware (avoids redirect loops)
# CF-Visitor tells origin what scheme the visitor used, even when
# Cloudflare itself fetches from origin over HTTP.
RewriteEngine On
RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# URL hygiene: /demo.html (legacy) -> /demo/ (canonical)
RewriteRule ^demo\.html$ /demo/ [R=301,L]

# Legacy /insights/ slug retirements -> current canonical articles
RewriteRule ^insights/ai-code-review/?$ /insights/ai-code-review-does-not-scale-linearly/ [R=301,L]
RewriteRule ^insights/cursor-rules-for-teams/?$ /insights/mneme-vs-cursor-rules/ [R=301,L]

# Branded 404 page
ErrorDocument 404 /404.html

# Brotli compression (falls back to gzip if unavailable)
<IfModule mod_brotli.c>
    AddOutputFilterByType BROTLI_COMPRESS text/html text/css text/javascript application/javascript text/xml application/xml image/svg+xml
</IfModule>
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/css text/javascript application/javascript text/xml application/xml image/svg+xml
</IfModule>

# Cache-Control headers — tell Cloudflare and browsers how long to cache
<IfModule mod_expires.c>
    ExpiresActive On

    # HTML — 1 hour (short so deploys propagate quickly after cache purge)
    ExpiresByType text/html                 "access plus 1 hour"

    # CSS / JS — 1 week
    ExpiresByType text/css                  "access plus 1 week"
    ExpiresByType application/javascript    "access plus 1 week"
    ExpiresByType text/javascript           "access plus 1 week"

    # Images — 1 month
    ExpiresByType image/png                 "access plus 1 month"
    ExpiresByType image/jpeg                "access plus 1 month"
    ExpiresByType image/webp                "access plus 1 month"
    ExpiresByType image/gif                 "access plus 1 month"
    ExpiresByType image/svg+xml             "access plus 1 month"
    ExpiresByType image/x-icon              "access plus 1 month"

    # Fonts
    ExpiresByType font/woff2                "access plus 1 month"
    ExpiresByType font/woff                 "access plus 1 month"
</IfModule>

<IfModule mod_headers.c>
    # Strip any server-injected Vary: User-Agent (added by mod_deflate/mod_brotli
    # on some cPanel stacks). Cloudflare refuses to cache responses with
    # Vary: User-Agent, so we unset it and pin exactly what we want.
    Header unset Vary
    Header set Vary "Accept-Encoding"

    # HTML
    <FilesMatch "\.(html|htm)$">
        Header set Cache-Control "public, max-age=3600"
    </FilesMatch>

    # CSS / JS
    <FilesMatch "\.(css|js)$">
        Header set Cache-Control "public, max-age=604800"
    </FilesMatch>

    # Images / fonts
    <FilesMatch "\.(png|jpg|jpeg|webp|gif|svg|ico|woff|woff2)$">
        Header set Cache-Control "public, max-age=2592000"
    </FilesMatch>
</IfModule>
