# -*- coding: utf-8 -*-
import os
import tempfile
import numpy as np
import pytest
from gshield_pic_sdk._image import to_bytes, to_rgb_ndarray


def test_to_bytes_path(tmp_path):
    """path: 写入一个 jpg 再读回 bytes。"""
    p = tmp_path / "x.jpg"
    raw = b"\xff\xd8\xff\xe0\x00\x10JFIF"
    p.write_bytes(raw)
    out = to_bytes(str(p))
    assert out == raw


def test_to_bytes_bytes():
    raw = b"\xff\xd8\xff\x00"
    assert to_bytes(raw) == raw


def test_to_bytes_ndarray():
    arr = np.zeros((10, 10, 3), dtype=np.uint8)
    arr[:, :, 0] = 255
    out = to_bytes(arr)
    assert isinstance(out, bytes)
    assert len(out) > 0


def test_to_bytes_empty_bytes():
    with pytest.raises(ValueError, match="empty"):
        to_bytes(b"")


def test_to_bytes_invalid_type():
    with pytest.raises(ValueError, match="str, bytes or ndarray"):
        to_bytes(123)


def test_to_rgb_ndarray_path(tmp_path):
    """path: 用 opencv 写一个 BGR 图再读成 RGB。"""
    import cv2
    p = tmp_path / "y.jpg"
    bgr = np.zeros((4, 4, 3), dtype=np.uint8)
    bgr[:, :, 0] = 100
    bgr[:, :, 1] = 50
    bgr[:, :, 2] = 200
    cv2.imwrite(str(p), bgr)
    out = to_rgb_ndarray(str(p))
    assert out.shape == (4, 4, 3)
    assert out.dtype == np.uint8
    # BGR: ch0=B=100, ch2=R=200 -> RGB: ch0=R=200, ch2=B=100（JPEG 可能有轻微偏差）
    np.testing.assert_allclose(out[:, :, 0], 200, atol=2)
    np.testing.assert_allclose(out[:, :, 2], 100, atol=2)


def test_to_rgb_ndarray_bytes():
    import cv2
    bgr = np.zeros((2, 2, 3), dtype=np.uint8)
    bgr[:, :, 0] = 1
    ok, buf = cv2.imencode(".jpg", bgr)
    assert ok
    out = to_rgb_ndarray(buf.tobytes())
    assert out.shape[0] >= 2 and out.shape[1] >= 2 and out.shape[2] == 3
    assert out.dtype == np.uint8


def test_to_rgb_ndarray_ndarray_bgr():
    # BGR: ch0=B=255, ch2=R=10 -> RGB: ch0=R=10, ch2=B=255
    bgr = np.zeros((3, 3, 3), dtype=np.uint8)
    bgr[:, :, 0] = 255
    bgr[:, :, 2] = 10
    out = to_rgb_ndarray(bgr)
    assert out.shape == (3, 3, 3)
    assert out.dtype == np.uint8
    np.testing.assert_array_equal(out[:, :, 0], 10)
    np.testing.assert_array_equal(out[:, :, 2], 255)
