"""Preset style mode: ``mode`` field, wire ``n6``, and pattern.json metadata."""

import json
import sys
from pathlib import Path

PROJECT_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT_ROOT / "src"))
sys.path.insert(0, str(PROJECT_ROOT / "led-driver" / "src"))

from patterns.pattern_modes import style_mode  # noqa: E402
from preset import Preset  # noqa: E402
from util.espnow_message import build_preset_dict, wire_n6  # noqa: E402


def test_wire_n6_prefers_mode_over_n6():
    assert wire_n6({"mode": 2, "n6": 0}) == 2
    assert wire_n6({"n6": 1}) == 1
    assert wire_n6({}) == 0


def test_build_preset_dict_maps_mode_to_n6():
    wire = build_preset_dict({"pattern": "meteor", "mode": 2, "colors": ["#ffffff"]})
    assert wire["n6"] == 2
    assert wire["p"] == "meteor"


def test_preset_edit_accepts_mode_alias():
    p = Preset({"p": "colour_cycle", "mode": 1, "d": 100, "c": [(255, 255, 255)]})
    assert p.n6 == 1


def test_style_mode_reads_mode_and_legacy_pattern_id():
    p = Preset({"p": "colour_cycle", "mode": 0, "d": 100, "c": [(255, 0, 0)]})
    assert style_mode(p, 0, {"rainbow": 1}) == 0

    legacy = Preset({"p": "rainbow", "d": 100, "c": [(255, 0, 0)]})
    assert style_mode(legacy, 0, {"rainbow": 1}) == 1


def test_pattern_json_defines_mode_for_merged_patterns():
    path = PROJECT_ROOT / "db" / "pattern.json"
    definitions = json.loads(path.read_text(encoding="utf-8"))
    for name in ("colour_cycle", "chase", "aurora", "meteor", "particles", "sparkle"):
        assert name in definitions, name
        mode = definitions[name].get("mode")
        assert isinstance(mode, dict), name
        assert len(mode) >= 2, name

    blink = definitions.get("blink", {})
    assert "mode" not in blink or not isinstance(blink.get("mode"), dict) or len(blink.get("mode", {})) < 2
