# common/utils/filters.py

import pytz
import markdown
from markupsafe import Markup
from datetime import datetime
from common.utils.nginx_utils import prefixed_url_for as puf
from common.utils.chat_utils import adjust_color_brightness, adjust_color_alpha, get_base_background_color
from flask import current_app, url_for


def to_local_time(utc_dt, timezone_str):
    """
    Converts a UTC datetime to a local datetime based on the provided timezone string.
    """
    if not utc_dt:
        return "N/A"
    local_tz = pytz.timezone(timezone_str)
    local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
    return local_dt.strftime('%Y-%m-%d %H:%M:%S %Z%z')


def time_difference(start_dt, end_dt):
    """
    Returns the time difference between two datetimes as a string.
    If end_dt is None, returns "Ongoing".
    """
    if not start_dt:
        return "N/A"
    if end_dt:
        delta = end_dt - start_dt
        # Customize the formatting as needed
        return str(delta)
    return "Ongoing"


def status_color(status_name):
    """Return Bootstrap color class for status"""
    colors = {
        'UPCOMING': 'secondary',
        'PENDING': 'warning',
        'ACTIVE': 'success',
        'COMPLETED': 'info',
        'INVOICED': 'primary',
        'CLOSED': 'dark'
    }
    return colors.get(status_name, 'secondary')


def render_markdown(text):
    """
    Renders markdown to HTML using Python's markdown library.
    Includes common extensions for better rendering.
    """
    if not text:
        return ""

    # Verwijder de triple backticks en markdown label
    text = clean_markdown(text)

    # Render de markdown met extensies
    return Markup(markdown.markdown(text, extensions=[
        'markdown.extensions.fenced_code',
        'markdown.extensions.codehilite',
        'markdown.extensions.tables',
        'markdown.extensions.toc'
    ]))


def clean_markdown(text):
    """
    Verwijdert triple backticks en markdown aanduiding uit de tekst
    """
    if not text:
        return ""

    text = text.strip()
    if text.startswith("```markdown"):
        text = text[len("```markdown"):].strip()
    elif text.startswith("```"):
        text = text[3:].strip()
    if text.endswith("```"):
        text = text[:-3].strip()

    return text


def prefixed_url_for(endpoint, **kwargs):
    return puf(endpoint, **kwargs)


def get_pagination_html(pagination, endpoint, **kwargs):
    """
    Generates HTML for pagination with the ability to include additional parameters
    """
    html = ['<nav aria-label="Page navigation"><ul class="pagination justify-content-center">']

    for page in pagination.iter_pages():
        if page:
            is_active = 'active' if page == pagination.page else ''
            url = url_for(endpoint, page=page, **kwargs)
            html.append(f'<li class="page-item {is_active}"><a class="page-link" href="{url}">{page}</a></li>')
        else:
            html.append('<li class="page-item disabled"><span class="page-link">...</span></li>')

    html.append('</ul></nav>')
    return Markup(''.join(html))


def asset_url(logical_path: str):
    """
    Resolve an asset logical path to a hashed URL using Parcel manifest when available.
    Return a URL that respects STATIC_URL (CDN) when configured; otherwise serve from /static/.
    Examples:
    - asset_url('dist/chat-client.js') -> 'https://cdn/.../dist/chat-client.abc123.js' (when STATIC_URL set)
    - asset_url('dist/chat-client.css') -> '/static/dist/chat-client.def456.css' (when STATIC_URL not set)
    """
    if not logical_path:
        return logical_path
    try:
        from common.utils.asset_manifest import resolve_asset
        # Resolve logical to possibly hashed path
        resolved = resolve_asset(logical_path) or logical_path

        # If manifest returns an absolute URL, return as-is
        if resolved.startswith('http://') or resolved.startswith('https://'):
            return resolved

        # Normalize: strip any leading '/static/' and leading '/'
        if resolved.startswith('/static/'):
            rel = resolved[len('/static/'):]
        else:
            rel = resolved.lstrip('/')

        # Build with STATIC_URL if configured
        static_base = (current_app.config.get('STATIC_URL') or '').rstrip('/')
        if static_base:
            return f"{static_base}/{rel}"
        # Fallback to app static
        return f"/static/{rel}"
    except Exception:
        # Conservative fallback also respecting STATIC_URL
        static_base = (current_app.config.get('STATIC_URL') or '').rstrip('/')
        rel = logical_path.lstrip('/')
        return f"{static_base}/{rel}" if static_base else f"/static/{rel}"


def register_filters(app):
    """
    Registers custom filters with the Flask app.
    """
    app.jinja_env.filters['to_local_time'] = to_local_time
    app.jinja_env.filters['time_difference'] = time_difference
    app.jinja_env.filters['status_color'] = status_color
    app.jinja_env.filters['prefixed_url_for'] = prefixed_url_for
    app.jinja_env.filters['markdown'] = render_markdown
    app.jinja_env.filters['clean_markdown'] = clean_markdown
    app.jinja_env.filters['adjust_color_brightness'] = adjust_color_brightness
    app.jinja_env.filters['adjust_color_alpha'] = adjust_color_alpha

    app.jinja_env.globals['prefixed_url_for'] = prefixed_url_for
    app.jinja_env.globals['get_pagination_html'] = get_pagination_html
    app.jinja_env.globals['get_base_background_color'] = get_base_background_color
    app.jinja_env.globals['asset_url'] = asset_url

