# -*- coding: utf-8 -*-
"""Never a broken text, never an empty hero (docs/plan/genre-browser/070 §Texty). Pure: no Kodi, no network.

Kodi's skin fonts draw Latin (and Latin Extended) only well: a Japanese, Korean, Hindi … title shows as boxes. A title
outside Latin takes the English one, else the original one if that is Latin; a title with none of them is dropped.
An empty Czech overview takes the English one (measured 2026-10-29: cs 64 %, en fills the rest, data/tmdb-probe.json).
"""
LATIN_END = 0x024F                       # Basic Latin … Latin Extended-B
PUNCTUATION = range(0x2000, 0x206F + 1)  # dashes, quotes, ellipsis of General Punctuation draw fine too


def readable(text):
    """True when every letter of `text` is one the skin fonts draw."""
    return all(ord(c) <= LATIN_END or ord(c) in PUNCTUATION for c in text or '')


def _title(item):
    return item.get('title') or item.get('name') or ''


def _original(item):
    return item.get('original_title') or item.get('original_name') or ''


def needs_english(items):
    """Whether a page of TMDb list items (in Czech) needs its English version."""
    return any(not item.get('overview') or not readable(_title(item)) for item in items)


def fix(items, english):
    """The items with readable titles and filled overviews; `english` the same page in en-US ({id: item} or [])."""
    by_id = english if isinstance(english, dict) else {e.get('id'): e for e in english or [] if isinstance(e, dict)}
    out = []
    for item in items:
        other = by_id.get(item.get('id')) or {}
        title = next((t for t in (_title(item), _title(other), _original(item)) if t and readable(t)), '')
        if not title:
            continue
        fixed = dict(item)
        fixed['title' if 'title' in item or 'name' not in item else 'name'] = title
        if not fixed.get('overview') and other.get('overview'):
            fixed['overview'] = other['overview']
        out.append(fixed)
    return out
