from models.sequence import Sequence
import os

_HERE = os.path.dirname(os.path.abspath(__file__))
_PROJECT_DB = os.path.normpath(os.path.join(_HERE, "..", "..", "db", "sequence.json"))


def test_sequence():
    """Test Sequence model CRUD operations."""
    if os.path.exists(_PROJECT_DB):
        os.remove(_PROJECT_DB)

    sequences = Sequence()

    print("Testing create sequence")
    sequence_id = sequences.create("1")
    print(f"Created sequence with ID: {sequence_id}")
    assert sequence_id is not None
    assert sequence_id in sequences

    print("\nTesting read sequence")
    sequence = sequences.read(sequence_id)
    print(f"Read: {sequence}")
    assert sequence is not None
    assert sequence["profile_id"] == "1"
    assert sequence["steps"] == []
    assert sequence["lanes"] == [[]]
    assert sequence.get("lanes_group_ids") == [[]]
    assert sequence.get("advance_mode") == "beats"
    assert sequence.get("simulated_bpm") == 120
    assert sequence["step_duration_ms"] == 3000
    assert sequence["loop"] is True
    assert sequence.get("sequence_transition") == 500

    print("\nTesting update sequence")
    update_data = {
        "name": "updated_seq",
        "steps": [
            {"preset_id": "5", "group_ids": ["1"], "beats": 2},
            {"preset_id": "6", "group_ids": [], "beats": 4},
        ],
        "lanes_group_ids": [["1"]],
        "step_duration_ms": 5000,
        "loop": True,
        "advance_mode": "beats",
        "simulated_bpm": 128,
    }
    result = sequences.update(sequence_id, update_data)
    assert result is True
    updated = sequences.read(sequence_id)
    assert updated["name"] == "updated_seq"
    assert len(updated["steps"]) == 2
    assert updated["steps"][0]["preset_id"] == "5"
    assert updated["steps"][0]["group_ids"] == ["1"]
    assert updated["steps"][0].get("beats") == 2
    assert isinstance(updated.get("lanes"), list)
    assert len(updated["lanes"]) == 1
    assert len(updated["lanes"][0]) == 2
    assert updated["lanes"][0][0]["beats"] == 2
    assert updated.get("advance_mode") == "beats"
    assert updated.get("simulated_bpm") == 128
    assert updated["step_duration_ms"] == 5000
    assert updated["loop"] is True

    print("\nTesting list sequences")
    sequence_list = sequences.list()
    print(f"Sequence list: {sequence_list}")
    assert sequence_id in sequence_list

    print("\nTesting delete sequence")
    deleted = sequences.delete(sequence_id)
    assert deleted is True
    assert sequence_id not in sequences

    print("\nTesting read after delete")
    sequence = sequences.read(sequence_id)
    assert sequence is None

    print("\nAll sequence tests passed!")


if __name__ == "__main__":
    test_sequence()
