import os
from flask import url_for
from modules.core.config import BASE_DIR


def build_dated_url_for(app):
    def dated_url_for(endpoint, **values):
        if endpoint == "static":
            filename = values.get("filename")
            if filename:
                filepath = os.path.join(app.static_folder, filename)
                if not os.path.exists(filepath):
                    # Preserve mtime-based URLs for unmoved legacy runtime files.
                    filepath = os.path.join(BASE_DIR, "static", filename)
                if os.path.exists(filepath):
                    values["v"] = int(os.path.getmtime(filepath))
        return url_for(endpoint, **values)

    return dated_url_for


def register_asset_helpers(app):
    dated_url_for = build_dated_url_for(app)

    @app.context_processor
    def override_url_for():
        return {"url_for": dated_url_for}
