from models.pallet import Palette
import os

def test_palette():
    """Test Palette model CRUD operations.
    Palette stores a list of colors per ID; read() returns that list (or unwraps from dict).
    """
    # Clean up any existing test file (model uses db/palette.json from project root)
    db_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "db")
    palette_file = os.path.join(db_dir, "palette.json")
    if os.path.exists(palette_file):
        os.remove(palette_file)
    
    palettes = Palette()
    
    print("Testing create palette")
    colors = ["#FF0000", "#00FF00", "#0000FF", "#FFFF00"]
    palette_id = palettes.create("test_palette", colors)
    print(f"Created palette with ID: {palette_id}")
    assert palette_id is not None
    assert palette_id in palettes
    
    print("\nTesting read palette")
    palette = palettes.read(palette_id)
    print(f"Read: {palette}")
    # read() returns list of colors (name is not stored)
    assert palette is not None
    assert isinstance(palette, list) or (isinstance(palette, dict) and "colors" in palette)
    colors_read = palette if isinstance(palette, list) else palette.get("colors", [])
    assert len(colors_read) == 4
    assert "#FF0000" in colors_read
    
    print("\nTesting update palette")
    update_data = {
        "name": "updated_palette",
        "colors": ["#FF00FF", "#00FFFF", "#FFA500"]
    }
    result = palettes.update(palette_id, update_data)
    assert result is True
    updated = palettes.read(palette_id)
    updated_colors = updated if isinstance(updated, list) else (updated.get("colors") or [])
    assert len(updated_colors) == 3
    assert "#FF00FF" in updated_colors
    
    print("\nTesting list palettes")
    palette_list = palettes.list()
    print(f"Palette list: {palette_list}")
    assert palette_id in palette_list
    
    print("\nTesting delete palette")
    deleted = palettes.delete(palette_id)
    assert deleted is True
    assert palette_id not in palettes
    
    print("\nTesting read after delete")
    palette = palettes.read(palette_id)
    # read() returns [] when id is missing (value or [])
    assert palette == [] or palette is None
    
    print("\nAll palette tests passed!")


if __name__ == '__main__':
    test_palette()
