from pathlib import Path

from django import template

from labb.config import load_config
from labb.django_settings import get_default_theme
from labb.shortcuts import get_labb_theme

register = template.Library()


@register.simple_tag
def lb_css_path():
    """
    Template tag to get the CSS output path from labb configuration.
    Usage: {% lb_css_path %}
    """
    labb_config = load_config(raise_not_found=False)

    try:
        output_path = Path(labb_config.output_file)
        # Return the path relative to static root (remove leading directories if needed)
        if str(output_path).startswith("static/"):
            return str(output_path)[7:]  # Remove 'static/' prefix
        else:
            return str(output_path)
    except Exception:
        return "css/output.css"


@register.simple_tag(takes_context=True)
def labb_theme(context):
    """
    Get the current theme from the request session and return as data-theme attribute.

    Usage:
        {% labb_theme as theme_attr %}
        <html {{ theme_attr }}>
    """
    request = context.get("request")
    if request:
        theme = get_labb_theme(request)
    else:
        # Get default theme from Django settings
        theme = get_default_theme()

    # Return empty string for __system__ theme (no data-theme attribute)
    if theme == "__system__" or not theme:
        return ""

    # Return data-theme attribute with theme value
    return f'data-theme="{theme}"'


@register.simple_tag(takes_context=True)
def labb_theme_val(context):
    """
    Get the current theme value from the request session.

    Usage:
        {% labb_theme_val as theme_value %}
        <span>{{ theme_value }}</span>
    """
    request = context.get("request")
    if request:
        return get_labb_theme(request)

    # Get default theme from Django settings
    return get_default_theme()
