# -*- coding: utf-8 -*-
"""
Helper: převod ffprobe JSON (streams) do normalizovaného dictu pro subcaps_cache.
Použití:
    meta = parse_ffprobe_streams(ffprobe_json)
    upsert_result(ident, meta, ffprobe_version)
"""

import re

_CZECH_LANG_CODES = ("cs", "cz", "cze", "ces")

def _res_tag(w: int, h: int) -> str:
    try:
        if h >= 2160 or w >= 3840:
            return "2160p"
        if h >= 1440 or w >= 2560:
            return "1440p"
        if h >= 1080 or w >= 1920:
            return "1080p"
        if h >= 720 or w >= 1280:
            return "720p"
        return "SD"
    except Exception:
        return None

def parse_ffprobe_streams(ffjson: dict) -> dict:
    """
    Očekává ffprobe -show_streams JSON (print_format=json).
    Vrací dict pro subcaps_cache.upsert_result(...).
    """
    streams = (ffjson or {}).get("streams") or []
    out = {
        "cz_subs": False,
        "subs_langs": [],
        "has_cz_audio": False,
        "audio_tracks": [],
        "best_audio": None,
        "video": {}
    }

    # --- VIDEO ---
    best_v = None
    for s in streams:
        if s.get("codec_type") == "video":
            w = s.get("width") or 0
            h = s.get("height") or 0
            pix_fmt = s.get("pix_fmt")
            # HDR/DV heuristiky
            # ffprobe někdy dává color_transfer/side_data_list; tady lehká heuristika
            color_trc = (s.get("color_transfer") or "").lower()
            side = s.get("side_data_list") or []
            hdr = "smpte2084" in color_trc or "hlg" in color_trc
            dv = False
            for sd in side:
                if (sd.get("side_data_type") or "").lower().startswith("dolby vision"):
                    dv = True
                    break
            best_v = {
                "width": w, "height": h, "pix_fmt": pix_fmt,
                "hdr": bool(hdr), "dv": bool(dv),
                "resolution_tag": _res_tag(w, h)
            }
            break  # první video stačí

    if best_v:
        out["video"] = best_v

    # --- AUDIO ---
    # Nasbíráme všechny audio tracky a vybereme 'best' s prioritou CZ -> více kanálů -> bitrate
    audio_tracks = []
    for s in streams:
        if s.get("codec_type") != "audio":
            continue
        tags = s.get("tags") or {}
        lang = (tags.get("language") or "").lower()
        title = tags.get("title") or ""
        codec = (s.get("codec_name") or "").lower()
        ch = s.get("channels")
        layout = s.get("channel_layout")
        br = s.get("bit_rate")
        # Atmos very-rough heuristika: TrueHD nebo E-AC3 s "atmos" v title
        atmos = ("atmos" in title.lower()) or (codec in ("truehd",) and "atmos" in title.lower())
        audio_tracks.append({
            "lang": lang or "und", "codec": codec, "channels": ch, "layout": layout,
            "title": title, "bit_rate": br, "atmos": bool(atmos)
        })

    out["audio_tracks"] = audio_tracks

    # has_cz_audio + best_audio
    def _lang_rank(l):
        l = (l or "").lower()
        # `ces` je ISO 639-2/B alias pro češtinu (vedle `cze`), patří do CZ.
        if l in ("cs", "cz", "cze", "ces"): return 100
        if l in ("sk", "slk", "slo"):       return 90
        if l in ("en", "eng"):              return 80
        return 10

    def _channels_rank(ch):
        try:
            ch = int(ch or 0)
            if ch >= 8: return 80
            if ch >= 6: return 60
            if ch >= 2: return 40
            return 20
        except Exception:
            return 0

    best = None
    best_score = -1
    for tr in audio_tracks:
        score = _lang_rank(tr.get("lang")) + _channels_rank(tr.get("channels"))
        # bonus za atmos
        if tr.get("atmos"):
            score += 10
        if score > best_score:
            best, best_score = tr, score

    out["best_audio"] = best
    out["has_cz_audio"] = any((t.get("lang") or "").lower() in _CZECH_LANG_CODES for t in audio_tracks)

    # --- SUBS ---
    subs_langs = []
    for s in streams:
        if s.get("codec_type") == "subtitle":
            lang = ( (s.get("tags") or {}).get("language") or "und" ).lower()
            subs_langs.append(lang)
    out["subs_langs"] = subs_langs
    out["cz_subs"] = any(l in _CZECH_LANG_CODES for l in subs_langs)

    return out