"""Sequence beat phase alignment (sync to musical downbeat)."""

import os
import sys

PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC_PATH = os.path.join(PROJECT_ROOT, "src")
if SRC_PATH not in sys.path:
    sys.path.insert(0, SRC_PATH)

from util.sequence_playback import apply_beat_phase_sync  # noqa: E402


def _ctx(lane_states):
    return {"lane_states": lane_states, "sequence_loop_beat": 5}


def test_apply_beat_phase_sync_step_resets_beat_count_only():
    ctx = _ctx(
        [
            {"stepIdx": 2, "beatCount": 3, "done": False},
            {"stepIdx": 1, "beatCount": 1, "done": True},
        ]
    )
    ok, resend = apply_beat_phase_sync(ctx, "step")
    assert ok is True
    assert resend is False
    assert ctx["lane_states"][0]["stepIdx"] == 2
    assert ctx["lane_states"][0]["beatCount"] == 0
    assert ctx["lane_states"][1]["beatCount"] == 1
    assert ctx["sequence_loop_beat"] == 5


def test_apply_beat_phase_sync_pass_restarts_pass():
    ctx = _ctx([{"stepIdx": 2, "beatCount": 3, "done": False}])
    ok, resend = apply_beat_phase_sync(ctx, "pass")
    assert ok is True
    assert resend is True
    st = ctx["lane_states"][0]
    assert st["stepIdx"] == 0
    assert st["beatCount"] == 0
    assert st["done"] is False
    assert ctx["sequence_loop_beat"] == 0
