"""
assets.py

Purpose:
  Manage icon/asset URL helpers and the `/assets` route that serves a limited
  allowlist of root-level files for backward compatibility. Also injects icon
  URLs into templates via a context processor.

Exports:
  - register_assets(app): registers the /assets route and icon context processor
  - brand_icon_url(), tab icon helpers, and internal existence checks
"""

import os
from flask import url_for, send_from_directory
from .paths import ROOT_DIR, STATIC_PATH


def _static_exists(filename: str) -> bool:
    return os.path.exists(os.path.join(STATIC_PATH, filename))


def _root_exists(filename: str) -> bool:
    return os.path.exists(os.path.join(ROOT_DIR, filename))


def _url_for_static_or_asset(filename: str) -> str:
    if _static_exists(filename):
        return url_for('static', filename=filename)
    if _root_exists(filename):
        return url_for('assets', filename=filename)
    return ''


def brand_icon_url() -> str:
    for name in ['webicon180x180.png', 'logocebav2.webp', 'logoceba.webp']:
        url = _url_for_static_or_asset(name)
        if url:
            return url
    return _url_for_static_or_asset('jelen.png') or '/favicon.ico'


def tab_icon_camera() -> str:
    return _url_for_static_or_asset('cameraicon.webp') or brand_icon_url()


def tab_icon_gallery() -> str:
    return _url_for_static_or_asset('galleryicon.png') or brand_icon_url()


def tab_icon_map() -> str:
    return _url_for_static_or_asset('mapicon.png') or brand_icon_url()


def register_assets(app):
    @app.route('/assets/<path:filename>')
    def assets(filename: str):
        allowed = {
            'logoceba.webp', 'logocebav2.webp',
            'galleryicon.png', 'mapicon.png', 'cameraicon.webp',
            'webicon180x180.png', 'webicon32x32.png', 'webicon16x16.png',
            'camera_render.png', 'camera_render1.png'
        }
        if filename not in allowed:
            return '', 404
        return send_from_directory(ROOT_DIR, filename)

    @app.context_processor
    def inject_icons():
        return {
            'ICON_BRAND': brand_icon_url(),
            'ICON_CAM': tab_icon_camera(),
            'ICON_GALLERY': tab_icon_gallery(),
            'ICON_MAP': tab_icon_map(),
        }


