#!/usr/bin/env python3
"""
Hernoemt bestanden met '?...' in de naam naar schone namen,
en past alle HTML/CSS referenties aan.
"""

import os
import re
from pathlib import Path

BASE_DIR = Path("/var/www/correctvloerverwarming2")


def rename_files():
    """Zoek bestanden met '?' in de naam en hernoem ze."""
    mapping = {}  # old_name -> new_name (relatief aan BASE_DIR)

    for f in BASE_DIR.rglob("*"):
        if "?" in f.name and f.is_file():
            clean_name = f.name.split("?")[0]
            new_path = f.parent / clean_name

            # Conflict: als schone naam al bestaat, overschrijf (de versie is hetzelfde bestand)
            old_rel = str(f.relative_to(BASE_DIR))
            new_rel = str(new_path.relative_to(BASE_DIR))

            mapping[old_rel] = new_rel
            mapping[f.name] = clean_name  # ook op bestandsnaam niveau

            f.rename(new_path)
            print(f"  Hernoemd: {old_rel} -> {new_rel}")

    return mapping


def fix_references(mapping):
    """Vervang verwijzingen met %3F of ? in HTML en CSS bestanden."""
    html_updated = css_updated = 0

    for html_path in BASE_DIR.rglob("*.html"):
        try:
            content = html_path.read_text(encoding="utf-8", errors="ignore")
            original = content

            # Vervang URL-encoded: bestand.js%3Fver=X.Y -> bestand.js
            content = re.sub(r'(%3F|\?)ver=[^"\'&\s>]+', '', content, flags=re.IGNORECASE)
            # Vervang ook andere query params op assets
            content = re.sub(r'(\.js|\.css|\.woff2?|\.ttf|\.png|\.svg|\.jpg|\.jpeg|\.webp)(%3F|\?)[^"\'&\s>]+', r'\1', content, flags=re.IGNORECASE)

            if content != original:
                html_path.write_text(content, encoding="utf-8")
                html_updated += 1
        except Exception as e:
            print(f"  Fout HTML {html_path}: {e}")

    for css_path in BASE_DIR.rglob("*.css"):
        try:
            content = css_path.read_text(encoding="utf-8", errors="ignore")
            original = content

            content = re.sub(r'(\.js|\.css|\.woff2?|\.ttf|\.png|\.svg|\.jpg|\.jpeg|\.webp)(\?)[^"\')\s]+', r'\1', content, flags=re.IGNORECASE)

            if content != original:
                css_path.write_text(content, encoding="utf-8")
                css_updated += 1
        except Exception as e:
            print(f"  Fout CSS {css_path}: {e}")

    print(f"HTML bijgewerkt: {html_updated}")
    print(f"CSS bijgewerkt:  {css_updated}")


if __name__ == "__main__":
    print("=== Bestanden hernoemen (? uit bestandsnamen) ===")
    mapping = rename_files()
    print(f"\nTotaal hernoemd: {len(mapping)//2} bestanden\n")
    print("=== Referenties in HTML/CSS bijwerken ===")
    fix_references(mapping)
    print("\nKlaar!")
