import time

from apps.controllers.dataclasses import CommandAction
from apps.controllers.services.commands import route_command_from_api
from apps.installations.models import Installation
from apps.streams.choices import StreamStatus
from apps.streams.models import Stream
from apps.streams.services.lifecycle import create_stream, stop_stream

INSTALLATION_ID = '8e60a05f-1b35-46b5-8f32-f96b40e81689'
USER_ID = 'c49239c2-acea-4fc4-817e-c562f67e747c'  # root@plevion.com

_ACTIVE_STATUSES = {StreamStatus.pending, StreamStatus.starting, StreamStatus.transmitting, StreamStatus.disconnected}

for s in Stream.objects.filter(installation_id=INSTALLATION_ID, status__in=_ACTIVE_STATUSES):
    stop_stream(str(s.id))
    print(f'stopped previous stream {s.id}')

installation = Installation.objects.get(id=INSTALLATION_ID)
stream = create_stream(installation_id=INSTALLATION_ID, user_id=USER_ID, protocol='webrtc')
route_command_from_api(installation.controller, CommandAction.STREAM_START, stream_id=str(stream.id))

deadline = time.monotonic() + 60
while time.monotonic() < deadline:
    stream.refresh_from_db()
    if stream.status == StreamStatus.transmitting:
        break
    if stream.status == StreamStatus.failed:
        raise RuntimeError(f'stream {stream.id} failed to start: {stream.status}')
    time.sleep(2)

print(f'NEW_STREAM_ID={stream.id} STATUS={stream.status}')
