"""Routes: media"""
from flask import Response, abort, send_file

from nexora.core import app
from nexora.services.images import _clean_static_reference, _inside_static, static_file_abs


# 1x1 transparent PNG — returned when an image path is empty or missing
# so templates never produce a 404 on broken <img> tags.
_TRANSPARENT_PX = (
    b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01'
    b'\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89'
    b'\x00\x00\x00\nIDATx\x9cc\x00\x01\x00\x00\x05\x00\x01'
    b'\r\n\xb4\x00\x00\x00\x00IEND\xaeB`\x82'
)


@app.route("/media/<path:filename>")
def serve_media(filename):
    """Bypasses cPanel Apache static handlers to ensure images load via Flask.
    Returns a 1x1 transparent pixel for empty/missing paths so the page
    never shows a broken image or triggers a 404.
    Sets long cache headers so browsers don't re-download images."""
    if not filename or not filename.strip():
        return Response(_TRANSPARENT_PX, mimetype="image/png",
                        headers={"Cache-Control": "public, max-age=300"})
    try:
        safe_name = _clean_static_reference(filename)
        if not safe_name or safe_name.lower().startswith("images/registrations/"):
            return abort(404)
        target = static_file_abs(safe_name)
        if not target or not _inside_static(target):
            return abort(404)
        if target.is_file():
            resp = send_file(str(target))
            resp.headers["Cache-Control"] = "public, max-age=604800, immutable"
            resp.headers["Vary"] = "Accept-Encoding"
            return resp
    except Exception:
        pass
    return abort(404)
