# -*- coding: utf-8 -*-
"""The settings of the genre widgets in the widget manager (docs/plan/genre-browser/030). Pure: no Kodi.

Every option of a row type is defined here once, with its choices and its default (the defaults come from the headless
tests, docs/plan/genre-browser/900-decisions.md). The skin string `mil.<sec>.<n>.opts` holds only what the user changed
('key=value,key=value'); the code never writes a default into it.

The quality thresholds of the listing (Výpis) are the global setting Kvalita návrhů's (wcs/quality/settings.py): its
values are the `base` of these options, so an option the user did not touch follows the global setting and one they
changed is that genre page's own (Standa 2026-10-29: the genre page never changes the global setting).
"""
from wcs.quality import settings as quality_settings

# row type -> [(key, string id of the label, choices, default)]; a bool option has choices (False, True)
OPTIONS = {
    'fy_genres': [
        ('w_library', 35540, (0.0, 0.5, 1.0, 1.5, 2.0), 1.0),
        ('w_watched', 35541, (0.0, 0.5, 1.0, 1.5, 2.0), 1.0),
        ('w_like', 35542, (0.0, 0.5, 1.0, 1.5, 2.0), 1.0),
        ('w_dislike', 35543, (0.0, 0.5, 1.0, 1.5, 2.0), 1.0),
        ('threshold', 35544, (0.1, 0.2, 0.3, 0.4, 0.5, 0.6), 0.2),
        ('tv_only', 35545, (False, True), False),
    ],
    # the quality thresholds of the filter Původ (wcs/quality, 070): the global setting's, then the listing's own
    'gn_list': [(key,) + quality_settings.SETTINGS[key][1:] for key in quality_settings.THRESHOLDS] + [
        ('star', 35552, (7.0, 7.5, 8.0, 8.5), 7.5),
        ('rating_votes', 35553, (10, 50, 100, 300, 1000), 100),
    ],
}
# the options that follow a global setting until the user changes them on the widget (row -> keys)
GLOBAL = {'gn_list': quality_settings.THRESHOLDS}


def defaults(row, base=None):
    """The options a widget has without changes; `base` the global values ({key: value}) of its GLOBAL options."""
    out = {key: default for key, _label, _choices, default in OPTIONS.get(row, ())}
    out.update({key: base[key] for key in GLOBAL.get(row, ()) if base and key in base})
    return out


def _parse(raw, default):
    if isinstance(default, bool):
        if raw in ('1', 'true', 'True'):
            return True
        if raw in ('0', 'false', 'False'):
            return False
        raise ValueError(raw)
    if isinstance(default, int):
        return int(raw)
    return float(raw)


def values(row, text, base=None):
    """The options of a widget: its defaults (the global ones under `base`) with the stored changes (a broken or
    unknown value is ignored)."""
    result = defaults(row, base)
    for part in (text or '').split(','):
        key, _sep, raw = part.partition('=')
        if key in result:
            try:
                result[key] = _parse(raw, result[key])
            except ValueError:
                pass
    return result


def _text(value):
    if isinstance(value, bool):
        return '1' if value else '0'
    return repr(value) if isinstance(value, float) else str(value)


def changed(row, text):
    """The keys the user set on this widget (stored in its skin string)."""
    stored = {part.partition('=')[0] for part in (text or '').split(',')}
    return {key for key, _l, _c, _d in OPTIONS.get(row, ()) if key in stored}


def encode(row, chosen, base=None):
    """'key=value,…' of the options that differ from their defaults (the global ones under `base`): choosing the
    global value again removes the widget's own ('' when nothing differs)."""
    base = defaults(row, base)
    return ','.join('{}={}'.format(key, _text(chosen[key])) for key, _l, _c, _d in OPTIONS.get(row, ())
                    if key in chosen and chosen[key] != base[key])


def show(value):
    """A value as the manager shows it: 7.5, 6.0, 20 (one decimal for a rating, like the addon settings);
    Zapnuto/Vypnuto is the caller's (bool)."""
    if isinstance(value, float):
        return '%.1f' % value
    return str(value)
