# Copyright 2026 Espressif Systems (Shanghai) Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import os
import queue
import sys
import time

# Add parent dir to path so we can import esp_viewer
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../"))
sys.path.append(project_root)

from esp_viewer.core.backend import DeviceService
from esp_viewer.core.mock_device import MockDevice
from esp_viewer.core.protocol import CommandType, EventType, Packet


def test_generic_integration():
    # Load Demo Profile
    profile_path = os.path.join(project_root, "esp_viewer/assets/profiles/demo.json")
    with open(profile_path, "r") as f:
        profile = json.load(f)

    cmd_queue = queue.Queue()
    event_queue = queue.Queue()

    # Init Service
    service = DeviceService(cmd_queue, event_queue, profile)
    mock = MockDevice("mock_port", profile=profile)
    service.set_device_interface(mock)

    service.start()

    print(">>> Connectivity Test")
    cmd_queue.put(Packet(CommandType.CONNECT))
    time.sleep(0.5)
    assert mock.connected
    print("PASS: Connected")

    print(">>> Stream Test")
    cmd_queue.put(Packet(CommandType.START_STREAM))
    time.sleep(1.0)  # Let it run for 1 second

    # Check Events
    stream_packets = []
    log_messages = []

    while not event_queue.empty():
        pkt = event_queue.get()
        if pkt.type == EventType.STREAM_DATA:
            stream_packets.append(pkt)
        elif pkt.type == EventType.LOG_MSG:
            log_messages.append(pkt)

    assert len(stream_packets) > 10
    print(f"PASS: Received {len(stream_packets)} data points")

    # Verify Data fields (from demo.json: ts, channel, value1, value2)
    first_pt = stream_packets[0].payload["values"]
    assert "value1" in first_pt
    assert "value2" in first_pt
    assert "_stream_id" in first_pt
    print("PASS: Data fields correct")

    print(">>> Stop Stream")
    cmd_queue.put(Packet(CommandType.STOP_STREAM))
    time.sleep(0.2)

    service.stop()
    service.join()
    mock.close()
    print(">>> Test Complete")


if __name__ == "__main__":
    test_generic_integration()
