from __future__ import annotations

import re
from typing import Any

try:
    import htmlmin  # type: ignore[import-not-found]
except ImportError:  # pragma: no cover - optional in local dev
    htmlmin = None

try:
    import rcssmin  # type: ignore[import-not-found]
except ImportError:  # pragma: no cover - optional in local dev
    rcssmin = None

try:
    import rjsmin  # type: ignore[import-not-found]
except ImportError:  # pragma: no cover - optional in local dev
    rjsmin = None


STYLE_BLOCK_RE = re.compile(r"(<style\b[^>]*>)(.*?)(</style>)", re.IGNORECASE | re.DOTALL)
SCRIPT_BLOCK_RE = re.compile(r"(<script\b[^>]*>)(.*?)(</script>)", re.IGNORECASE | re.DOTALL)
HTML_COMMENT_RE = re.compile(r"<!--(?!\[if).*?-->", re.DOTALL | re.IGNORECASE)


def _minify_css(css: str) -> str:
    if rcssmin is not None:
        return str(rcssmin.cssmin(css))
    css = re.sub(r"/\*.*?\*/", "", css, flags=re.DOTALL)
    css = re.sub(r"\s+", " ", css)
    css = re.sub(r"\s*([{}:;,>])\s*", r"\1", css)
    css = re.sub(r";}", "}", css)
    return css.strip()


def _is_js_like_script(open_tag: str) -> bool:
    lowered = open_tag.lower()
    if "src=" in lowered:
        return False
    if "type=" not in lowered:
        return True
    return any(token in lowered for token in ("javascript", "ecmascript", "module"))


def _minify_js(js: str) -> str:
    if rjsmin is not None:
        return str(rjsmin.jsmin(js))
    lines = [line.strip() for line in js.splitlines() if line.strip()]
    return "\n".join(lines).strip()


def _ensure_google_font_preconnects(html: str) -> str:
    lowered = html.lower()
    if "fonts.googleapis.com" not in lowered:
        return html
    if 'rel="preconnect" href="https://fonts.googleapis.com"' in lowered:
        return html
    preload = (
        '<link rel="preconnect" href="https://fonts.googleapis.com">'
        '<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>'
    )
    return html.replace("<head>", f"<head>{preload}", 1)


def optimize_artifact_html(html: str) -> tuple[str, dict[str, Any]]:
    original = html or ""
    optimized = _ensure_google_font_preconnects(original)

    def minify_style_block(match: re.Match[str]) -> str:
        return f"{match.group(1)}{_minify_css(match.group(2))}{match.group(3)}"

    def minify_script_block(match: re.Match[str]) -> str:
        open_tag = match.group(1)
        body = match.group(2)
        if not _is_js_like_script(open_tag):
            return match.group(0)
        return f"{open_tag}{_minify_js(body)}{match.group(3)}"

    optimized = STYLE_BLOCK_RE.sub(minify_style_block, optimized)
    optimized = SCRIPT_BLOCK_RE.sub(minify_script_block, optimized)
    optimized = HTML_COMMENT_RE.sub("", optimized)

    if htmlmin is not None:
        optimized = htmlmin.minify(
            optimized,
            remove_comments=True,
            remove_empty_space=True,
            reduce_boolean_attributes=False,
            remove_optional_attribute_quotes=False,
        )
    else:
        optimized = re.sub(r">\s+<", "><", optimized)
        optimized = re.sub(r"\n{3,}", "\n\n", optimized)

    original_bytes = len(original.encode("utf-8"))
    optimized_bytes = len(optimized.encode("utf-8"))
    if optimized_bytes >= original_bytes:
        report = {
            "original_bytes": original_bytes,
            "optimized_bytes": original_bytes,
            "saved_bytes": 0,
            "saved_percent": 0.0,
            "optimized": False,
        }
        return original, report

    saved_bytes = original_bytes - optimized_bytes
    report = {
        "original_bytes": original_bytes,
        "optimized_bytes": optimized_bytes,
        "saved_bytes": saved_bytes,
        "saved_percent": round((saved_bytes / original_bytes) * 100, 1) if original_bytes else 0.0,
        "optimized": True,
    }
    return optimized, report
