"""Tests for ColorStripStore startup migrations."""

import json

import pytest

from ledgrab.storage.color_strip_source import SingleColorStripSource
from ledgrab.storage.color_strip_store import ColorStripStore
from ledgrab.storage.database import Database


@pytest.fixture
def tmp_db(tmp_path):
    db = Database(tmp_path / "test.db")
    yield db
    db.close()


def _insert_legacy_row(db: Database, item_id: str, name: str, color: list[int]) -> dict:
    """Insert a pre-rename color strip row with ``source_type='static'``."""
    from datetime import datetime, timezone

    now = datetime.now(timezone.utc).isoformat()
    blob = {
        "id": item_id,
        "name": name,
        "source_type": "static",
        "color": color,
        "animation": None,
        "tags": [],
        "led_count": 30,
        "created_at": now,
        "updated_at": now,
        "icon": "",
        "icon_color": "",
    }
    db.upsert("color_strip_sources", item_id, name, blob)
    return blob


def test_legacy_static_row_is_rewritten_to_single_color(tmp_db):
    """A row with ``source_type='static'`` is rewritten on first store load."""
    _insert_legacy_row(tmp_db, "css_legacy01", "Legacy Solid", [255, 0, 0])

    # Sanity: legacy blob really is on disk
    raw_before = tmp_db.load_all("color_strip_sources")
    assert raw_before[0]["source_type"] == "static"

    store = ColorStripStore(tmp_db)

    # In-memory item is a SingleColorStripSource with the canonical type
    item = store.get("css_legacy01")
    assert isinstance(item, SingleColorStripSource)
    assert item.source_type == "single_color"

    # The on-disk row was rewritten too — no second migration on next boot
    raw_after = tmp_db.load_all("color_strip_sources")
    assert raw_after[0]["source_type"] == "single_color"


def test_already_migrated_row_is_left_alone(tmp_db):
    """Rows already using ``single_color`` are not touched."""
    from datetime import datetime, timezone

    now = datetime.now(timezone.utc).isoformat()
    blob = {
        "id": "css_new01",
        "name": "Already Migrated",
        "source_type": "single_color",
        "color": [0, 128, 255],
        "animation": None,
        "tags": [],
        "led_count": 30,
        "created_at": now,
        "updated_at": now,
        "icon": "",
        "icon_color": "",
    }
    tmp_db.upsert("color_strip_sources", "css_new01", "Already Migrated", blob)

    raw_before = tmp_db.load_all("color_strip_sources")
    before_json = json.dumps(raw_before[0], sort_keys=True)

    store = ColorStripStore(tmp_db)
    item = store.get("css_new01")
    assert isinstance(item, SingleColorStripSource)

    raw_after = tmp_db.load_all("color_strip_sources")
    after_json = json.dumps(raw_after[0], sort_keys=True)
    assert before_json == after_json
