"""Minimal public media-serving layer -- Storage Path Layer / Phase 2.

Why this exists: in external DATA_DIR mode, offer photos/videos and agent
avatars no longer physically live under Flask's static_folder (they live
under storage_paths.offer_dir()/agent_avatar_dir(), which resolve outside
the repo checkout). Flask's built-in static handler can therefore no
longer serve them. These two routes take over serving JUST those specific
URL patterns -- registered at the exact same literal paths the app has
always used (/static/images/<id>/<filename>, /static/images/agent_<id>.<ext>)
-- so every existing URL-generation call site (modules/investment/functions.py
::get_image_path(), InvestmentManager/routes/offer_catalog.py's
_resolve_agent_avatar_url()/_resolve_offer_main_image_url(), dashboard.py,
templates/components/agent_card.html, ...) keeps producing byte-identical
URLs with ZERO changes, in both legacy and external mode. Werkzeug's URL
matcher prefers these more specific rules over the generic
/static/<path:filename> catch-all, so nothing else under static/images/
(design assets: logos, hero images, flags, wojewodztwa/*) is affected --
those still fall through to Flask's normal static handler untouched.

Security (critical): the offer-image route's URL pattern structurally
allows a path segment containing "notes.md", "description_<id>.md" or
"docs/<file>" -- exactly the private files the audit flagged as
accidentally public today under legacy /static serving. This route does
NOT reproduce that: it validates the requested filename against a strict
allow-list (image_<id>_url_N.<ext> / video_<id>.<ext> only) before ever
touching the filesystem, and rejects everything else with 404. It never
uses send_from_directory on the whole offer directory or on DATA_DIR
itself -- only on a single, pre-validated filename within it.
"""
from __future__ import annotations

import re

from flask import Blueprint, abort, send_from_directory

from modules.core import offer_media as offer_media_contract, storage_paths

_OFFER_IMAGE_RE = offer_media_contract.OFFER_IMAGE_RE

media_bp = Blueprint("media", __name__)

_OFFER_VIDEO_RE = re.compile(r"^video_(?P<id>\d+)\.(mp4|webm)$", re.IGNORECASE)

# Exact filename only -- not a pattern. thumbnail.jpg (DATA_DIR cleanup
# task) is a per-offer, auto-generated 400x300 preview created by
# tools/resize_images.py from the resolved main offer image. There is no
# offer id embedded in the filename to cross-check against the URL's
# <int:offer_id>, unlike the two patterns above -- the offer_id path
# segment alone scopes it to the right directory via storage_paths.offer_dir().
_OFFER_THUMBNAIL_FILENAME = "thumbnail.jpg"


@media_bp.route("/static/images/<int:offer_id>/<path:filename>")
def offer_media(offer_id, filename):
    if filename == _OFFER_THUMBNAIL_FILENAME:
        directory = storage_paths.offer_dir(offer_id)
        return send_from_directory(directory, filename)

    match = _OFFER_IMAGE_RE.match(filename) or _OFFER_VIDEO_RE.match(filename)
    if not match or int(match.group("id")) != offer_id:
        # Deliberately includes: notes.md, description_<id>.md, docs/*,
        # disallowed extensions, and any offer_id/filename mismatch.
        abort(404)

    directory = storage_paths.offer_dir(offer_id)
    return send_from_directory(directory, filename)


@media_bp.route("/static/images/agent_<int:agent_id>.<any(jpg,jpeg,png,webp):ext>")
def agent_avatar(agent_id, ext):
    filename = f"agent_{agent_id}.{ext}"
    directory = storage_paths.agent_avatar_dir()
    return send_from_directory(directory, filename)
