"""Offline checks of the Vinyl radio (docs/plan/vinyl-radio): what the player shows, the shadow playlist of a
collection, the start request, and the creator's stop."""
from pathlib import Path
import sys
import unittest
from unittest.mock import patch

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import stubs
stubs.install()
import xbmcaddon
import os
import tempfile
from wcs.skin import slots
from wcs.vinyl import client, radio, radio_player, radio_start, radio_widgets

MARKS = [
    {'atSec': 0.5, 'kind': 'speech', 'text': 'Host: Vítejte <short pause> u nás.'},
    {'atSec': 1.0, 'kind': 'track', 'song': {'id': 1, 'title': 'One', 'artist': 'A'}},
    {'atSec': 6.0, 'kind': 'speech', 'text': 'Host: Tohle je [laughs] |přesně tak| One.\nHostka: Paráda .'},
    {'atSec': 200.0, 'kind': 'track', 'song': {'id': 2, 'title': 'Two', 'artist': 'B'}},
]


class VinylRadioTests(unittest.TestCase):
    def setUp(self):
        self.addCleanup(patch.stopall)
        patch.object(xbmcaddon.Addon, 'settings', {'vinyl_user_id': '11', 'vinyl_token': 'synthetic'}).start()

    def test_heard_follows_the_listener_second(self):
        self.assertEqual(radio_player.heard(MARKS, 0.7), (None, 'Vítejte u nás.'))
        track, speech = radio_player.heard(MARKS, 3)
        self.assertEqual((track['title'], speech), ('One', None))
        self.assertEqual(radio_player.heard(MARKS, 150)[1], 'Tohle je (přesně tak) One.\nParáda.')
        track, speech = radio_player.heard(MARKS, 201)
        self.assertEqual((track['title'], speech), ('Two', None), 'a new track clears the last comment')

    def test_collection_airs_from_a_shadow_playlist_named_like_the_web(self):
        songs = [{'id': n} for n in range(80)]
        with patch('wcs.vinyl.context.owns', return_value=False), \
                patch.object(client, 'collection', return_value=songs), \
                patch.object(client, 'request', return_value={'playlistId': 55}) as request:
            source = radio._source('artist', {'name': 'Hozier'})
        self.assertEqual((source['payload'], source['page'], source['count']),
                         ({'playlistId': 55}, {'pageType': 'artist', 'pageId': 'Hozier'}, radio.SAMPLE))
        path, method, body = request.call_args[0]
        self.assertEqual((path, method, body['name']), ('playlists/shadow', 'POST', '[auto] Artist: Hozier'))
        self.assertEqual(len(body['songIds']), radio.SAMPLE)
        with patch('wcs.vinyl.context.owns', return_value=True), \
                patch.object(client, 'collection', return_value=songs[:3]):
            source = radio._source('playlist', {'id': '7', 'name': 'Mix'})
        self.assertEqual((source['payload'], source['page'], source['count']),
                         ({'playlistId': 7}, {'pageType': 'playlist', 'pageId': '7'}, 3))

    def test_the_studio_decision_starts_with_the_preset_and_page_then_tunes_in(self):
        broadcast = {'id': 'b1', 'title': 'T', 'creatorUserId': 11}
        page = {'pageType': 'playlist', 'pageId': '7'}
        with patch('wcs.vinyl.radio_studio.show', return_value=('launch', {'playlistId': 7}, 'neon-fm', page)), \
                patch.object(radio, '_source', return_value={'page': page}), \
                patch.object(client, 'request', return_value={'broadcast': broadcast}) as request, \
                patch('wcs.vinyl.radio_widgets.request') as rows, \
                patch.object(radio, 'tune') as tune:
            radio.start({'kind': 'playlist', 'id': '7'})
        self.assertEqual(request.call_args[0][:3], ('radio/launch', 'POST',
                                                    {'playlistId': 7, 'characterId': 'neon-fm', 'pageType': 'playlist', 'pageId': '7'}))
        tune.assert_called_once_with(broadcast)
        rows.assert_called_once_with()

    def test_a_card_of_someone_elses_broadcast_tunes_in(self):
        broadcasts = {'broadcasts': [{'id': 'b2', 'creatorUserId': 99}]}
        with patch.object(client, 'request', return_value=broadcasts), patch.object(radio, 'tune') as tune:
            radio.tune_id('b2')
        tune.assert_called_once_with(broadcasts['broadcasts'][0])

    def test_the_radio_rows_join_vinyl_once_in_their_places(self):
        shown = ['vinyl_curator', 'vinyl_playlists', 'vinyl_genres', 'vinyl_artists', 'home_vinyl_actions']
        widgets = {n: {'type': row, 'limit': '20', 'sort': '', 'style': '', 'uid': row} for n, row in enumerate(shown, 1)}
        blank = {'type': '', 'limit': '', 'sort': '', 'style': ''}

        def current(sec, n):
            return dict(widgets.get(n, blank))

        def write(sec, rows, hw, up):
            widgets.clear()
            widgets.update({n: dict(w) for n, w in enumerate(rows, 1)})
            return True

        with patch.object(slots, 'current', side_effect=current), patch.object(slots, '_write_section', side_effect=write), \
                patch.object(slots, 'reload_skin') as reload, patch('xbmc.executebuiltin') as execute:
            slots.add_radio_rows()
            first = [widgets[n]['type'] for n in sorted(widgets)]
            slots.add_radio_rows()
        self.assertEqual(first, ['vinyl_curator', 'vinyl_radio_live', 'vinyl_radio_studio', 'vinyl_playlists', 'vinyl_genres',
                                 'vinyl_artists', 'vinyl_radio_records', 'home_vinyl_actions'])
        self.assertEqual([widgets[n]['type'] for n in sorted(widgets)], first, 'a second run moves nothing')
        execute.assert_any_call('Skin.SetBool(MilionarRadioV1)', True)
        self.assertEqual(reload.call_count, 1, "only the run that moved rows reloads the skin")
        self.assertEqual(slots.styles_of('vinyl_radio_live')[0], 'square')
        self.assertEqual(slots.default_for('vinyl_radio_studio', 'vinyl')[3], 'categories')

    def test_the_on_air_row_is_published_only_when_its_cards_change(self):
        folder = tempfile.mkdtemp()
        self.addCleanup(lambda: [os.remove(os.path.join(folder, f)) for f in os.listdir(folder)])
        on_air = {'broadcasts': [{'id': 'b1', 'sessionId': 3, 'title': 'Noc', 'creatorUserId': 11, 'creatorName': 'DjC',
                                  'listeners': 1, 'nowPlaying': {'id': 5, 'title': 'One', 'artist': 'A', 'path': 'x'}}]}
        with patch.object(client, 'cache_path', side_effect=lambda source, user=None: os.path.join(folder, source + '.json')), \
                patch.object(client, 'request', return_value=on_air), patch('wcs.skin.refresh.changed') as changed:
            self.assertTrue(radio_widgets.refresh('vinyl_radio_live'))
            on_air['broadcasts'][0]['listeners'] = 4
            self.assertTrue(radio_widgets.refresh('vinyl_radio_live'))
            changed.assert_called_once_with(['vinyl_radio_live'])
            self.assertNotIn('path', radio_widgets.snapshot('vinyl_radio_live')['items'][0]['nowPlaying'])
            with patch('wcs.vinyl.radio_widgets.request') as ask:
                cards = radio_widgets.build({'row': 'vinyl_radio_live', 'limit': '20'})
                ask.assert_not_called()
        self.assertEqual(len(cards), 1)
        self.assertIn('action%3Dvinyl_radio_tune', cards[0][0])
        self.assertIn('vinyl_radio_tune', cards[0][1].getProperty('milionar.exec'))

    def test_the_studio_row_opens_the_dialog_on_each_page(self):
        cards = radio_widgets.build({'row': 'vinyl_radio_studio'})
        self.assertEqual([c[1].getProperty('milionar.exec').split('page=')[1].rstrip(')') for c in cards],
                         ['playlists', 'create', 'live', 'records'])

    OPTS = {'characters': [{'id': 'vinyl-fm', 'name': 'Vinyl FM', 'solo': {'description': 'Honza'}, 'duo': {'description': 'Honza a Terka'}},
                           {'id': 'custom', 'name': 'Vlastní', 'solo': {}, 'duo': {}}],
            'recommended': {'characterId': 'vinyl-fm', 'label': 'Ranní show'},
            'ttsModels': [{'id': 'flash', 'label': 'Flash', 'note': ''}, {'id': 'lite', 'label': 'Flash-Lite', 'note': ''}],
            'voices': [{'id': 'Kore', 'name': 'Kore', 'gender': 'F'}, {'id': 'Puck', 'name': 'Puck', 'gender': 'M'}],
            'agyModels': [{'id': '{} ({})'.format(f, r), 'label': ''} for f in ('Gemini 3.8 Flash', 'Claude Opus 5.5')
                          for r in ('Low', 'Medium', 'High')],
            'places': {'Česká republika': ['Praha', 'Plzeň'], 'Slovensko': ['Bratislava', 'Košice']},
            'launch': {'characterId': 'vinyl-fm', 'voiceId': 'Puck', 'voiceId2': 'Kore', 'ttsModel': 'flash',
                       'agyModel': 'Gemini 3.8 Flash (Low)'}}

    def test_the_lobby_rows_show_only_what_applies(self):
        keys = lambda prefs, dram=None: [k for k, _l, _v in radio_start.rows(self.OPTS, prefs, dram)]
        self.assertEqual(keys({'radioCharacterId': 'vinyl-fm'}),
                         ['voice', 'mode', 'tts', 'agy', 'reasoning', 'country', 'city', 'description'])
        self.assertEqual(keys({'radioCharacterId': 'custom', 'radioSpeakerMode': 'duo'})[:5],
                         ['voice', 'mode', 'tts', 'voice1', 'voice2'], 'the custom moderator picks its voices')
        self.assertNotIn('tts', keys({'radioCharacterId': 'custom', 'radioVoiceOff': True}), 'no voice, no voice model')
        self.assertIn('dramaturgy', keys({}, {'source': 'default', 'presets': [], 'playlist': 7}))

    def test_a_setting_changes_like_the_lobby(self):
        dialog = type('D', (), {})()
        dialog.select = lambda *a, **k: 1
        prefs = {'radioAgyModel': 'Gemini 3.8 Flash (High)', 'radioCountry': 'Česká republika', 'radioCity': 'Plzeň'}
        self.assertEqual(radio_start.change('agy', self.OPTS, prefs, dialog), {'radioAgyModel': 'Claude Opus 5.5 (High)'})
        self.assertEqual(radio_start.change('reasoning', self.OPTS, prefs, dialog), {'radioAgyModel': 'Gemini 3.8 Flash (Medium)'})
        self.assertEqual(radio_start.change('country', self.OPTS, prefs, dialog), {'radioCountry': 'Slovensko', 'radioCity': 'Bratislava'})
        self.assertEqual(radio_start.change('voice', self.OPTS, prefs, dialog), {'radioVoiceOff': True, 'radioEngine': 'gemini'})
        self.assertEqual(radio_start.change('voice1', self.OPTS, prefs, dialog), {'radioVoiceGemini1': 'Kore'}, 'men first')

    def test_a_moderator_brings_its_dramaturgy_preset(self):
        dram = {'source': 'custom', 'playlist': 7, 'presets': [{'id': 3, 'name': 'Vinyl FM (Solo)'}, {'id': 4, 'name': 'Vinyl FM (Duo)'}]}
        with patch.object(client, 'request') as request:
            radio_start.follow_moderator(dram, 'vinyl-fm', 'duo', self.OPTS)
            self.assertEqual(request.call_args[0], ('radio/settings/7/source', 'PATCH', {'source': 'preset:4'}))
            radio_start.follow_moderator(dram, 'custom', 'duo', self.OPTS)
        self.assertEqual(dram['source'], 'custom')
        radio_start.follow_moderator(None, 'vinyl-fm', 'solo', self.OPTS)      # not a playlist: nothing to follow

    def test_stream_never_carries_the_users_session(self):
        url = client.stream('radio/broadcast/b1/stream?listener=x')
        self.assertIn('/chudy/mac/4017/api/vinyl/radio/broadcast/b1/stream', url)
        self.assertNotIn('synthetic', url)

    def test_only_the_creator_stop_ends_the_broadcast(self):
        live = radio_player.Live('p', 'b1', 0.0)
        with patch.object(client, 'request') as request:
            live.left()
            request.assert_not_called()
            live.mine = True
            live.left()
        self.assertEqual(request.call_args[0][:2], ('radio/broadcast/b1/stop', 'POST'))


if __name__ == '__main__':
    unittest.main()
