# -*- coding: utf-8 -*-
"""The choices of a broadcast's start, the same as Vinyl's Studio lobby (docs/plan/vinyl-radio/020): the moderator
(presets or Vlastní), voice on or "Bez hlasu", Solo / Duo, the voice model, the custom moderator's voices, the AI model
and its reasoning, the dramaturgy of a playlist, the place and the description. Every choice is the user's saved Studio
choice of that page in Vinyl (`radio/page-prefs`, the playlist's `radio/settings/<id>/source`), saved at once like the
web lobby saves it, so Kodi and the web start the same broadcast; Vinyl resolves voices and models. The Radio Studio
dialog (wcs/vinyl/radio_studio.py) shows them.
"""
import re
from urllib.parse import quote, urlencode

import xbmc
import xbmcgui

from wcs.vinyl import client

CREATE_PAGE = {'pageType': 'create-radio', 'pageId': 'lobby'}
CUSTOM = 'custom'
AGY = re.compile(r'^(.*) \((\w+)\)$')                     # "Gemini 3.8 Flash (Low)" -> family, reasoning


def text(number):
    return client.addon().getLocalizedString(number)


def _log(message):
    xbmc.log('[Milionář Vinyl Radio] start: {}'.format(message), xbmc.LOGINFO)


def options(page):
    return client.request('radio/launch/options?' + urlencode(page), timeout=(5, 15))


def save(page, updates):
    """One choice saved like the web lobby saves it, at once."""
    client.request('radio/page-prefs/{}/{}'.format(quote(page['pageType'], safe=''), quote(page['pageId'], safe='')),
                   'PATCH', updates)
    _log('saved {} for {}/{}'.format(sorted(updates), page['pageType'], page['pageId']))


# ---- the playlist's dramaturgy (the lobby's "Dramaturgie": Default, a preset, Vlastní)
def dramaturgy(page):
    """{'source': ..., 'presets': [...], 'playlist': id} of a playlist page; None for any other page."""
    if page.get('pageType') != 'playlist':
        return None
    playlist = int(page['pageId'])
    settings = client.request('radio/settings/{}'.format(playlist), timeout=(5, 15)).get('settings') or {}
    presets = client.request('radio/presets', timeout=(5, 15)).get('presets') or []
    return {'source': settings.get('dramaturgy_source') or CUSTOM, 'playlist': playlist,
            'presets': [{'id': p['id'], 'name': p.get('name') or ''} for p in presets]}


def save_dramaturgy(dram, source):
    client.request('radio/settings/{}/source'.format(dram['playlist']), 'PATCH', {'source': source})
    dram['source'] = source
    _log('dramaturgy of playlist {} -> {}'.format(dram['playlist'], source))


def follow_moderator(dram, character_id, mode, opts):
    """As the lobby does: picking a moderator (or Solo / Duo) picks its dramaturgy preset "<name> (Solo|Duo)"; the custom
    moderator keeps the playlist's own dramaturgy."""
    if not dram:
        return
    if character_id == CUSTOM:
        save_dramaturgy(dram, CUSTOM)
        return
    name = '{} ({})'.format(character(opts, character_id)['name'], 'Duo' if mode == 'duo' else 'Solo')
    preset = next((p for p in dram['presets'] if p['name'] == name), None)
    if preset:
        save_dramaturgy(dram, 'preset:{}'.format(preset['id']))


def _dramaturgy_label(dram):
    source = dram['source']
    if source == 'default':
        return text(33169)
    if source.startswith('preset:'):
        return next((p['name'] for p in dram['presets'] if 'preset:{}'.format(p['id']) == source), source)
    return text(33170)


# ---- reading the choices
def _item(label, label2='', icon=''):
    li = xbmcgui.ListItem(label, label2, offscreen=True)
    if icon:
        li.setArt({'icon': icon})
    return li


def character(opts, identity):
    return next((c for c in opts['characters'] if c['id'] == identity), opts['characters'][0])


def current(opts, prefs):
    return character(opts, prefs.get('radioCharacterId') or opts['launch']['characterId'])


def mode_of(prefs):
    return 'duo' if prefs.get('radioSpeakerMode') == 'duo' else 'solo'


def describe(character, mode):
    """The moderator's card line ("Honza Vinyla — přirozený DJ…"); the custom moderator's own explanation."""
    if character['id'] == CUSTOM:
        return text(33178 if mode == 'duo' else 33177)
    profile = character.get(mode) or character.get('solo') or {}
    names = ' & '.join(n for n in (profile.get('moderatorName'), profile.get('moderatorName2') if mode == 'duo' else '') if n)
    return profile.get('description') or names


def summary(opts, prefs, character):
    return ' · '.join((character['name'], text(33111 if mode_of(prefs) == 'duo' else 33110),
                       text(33114) if prefs.get('radioVoiceOff') else _label(opts['ttsModels'], _tts_model(opts, prefs))))


def _label(entries, value, key='id'):
    return next((e['label'] for e in entries if e[key] == value), value or '')


def _tts_model(opts, prefs):
    models = [m['id'] for m in opts['ttsModels']]
    value = prefs.get('radioGeminiModel')
    return value if value in models else opts['launch'].get('ttsModel') or (models[0] if models else '')


def _agy(opts, prefs):
    """(family, reasoning) of the saved AI model, the families and the reasoning levels Vinyl offers."""
    pairs = [AGY.match(m['id']).groups() for m in opts['agyModels'] if AGY.match(m['id'])]
    families = list(dict.fromkeys(f for f, _r in pairs))
    levels = list(dict.fromkeys(r for _f, r in pairs))
    match = AGY.match(prefs.get('radioAgyModel') or opts['launch'].get('agyModel') or '')
    family, level = match.groups() if match else (families[0], levels[0])
    return (family if family in families else families[0]), (level if level in levels else levels[0]), families, levels


def _place(prefs):
    if prefs.get('radioCountry') == CUSTOM:
        return prefs.get('radioCustomCountry') or '', prefs.get('radioCustomCity') or ''
    city = prefs.get('radioCustomCity') if prefs.get('radioCity') == CUSTOM else prefs.get('radioCity')
    return prefs.get('radioCountry') or '', city or ''


def _voice(opts, prefs, slot):
    value = prefs.get('radioVoiceGemini{}'.format(slot))
    voices = {v['id']: v for v in opts['voices']}
    if value not in voices:
        value = opts['launch']['voiceId'] if slot == 1 else opts['launch']['voiceId2'] or ''
    return value


def _voice_label(opts, voice_id):
    voice = next((v for v in opts['voices'] if v['id'] == voice_id), None)
    return '{} · {}'.format(voice['name'], text(33181 if voice['gender'] == 'M' else 33182)) if voice else (voice_id or '—')


def rows(opts, prefs, dram=None):
    """The lobby's settings as (key, label, value) rows, in its order; what does not apply is left out (the voice model
    without a voice, the voices of a preset moderator, the dramaturgy outside a playlist)."""
    moderator = current(opts, prefs)
    duo, spoken = mode_of(prefs) == 'duo', not prefs.get('radioVoiceOff')
    result = [('voice', text(33112), text(33113 if spoken else 33114)),
              ('mode', text(33109), text(33111 if duo else 33110))]
    if spoken:
        result.append(('tts', text(33115), _label(opts['ttsModels'], _tts_model(opts, prefs))))
        if moderator['id'] == CUSTOM:
            result.append(('voice1', text(33133 if duo else 33180), _voice_label(opts, _voice(opts, prefs, 1))))
            if duo:
                result.append(('voice2', text(33134), _voice_label(opts, _voice(opts, prefs, 2))))
    family, level, _families, _levels = _agy(opts, prefs)
    result += [('agy', text(33116), family), ('reasoning', text(33167), level)]
    if dram is not None:
        result.append(('dramaturgy', text(33168), _dramaturgy_label(dram)))
    country, city = _place(prefs)
    result += [('country', text(33137), country or '—'), ('city', text(33138), city or '—'),
               ('description', text(33172 if moderator['id'] == CUSTOM else 33171), prefs.get('radioDescription') or '—')]
    return result


# ---- changing one
def change(key, opts, prefs, dialog):
    """The new value of one row as page-prefs keys ({} when nothing changed); voice and mode switch at once."""
    if key == 'voice':
        return {'radioVoiceOff': not prefs.get('radioVoiceOff'), 'radioEngine': 'gemini'}
    if key == 'mode':
        # Duo exists only on Gemini, which is the Studio's only engine.
        return {'radioSpeakerMode': 'solo' if mode_of(prefs) == 'duo' else 'duo', 'radioEngine': 'gemini'}
    if key == 'tts':
        models = opts['ttsModels']
        picked = dialog.select(text(33115), [_item(m['label'], m.get('note', '')) for m in models],
                               preselect=next((i for i, m in enumerate(models) if m['id'] == _tts_model(opts, prefs)), 0),
                               useDetails=True)
        return {'radioGeminiModel': models[picked]['id']} if picked >= 0 else {}
    if key in ('voice1', 'voice2'):
        slot = 1 if key == 'voice1' else 2
        voices = sorted(opts['voices'], key=lambda v: (v['gender'] != 'M', v['name']))      # Muž, then Žena, as the lobby
        chosen = _voice(opts, prefs, slot)
        items = [_item('{} · {}{}'.format(v['name'], text(33181 if v['gender'] == 'M' else 33182),
                                          ' · S' if v.get('tier') == 'S' else ''), v.get('description', '')) for v in voices]
        picked = dialog.select(text(33133 if slot == 1 and mode_of(prefs) == 'duo' else 33180 if slot == 1 else 33134),
                               items, preselect=next((i for i, v in enumerate(voices) if v['id'] == chosen), 0), useDetails=True)
        return {'radioVoiceGemini{}'.format(slot): voices[picked]['id']} if picked >= 0 else {}
    if key in ('agy', 'reasoning'):
        family, level, families, levels = _agy(opts, prefs)
        values = families if key == 'agy' else levels
        picked = dialog.select(text(33116 if key == 'agy' else 33167), values,
                               preselect=values.index(family if key == 'agy' else level))
        if picked < 0:
            return {}
        family, level = (values[picked], level) if key == 'agy' else (family, values[picked])
        return {'radioAgyModel': '{} ({})'.format(family, level)}
    if key == 'country':
        return _change_country(opts, prefs, dialog)
    if key == 'city':
        return _change_city(opts, prefs, dialog)
    if key == 'description':
        value = dialog.input(text(33172 if current(opts, prefs)['id'] == CUSTOM else 33171), prefs.get('radioDescription') or '')
        return {'radioDescription': value.strip()} if value is not None and value.strip() != (prefs.get('radioDescription') or '') else {}
    return {}


def change_dramaturgy(dram, dialog):
    sources = ['default'] + ['preset:{}'.format(p['id']) for p in dram['presets']] + [CUSTOM]
    labels = [text(33169)] + [p['name'] for p in dram['presets']] + [text(33170)]
    picked = dialog.select(text(33168), labels, preselect=sources.index(dram['source']) if dram['source'] in sources else 0)
    if picked >= 0 and sources[picked] != dram['source']:
        save_dramaturgy(dram, sources[picked])


def _change_country(opts, prefs, dialog):
    """Like the lobby: another country takes its first city; Vlastní… asks for the country (the city follows)."""
    countries = list(opts['places'])
    picked = dialog.select(text(33137), countries + [text(33119)],
                           preselect=countries.index(prefs['radioCountry']) if prefs.get('radioCountry') in countries
                           else len(countries))
    if picked < 0:
        return {}
    if picked == len(countries):
        country = dialog.input(text(33137), prefs.get('radioCustomCountry') or '').strip()
        return {'radioCountry': CUSTOM, 'radioCity': CUSTOM, 'radioCustomCountry': country} if country else {}
    country = countries[picked]
    cities = opts['places'][country]
    return {'radioCountry': country, 'radioCity': cities[0] if cities else ''}


def _change_city(opts, prefs, dialog):
    if prefs.get('radioCountry') == CUSTOM or prefs.get('radioCountry') not in opts['places']:
        city = dialog.input(text(33138), prefs.get('radioCustomCity') or '').strip()
        return {'radioCity': CUSTOM, 'radioCustomCity': city} if city else {}
    cities = opts['places'][prefs['radioCountry']]
    picked = dialog.select(text(33138), cities + [text(33119)],
                           preselect=cities.index(prefs['radioCity']) if prefs.get('radioCity') in cities else len(cities))
    if picked < 0:
        return {}
    if picked == len(cities):
        city = dialog.input(text(33138), prefs.get('radioCustomCity') or '').strip()
        return {'radioCity': CUSTOM, 'radioCustomCity': city} if city else {}
    return {'radioCity': cities[picked]}
