"""Utility functions for generating random background colors that work well with glass UI."""

from __future__ import annotations

import random
from colorsys import hsv_to_rgb

# Curated color palettes that look good with glassmorphism
COLOR_PALETTES = {
    "dark_cool": [
        "#0f172a", "#1e1b4b", "#1e293b", "#0f3d66", "#1a3a52",
        "#0d2b4a", "#1a2f4f", "#162649", "#132d52", "#1f3a5f",
    ],
    "dark_warm": [
        "#2d1f14", "#3d2817", "#3d1a11", "#3d2416", "#4a2c1a",
        "#452318", "#3f2a1f", "#462b1f", "#3d2618", "#4a3222",
    ],
    "dark_jewel": [
        "#1a3a3a", "#2d2842", "#3d2640", "#3d1f4e", "#2f3f5f",
        "#2d3f4a", "#3d2f5f", "#4a2f4a", "#3f2f5f", "#2f4a5f",
    ],
    "dark_forest": [
        "#1b3d2e", "#1a4d2e", "#1f3a2c", "#254333", "#213d3f",
        "#1f4a3a", "#2d4a3d", "#244033", "#2f4a3f", "#1f5a4a",
    ],
    "night_neon": [
        "#0a0a1a", "#1a0a2e", "#16213e", "#0f3460", "#2c1a4a",
        "#1a2a4a", "#0a1f4a", "#2a1a5a", "#1a0a4a", "#0f1a3a",
    ],
}

def _hex_to_rgb(hex_color: str) -> tuple:
    """Convert hex color to RGB (0-1 range)"""
    hex_color = hex_color.lstrip("#")
    return tuple(int(hex_color[i:i+2], 16) / 255.0 for i in (0, 2, 4))

def _rgb_to_hex(r: float, g: float, b: float) -> str:
    """Convert RGB (0-1 range) to hex"""
    return "#{:02x}{:02x}{:02x}".format(
        int(r * 255), int(g * 255), int(b * 255)
    )

def _lighten_color(hex_color: str, factor: float = 0.2) -> str:
    """Lighten a color by a given factor (0.2 = 20% lighter)"""
    r, g, b = _hex_to_rgb(hex_color)
    r = min(1.0, r + factor)
    g = min(1.0, g + factor)
    b = min(1.0, b + factor)
    return _rgb_to_hex(r, g, b)

def _darken_color(hex_color: str, factor: float = 0.2) -> str:
    """Darken a color by a given factor (0.2 = 20% darker)"""
    r, g, b = _hex_to_rgb(hex_color)
    r = max(0.0, r - factor)
    g = max(0.0, g - factor)
    b = max(0.0, b - factor)
    return _rgb_to_hex(r, g, b)

def _saturate_color(hex_color: str, factor: float = 1.2) -> str:
    """Adjust saturation of a color"""
    r, g, b = _hex_to_rgb(hex_color)
    from colorsys import rgb_to_hsv, hsv_to_rgb
    h, s, v = rgb_to_hsv(r, g, b)
    s = min(1.0, s * factor)
    r, g, b = hsv_to_rgb(h, s, v)
    return _rgb_to_hex(r, g, b)

def generate_random_background() -> str:
    """Generate a random background color suitable for glass UI design"""
    palette = random.choice(list(COLOR_PALETTES.values()))
    return random.choice(palette)

def generate_gradient_background(color1: str | None = None, color2: str | None = None) -> str:
    """Generate a two-color gradient background as SVG gradient definition"""
    if color1 is None:
        color1 = generate_random_background()
    if color2 is None:
        # Derive second color from first - either lighter, darker, or different hue
        choice = random.choice(["lighten", "darken", "saturate"])
        if choice == "lighten":
            color2 = _lighten_color(color1, 0.15)
        elif choice == "darken":
            color2 = _darken_color(color1, 0.15)
        else:
            color2 = _saturate_color(color1, 1.3)
    
    gradient_id = f"bg-gradient-{random.randint(1000, 9999)}"
    return f"""<defs>
        <linearGradient id="{gradient_id}" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" style="stop-color:{color1};stop-opacity:1" />
            <stop offset="100%" style="stop-color:{color2};stop-opacity:1" />
        </linearGradient>
    </defs>"""

def get_bg_color(bg_choice: str | None) -> str:
    """Resolve background choice to actual color"""
    if not bg_choice or bg_choice in ("auto", "transparent", "none", "🎲 Random"):
        return generate_random_background()
    
    # Remove emoji from choice if present
    color = bg_choice.split(" ", 1)[-1] if " " in bg_choice else bg_choice
    return color if color.startswith("#") else generate_random_background()

def get_complementary_color(hex_color: str, brightness_offset: float = 0.0) -> str:
    """Get a complementary color for accent/highlights"""
    r, g, b = _hex_to_rgb(hex_color)
    from colorsys import rgb_to_hsv, hsv_to_rgb
    h, s, v = rgb_to_hsv(r, g, b)
    
    # Rotate hue by 180 degrees for complementary color
    h = (h + 0.5) % 1.0
    v = min(1.0, max(0.0, v + brightness_offset))
    
    r, g, b = hsv_to_rgb(h, s, v)
    return _rgb_to_hex(r, g, b)
