import os
import shutil
import glob
import re
import subprocess

# 1. Run generate_client_bundle.py
subprocess.run(["python", "scripts/generate_client_bundle.py"], check=True)

out_dir = "out"
assets_dir = os.path.join(out_dir, "assets")
css_dest_dir = os.path.join(assets_dir, "css")
js_dest_dir = os.path.join(assets_dir, "js")
os.makedirs(css_dest_dir, exist_ok=True)
os.makedirs(js_dest_dir, exist_ok=True)

# 2. Copy client bundle to out/assets/js/raulasencio.js
if os.path.exists("public/assets/js/raulasencio.js"):
    shutil.copy("public/assets/js/raulasencio.js", os.path.join(js_dest_dir, "raulasencio.js"))

# 3. Collect all CSS files and save a consolidated styles.css
css_files = glob.glob(os.path.join(out_dir, "_next", "static", "chunks", "*.css"))
combined_css = ""
for css_f in css_files:
    with open(css_f, "r", encoding="utf-8") as f:
        combined_css += f.read() + "\n"

# Add mobile smooth scroll and touch optimizations to consolidated styles
mobile_css_enhancements = """
/* Mobile Navigation & Smooth Scrolling Optimizations */
html {
  scroll-padding-top: 5rem;
  scroll-behavior: smooth;
  -webkit-tap-highlight-color: transparent;
}
section[id] {
  scroll-margin-top: 5rem;
}
#ra-product-modal-container, #ra-cart-drawer-container {
  -webkit-overflow-scrolling: touch;
}
"""
combined_css += mobile_css_enhancements

main_css_path = os.path.join(css_dest_dir, "styles.css")
with open(main_css_path, "w", encoding="utf-8") as f:
    f.write(combined_css)
print(f"Created {main_css_path} ({len(combined_css)} bytes)")

# Ensure public/images are synced to out/images
if os.path.exists("public/images"):
    out_images_dir = os.path.join(out_dir, "images")
    os.makedirs(out_images_dir, exist_ok=True)
    for img_file in os.listdir("public/images"):
        src_img = os.path.join("public/images", img_file)
        if os.path.isfile(src_img):
            shutil.copy(src_img, os.path.join(out_images_dir, img_file))
    print(f"Synced images to {out_images_dir}")

# 4. Patch all HTML files for relative scripts and subfolder compatibility
html_files = glob.glob(os.path.join(out_dir, "**", "*.html"), recursive=True)

for h_path in html_files:
    with open(h_path, "r", encoding="utf-8") as f:
        content = f.read()

    # Calculate relative prefix based on depth
    rel_depth = os.path.relpath(out_dir, os.path.dirname(h_path))
    prefix = "./" if rel_depth == "." else "../" * (len(rel_depth.split(os.sep)))

    # Inline script to auto-detect base path dynamically
    head_bootstrap_script = f"""
    <script>
      (function() {{
        var p = window.location.pathname;
        var base = p.replace(/\\/(checkout|admin|order-confirmed)(\\/.*)?$/, '/');
        if (!base.endsWith('/')) base += '/';
        window.TURBOPACK_CHUNK_BASE_PATH = base + '_next/';
      }})();
    </script>
    <link rel="stylesheet" href="{prefix}assets/css/styles.css" />
    """

    # Inject bootstrap script into <head>
    if "<head>" in content:
        content = content.replace("<head>", f"<head>{head_bootstrap_script}")
    elif "<head " in content:
        content = re.sub(r'(<head[^>]*>)', r'\1' + head_bootstrap_script, content, count=1)

    # Inject standalone client controller before </body>
    app_script_tag = f'<script src="{prefix}assets/js/raulasencio.js" defer></script>'
    if "raulasencio.js" not in content and "</body>" in content:
        content = content.replace("</body>", f"{app_script_tag}</body>")

    # Convert all absolute /_next/ to relative prefix
    content = content.replace('src="/_next/', f'src="{prefix}_next/')
    content = content.replace('href="/_next/', f'href="{prefix}_next/')
    content = content.replace('href="/favicon.ico', f'href="{prefix}favicon.ico')

    # Convert internal absolute links to relative
    content = re.sub(r'href="/admin/?"', f'href="{prefix}admin/"', content)
    content = re.sub(r'href="/checkout/?"', f'href="{prefix}checkout/"', content)
    content = re.sub(r'href="/order-confirmed/?"', f'href="{prefix}order-confirmed/"', content)
    content = re.sub(r'href="/(?!https?:|#|tel:|mailto:)"', f'href="{prefix}"', content)

    with open(h_path, "w", encoding="utf-8") as f:
        f.write(content)
    print(f"Patched {h_path} (prefix: {prefix}) with raulasencio.js")

# 5. Patch turbopack loader if needed so it respects dynamic base
turbopack_files = glob.glob(os.path.join(out_dir, "_next", "static", "chunks", "turbopack-*.js"))
for tb_file in turbopack_files:
    with open(tb_file, "r", encoding="utf-8") as f:
        tb_content = f.read()
    
    tb_content = tb_content.replace(
        'R="string"==typeof TURBOPACK_CHUNK_BASE_PATH?TURBOPACK_CHUNK_BASE_PATH:"/_next/"',
        'R="string"==typeof TURBOPACK_CHUNK_BASE_PATH?TURBOPACK_CHUNK_BASE_PATH:(typeof window!=="undefined"&&window.TURBOPACK_CHUNK_BASE_PATH?window.TURBOPACK_CHUNK_BASE_PATH:"./_next/")'
    )
    with open(tb_file, "w", encoding="utf-8") as f:
        f.write(tb_content)
    print(f"Patched {tb_file}")

# 6. Create robust .htaccess for Strato
htaccess_content = """# Strato Apache Configuration - Raúl Asencio Pastelerías
RewriteEngine On

# 1. Forzar HTTPS si está disponible
<IfModule mod_rewrite.c>
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

# 2. Servir archivos reales directamente (CSS, JS, imágenes, PHP)
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# 3. Soporte para rutas limpias (admin, checkout, order-confirmed)
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^/]+)/?$ $1.html [L]

RewriteCond %{REQUEST_FILENAME}/index.html -f
RewriteRule ^([^/]+)/?$ $1/index.html [L]

# 4. Compresión GZIP
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/css application/javascript application/json image/svg+xml
</IfModule>

# 5. Tipos MIME correctos
AddType text/css .css
AddType application/javascript .js
AddType image/svg+xml .svg
AddType image/webp .webp
AddType font/woff2 .woff2
"""

with open(os.path.join(out_dir, ".htaccess"), "w", encoding="utf-8") as f:
    f.write(htaccess_content)

print(".htaccess updated successfully.")
