import sys, os, base64, io
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from PIL import Image
from stitch_core import stitch_images

def make(color, w=100, h=80):
    img = Image.new("RGB", (w, h), color)
    buf = io.BytesIO()
    img.save(buf, "PNG")
    return base64.b64encode(buf.getvalue()).decode()

# horizontal
res = stitch_images([make("red", 100, 80), make("blue", 120, 80)], direction="horizontal")
assert res["width"] == 220 and res["height"] == 80, f"horizontal failed: {res}"
print("horizontal OK:", res["width"], "x", res["height"])

# vertical with spacing
res = stitch_images([make("green", 100, 80), make("yellow", 100, 60)], direction="vertical", spacing=10)
assert res["width"] == 100 and res["height"] == 150, f"vertical failed: {res}"
print("vertical OK:", res["width"], "x", res["height"])

# grid 2x2
imgs = [make(c, 50, 50) for c in ["red", "green", "blue", "yellow"]]
res = stitch_images(imgs, direction="grid", columns=2, spacing=5)
assert res["width"] == 105 and res["height"] == 105, f"grid failed: {res}"
print("grid OK:", res["width"], "x", res["height"])

# fit_width
res = stitch_images([make("cyan", 100, 80), make("magenta", 60, 40)], direction="horizontal", resize_mode="fit_width")
assert res["width"] == 200, f"fit_width failed: {res}"
print("fit_width OK:", res["width"], "x", res["height"])

# error on < 2 images
try:
    stitch_images([make("red")], direction="horizontal")
    raise AssertionError("should have raised ValueError")
except ValueError:
    print("error-check OK")

print("ALL TESTS PASSED")
