"""Tests for multi-source region capture (v0.9.16)."""

import json
import sys
import os

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))


def test_capture_region_new_fields():
    """CaptureRegion has source_type and source_id with backward-compatible defaults."""
    from djhud.models import CaptureRegion

    # New region without source fields — defaults to empty (global source)
    r = CaptureRegion(name="Test", src_x=0, src_y=0, src_w=200, src_h=100,
                      out_x=10, out_y=10, target_h=50)
    assert r.source_type == ""
    assert r.source_id == ""
    assert r.estimated_width() == 100

    # Explicit source fields
    r2 = CaptureRegion(name="Stream", src_x=0, src_y=0, src_w=1080, src_h=80,
                       out_x=0, out_y=0, target_h=80,
                       source_type="stream", source_id="ws://10.66.66.3:7088/ws")
    assert r2.source_type == "stream"
    assert r2.source_id == "ws://10.66.66.3:7088/ws"

    r3 = CaptureRegion(name="Win", src_x=100, src_y=200, src_w=400, src_h=80,
                       out_x=0, out_y=0, target_h=80,
                       source_type="window", source_id="Traktor Pro")
    assert r3.source_type == "window"
    assert r3.source_id == "Traktor Pro"


def test_capture_region_asdict_roundtrip():
    """CaptureRegion serializes/deserializes with new fields intact."""
    from dataclasses import asdict
    from djhud.models import CaptureRegion

    original = CaptureRegion(
        name="Remote DJ", src_x=0, src_y=0, src_w=1080, src_h=80,
        out_x=0, out_y=0, target_h=80,
        source_type="stream", source_id="ws://10.66.66.3:7088/ws"
    )
    d = asdict(original)
    assert d["source_type"] == "stream"
    assert d["source_id"] == "ws://10.66.66.3:7088/ws"

    # Roundtrip through JSON (simulates preset save/load)
    json_str = json.dumps(d)
    loaded = json.loads(json_str)
    restored = CaptureRegion(**loaded)
    assert restored.source_type == "stream"
    assert restored.source_id == "ws://10.66.66.3:7088/ws"
    assert restored.name == "Remote DJ"


def test_backward_compatible_preset_load():
    """Old presets without source_type/source_id load correctly."""
    from djhud.models import CaptureRegion

    # Simulates an old preset region dict
    old_region_data = {
        "name": "Waveform",
        "src_x": 100, "src_y": 200, "src_w": 400, "src_h": 80,
        "out_x": 0, "out_y": 0, "target_h": 80,
        "enabled": True, "locked": False, "edit_as_crop": False,
        "raw_out_x": 0, "raw_out_y": 0,
    }
    r = CaptureRegion(**old_region_data)
    assert r.source_type == ""
    assert r.source_id == ""
    assert r.name == "Waveform"


def test_new_preset_format():
    """New preset format with per-region source info round-trips through JSON."""
    from dataclasses import asdict
    from djhud.models import CaptureRegion

    regions = [
        CaptureRegion(name="Waveform", src_x=100, src_y=200, src_w=400, src_h=80,
                      out_x=0, out_y=0, target_h=80,
                      source_type="window", source_id="Traktor Pro"),
        CaptureRegion(name="Remote DJ", src_x=0, src_y=0, src_w=1080, src_h=80,
                      out_x=400, out_y=0, target_h=80,
                      source_type="stream", source_id="ws://10.66.66.3:7088/ws"),
        CaptureRegion(name="Legacy", src_x=0, src_y=0, src_w=200, src_h=80,
                      out_x=800, out_y=0, target_h=80),  # no source = global
    ]
    preset = {
        "canvas_w": 1080,
        "canvas_h": 80,
        "regions": [asdict(r) for r in regions],
    }
    json_str = json.dumps(preset, indent=2)
    loaded = json.loads(json_str)

    restored = [CaptureRegion(**rd) for rd in loaded["regions"]]
    assert restored[0].source_type == "window"
    assert restored[0].source_id == "Traktor Pro"
    assert restored[1].source_type == "stream"
    assert restored[2].source_type == ""
    assert restored[2].source_id == ""


def test_stream_receiver_import():
    """StreamReceiver class imports and instantiates."""
    from djhud.stream_input import StreamReceiver

    rx = StreamReceiver("ws://10.66.66.3:7088/ws")
    assert rx.ws_url == "ws://10.66.66.3:7088/ws"
    assert rx.frame is None
    assert rx.connected is False
    assert rx.fps == 0.0
    assert rx.frame_count == 0


def test_stream_receiver_no_double_start():
    """Calling start() twice doesn't create duplicate threads."""
    from djhud.stream_input import StreamReceiver

    rx = StreamReceiver("ws://127.0.0.1:99999/ws")  # won't connect
    rx.start()
    thread1 = rx._thread
    rx.start()  # should be a no-op
    assert rx._thread is thread1
    rx.stop()


if __name__ == "__main__":
    test_capture_region_new_fields()
    test_capture_region_asdict_roundtrip()
    test_backward_compatible_preset_load()
    test_new_preset_format()
    test_stream_receiver_import()
    test_stream_receiver_no_double_start()
    print("All multi-source tests passed!")
