#!/usr/bin/env python3
"""Minify CSS, JS, and HTML files in the deploy directory in-place."""

import re
import subprocess
import sys
from pathlib import Path

DEPLOY_DIR = Path("./deploy")


def minify_css(content):
    result = subprocess.run(
        ["cleancss", "--level", "1"],
        input=content,
        capture_output=True,
        text=True,
    )
    if result.returncode != 0:
        print(f"  cleancss error: {result.stderr}", file=sys.stderr)
        return content
    return result.stdout


def minify_js(content):
    result = subprocess.run(
        ["terser", "--compress", "--mangle"],
        input=content,
        capture_output=True,
        text=True,
    )
    if result.returncode != 0:
        print(f"  terser error: {result.stderr}", file=sys.stderr)
        return content
    return result.stdout


def minify_html(content):
    # Extract and preserve <pre> and <code> blocks before minifying
    preserved = {}

    def preserve(match):
        key = f"\x00PRESERVE{len(preserved)}\x00"
        preserved[key] = match.group(0)
        return key

    content = re.sub(r"<pre[\s\S]*?</pre>", preserve, content, flags=re.IGNORECASE)
    content = re.sub(r"<code[\s\S]*?</code>", preserve, content, flags=re.IGNORECASE)

    # Minify everything else
    content = re.sub(r"<!--.*?-->", "", content, flags=re.DOTALL)
    content = " ".join(line.strip() for line in content.splitlines())
    content = re.sub(r">\s+<", "><", content)
    content = re.sub(r"\s{2,}", " ", content)
    content = content.strip()

    # Restore preserved blocks untouched
    for key, value in preserved.items():
        content = content.replace(key, value)

    return content


HANDLERS = {
    ".css": minify_css,
    ".js": minify_js,
    ".html": minify_html,
}


def minify_files():
    for file in DEPLOY_DIR.rglob("*"):
        handler = HANDLERS.get(file.suffix)
        if not handler:
            continue
        content = file.read_text(encoding="utf-8")
        file.write_text(handler(content), encoding="utf-8")
        print(f"{file.suffix.upper().rjust(5)}: {file}")


if __name__ == "__main__":
    if not DEPLOY_DIR.exists():
        print(f"Error: deploy directory not found at {DEPLOY_DIR}", file=sys.stderr)
        sys.exit(1)

    print("Minifying assets...")
    minify_files()
    print("Done.")
