"""Tests for the single-color audit rule.

The rule downsamples + measures the fraction of pixels within `tolerance`
(Euclidean RGB distance) of the dominant color. Matches if that fraction
exceeds `threshold`. Single-color content is typically uploaded by
mistake (placeholder/error/preview images) and should be flagged.
"""

from PIL import Image

from backend.app.services.audits import single_color


def test_single_color_evaluate_true_for_uniform_image():
    im = Image.new("RGB", (50, 50), (128, 64, 200))
    assert single_color.evaluate(im, threshold=0.9, tolerance=10) is True


def test_single_color_evaluate_false_for_diverse_image():
    # Half black, half white — no single color dominates.
    im = Image.new("RGB", (50, 50), (0, 0, 0))
    for x in range(25):
        for y in range(50):
            im.putpixel((x, y), (255, 255, 255))
    assert single_color.evaluate(im, threshold=0.9, tolerance=10) is False


def test_single_color_evaluate_respects_tolerance_widening():
    # Gradient image: pixels span 0..50 in R channel. Tight tolerance
    # rejects (no concentration), wide tolerance accepts (all near 25).
    im = Image.new("RGB", (50, 50), (0, 0, 0))
    for x in range(50):
        for y in range(50):
            im.putpixel((x, y), (x, 0, 0))
    assert single_color.evaluate(im, threshold=0.9, tolerance=5) is False
    assert single_color.evaluate(im, threshold=0.9, tolerance=50) is True


def test_single_color_evaluate_handles_rgba_input():
    # Alpha channel should be ignored — only RGB matters for the rule.
    im = Image.new("RGBA", (50, 50), (100, 100, 100, 128))
    assert single_color.evaluate(im, threshold=0.9, tolerance=10) is True
