"""
ChameleonEngine — Real-time Album Art Color Match Dynamic Theme for Subify v3.0 Ultra
"""

import threading
import urllib.request
import objc
import AppKit
from AppKit import (
    NSImage, NSBitmapImageRep, NSColor,
    NSVisualEffectMaterialHUDWindow
)
from Quartz import CGColorCreateGenericRGB
from theme_engine import Theme


def extract_dominant_color(image: NSImage) -> tuple:
    """Extract dominant RGB color from an NSImage."""
    if image is None:
        return (0.4, 0.4, 0.4)

    try:
        tiff = image.TIFFRepresentation()
        if not tiff:
            return (0.4, 0.4, 0.4)
        rep = NSBitmapImageRep.imageRepWithData_(tiff)
        if not rep:
            return (0.4, 0.4, 0.4)

        w = rep.pixelsWide()
        h = rep.pixelsHigh()
        if w == 0 or h == 0:
            return (0.4, 0.4, 0.4)

        step_x = max(1, w // 10)
        step_y = max(1, h // 10)

        r_total, g_total, b_total, count = 0.0, 0.0, 0.0, 0

        for x in range(0, w, step_x):
            for y in range(0, h, step_y):
                c = rep.colorAtX_y_(x, y)
                if c:
                    r_total += c.redComponent()
                    g_total += c.greenComponent()
                    b_total += c.blueComponent()
                    count += 1

        if count > 0:
            r = min(max(r_total / count, 0.15), 0.95)
            g = min(max(g_total / count, 0.15), 0.95)
            b = min(max(b_total / count, 0.15), 0.95)
            return (r, g, b)
    except Exception:
        pass

    return (0.4, 0.4, 0.4)


class ChameleonEngine:
    """Generates dynamic glass themes matching currently playing album artwork."""

    @classmethod
    def create_chameleon_theme(cls, image: NSImage) -> Theme:
        r, g, b = extract_dominant_color(image)

        border_rgb = (r, g, b, 0.65)
        shadow_rgb = (r * 0.5, g * 0.5, b * 0.5, 0.6)
        text_color = NSColor.colorWithWhite_alpha_(1.0, 1.0)
        next_text_color = NSColor.colorWithRed_green_blue_alpha_(r + 0.2, g + 0.2, b + 0.2, 0.7)
        accent_color = NSColor.colorWithRed_green_blue_alpha_(r, g, b, 1.0)

        return Theme(
            name='Chameleon',
            material=NSVisualEffectMaterialHUDWindow,
            border_rgb=border_rgb,
            shadow_rgb=shadow_rgb,
            text_color=text_color,
            next_text_color=next_text_color,
            accent_color=accent_color
        )
