import numpy as np
import pytest
from PIL import Image

from clawid.algorithms.visible import embed_visible
from clawid.core.embed import embed


def make_image(size=(512, 512)) -> Image.Image:
    return Image.new('RGB', size, color=(180, 180, 180))


def test_returns_rgb_image():
    result = embed_visible(make_image(), "clawID test")
    assert isinstance(result, Image.Image)
    assert result.mode == 'RGB'


def test_size_unchanged():
    img = make_image((800, 600))
    result = embed_visible(img, "watermark")
    assert result.size == img.size


def test_modifies_pixels():
    img = make_image()
    result = embed_visible(img, "watermark text")
    assert not np.array_equal(np.array(img), np.array(result))


def test_all_positions():
    img = make_image()
    for pos in ['top-left', 'top-right', 'bottom-left', 'bottom-right', 'center']:
        out = embed_visible(img, "test", position=pos)
        assert out.size == img.size


def test_invalid_position_raises():
    with pytest.raises(ValueError, match="position"):
        embed_visible(make_image(), "text", position='middle')


def test_invalid_opacity_raises():
    with pytest.raises(ValueError, match="opacity"):
        embed_visible(make_image(), "text", opacity=1.5)


def test_embed_visible_mode(tmp_path):
    """End-to-end: embed in visible mode, result is a valid RGB image."""
    src = str(tmp_path / 'src.png')
    out = str(tmp_path / 'out.png')
    make_image().save(src)
    embed(src, out, {'uid': 'vis_user', 'platform': 'hawky.ai'}, mode='visible')
    result = Image.open(out)
    assert result.mode == 'RGB'


def test_embed_both_mode(tmp_path):
    """Both mode should apply invisible + visible watermarks."""
    from clawid.core.detect import detect
    src = str(tmp_path / 'src.png')
    out = str(tmp_path / 'out.png')
    make_image((512, 512)).save(src)
    embed(src, out, {'uid': 'both_user'}, mode='both')
    # Invisible watermark should still be detectable
    result = detect(out)
    assert result is not None
    assert result['uid'] == 'both_user'
