import json
import re

"""
Utility functions for chat customization.
"""
from flask import current_app


def get_default_chat_customisation(tenant_customisation=None):
    """
    Get chat customization options with default values for missing options.

    Args:
        tenant_customisation (dict or str, optional): The tenant's customization options.
            Defaults to None. Can be a dict or a JSON string.

    Returns:
        dict: A dictionary containing all customization options with default values
            for any missing options.
    """
    # Default customization options
    default_customisation = {
        'sidebar_markdown': '',
        'sidebar_color': '#f8f9fa',
        'sidebar_background': '#2c3e50',
        'markdown_background_color': 'transparent',
        'markdown_text_color': '#ffffff',
        'gradient_start_color': '#f5f7fa',
        'gradient_end_color': '#c3cfe2',
        'progress_tracker_insights': 'No Information',
        'form_title_display': 'Full Title',
        'active_background_color': '#ffffff',
        'history_background': 10,
        'ai_message_background': '#ffffff',
        'ai_message_text_color': '#212529',
        'human_message_background': '#212529',
        'human_message_text_color': '#ffffff',

    }

    # If no tenant customization is provided, return the defaults
    if tenant_customisation is None:
        return default_customisation

    # Start with the default customization
    customisation = default_customisation.copy()

    # Convert JSON string to dict if needed
    if isinstance(tenant_customisation, str):
        try:
            tenant_customisation = json.loads(tenant_customisation)
        except json.JSONDecodeError as e:
            current_app.logger.error(f"Error parsing JSON customisation: {e}")
            return default_customisation

    # Update with tenant customization
    if tenant_customisation:
        for key, value in tenant_customisation.items():
            if key in customisation:
                customisation[key] = value

    return customisation


def hex_to_rgb(hex_color):
    """
    Convert hex color to RGB tuple.
    
    Args:
        hex_color (str): Hex color string (e.g., '#ffffff' or 'ffffff')
    
    Returns:
        tuple: RGB values as (r, g, b)
    """
    # Remove # if present
    hex_color = hex_color.lstrip('#')
    
    # Handle 3-character hex codes
    if len(hex_color) == 3:
        hex_color = ''.join([c*2 for c in hex_color])
    
    # Convert to RGB
    try:
        return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
    except ValueError:
        # Return white as fallback
        return (255, 255, 255)


def adjust_color_alpha(percentage):
    """
    Convert percentage to RGBA color with appropriate base color and alpha.
    
    Args:
        percentage (int): Percentage (-50 to 50)
                         Positive = white base (lighten)
                         Negative = black base (darken)
                         Zero = transparent
    
    Returns:
        str: RGBA color string for CSS
    """
    if percentage == 0:
        return 'rgba(255, 255, 255, 0)'  # Volledig transparant
    
    # Bepaal basis kleur
    if percentage > 0:
        # Positief = wit voor verheldering
        base_color = (255, 255, 255)
    else:
        # Negatief = zwart voor verdonkering  
        base_color = (0, 0, 0)
    
    # Bereken alpha op basis van percentage (max 50 = alpha 1.0)
    alpha = abs(percentage) / 50.0
    alpha = max(0.0, min(1.0, alpha))  # Zorg voor 0.0-1.0 range
    
    return f'rgba({base_color[0]}, {base_color[1]}, {base_color[2]}, {alpha})'


def adjust_color_brightness(hex_color, percentage):
    """
    Adjust the brightness of a hex color by a percentage.
    
    Args:
        hex_color (str): Hex color string (e.g., '#ffffff')
        percentage (int): Percentage to adjust (-100 to 100)
                         Positive = lighter, Negative = darker
    
    Returns:
        str: RGBA color string for CSS (e.g., 'rgba(255, 255, 255, 0.9)')
    """
    if not hex_color or not isinstance(hex_color, str):
        return 'rgba(255, 255, 255, 0.1)'
    
    # Get RGB values
    r, g, b = hex_to_rgb(hex_color)
    
    # Calculate adjustment factor
    if percentage > 0:
        # Lighten: move towards white
        factor = percentage / 100.0
        r = int(r + (255 - r) * factor)
        g = int(g + (255 - g) * factor)
        b = int(b + (255 - b) * factor)
    else:
        # Darken: move towards black
        factor = abs(percentage) / 100.0
        r = int(r * (1 - factor))
        g = int(g * (1 - factor))
        b = int(b * (1 - factor))
    
    # Ensure values are within 0-255 range
    r = max(0, min(255, r))
    g = max(0, min(255, g))
    b = max(0, min(255, b))
    
    # Return as rgba with slight transparency for better blending
    return f'rgba({r}, {g}, {b}, 0.9)'


def get_base_background_color():
    """
    Get the base background color for history adjustments.
    This should be the main chat background color.
    
    Returns:
        str: Hex color string
    """
    # Use a neutral base color that works well with adjustments
    return '#f8f9fa'
