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55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
"""Shared helpers for metadata providers and resolvers."""
from __future__ import annotations

import asyncio
import re
from difflib import SequenceMatcher
from typing import Any, Dict, Optional
from urllib.parse import quote

from rapidfuzz import fuzz

from Backend.helper.bounded import BoundedDict
from Backend.logger import LOGGER

# Match thresholds
CINEMETA_THRESHOLD = 0.60
TMDB_THRESHOLD = 0.55
TVDB_THRESHOLD = 0.55
KITSU_THRESHOLD = 0.55
STRONG_MATCH = 0.92
ALT_TITLE_LOOKUPS = 5

# Combined-file constants (Specials season)
COMBINED_SEASON = 0
COMBINED_EPISODE_BASE = 1000

GRADIENT_COVER_BASE = "https://gradient-cover-api.vercel.app"

API_SEMAPHORE = asyncio.Semaphore(12)

# Shared caches (provider modules may also keep their own)
IMDB_CACHE = BoundedDict(300)
TMDB_SEARCH_CACHE = BoundedDict(300)
TMDB_DETAILS_CACHE = BoundedDict(300)
EPISODE_CACHE = BoundedDict(500)
ALT_TITLES_CACHE = BoundedDict(300)
TVDB_CACHE = BoundedDict(300)
KITSU_CACHE = BoundedDict(300)

_INFLIGHT: Dict[tuple, asyncio.Future] = {}

_APOSTROPHE_RE = re.compile(r"['\u2018\u2019`\u00B4]")
_SYMBOL_STRIP_RE = re.compile(r"[&.\-:]+")
_HTML_RE = re.compile(r"<[^>]+>")


async def cached_call(store: dict, key, ns: str, producer):
    if key in store:
        return store[key]
    flight_key = (ns, key)
    fut = _INFLIGHT.get(flight_key)
    if fut is not None:
        return await fut
    fut = asyncio.get_running_loop().create_future()
    _INFLIGHT[flight_key] = fut
    try:
        result = await producer()
    except Exception as e:
        _INFLIGHT.pop(flight_key, None)
        if not fut.done():
            fut.set_exception(e)
            fut.exception()
        raise
    store[key] = result
    _INFLIGHT.pop(flight_key, None)
    if not fut.done():
        fut.set_result(result)
    return result


def strip_html(text: str) -> str:
    if not text:
        return ""
    return re.sub(r"\s+", " ", _HTML_RE.sub(" ", text)).strip()


def normalize_title(title: str) -> str:
    if not title:
        return ""
    t = title.lower().strip()
    t = re.sub(r"^\b(the|a|an)\b\s+", "", t)
    t = re.sub(r"[^\w\s]", " ", t)
    return re.sub(r"\s+", " ", t).strip()


def fuzzy_ratio(a: str, b: str) -> float:
    if not a or not b:
        return 0.0
    try:
        set_ratio = fuzz.token_set_ratio(a, b) / 100.0
        sort_ratio = fuzz.token_sort_ratio(a, b) / 100.0
        a_tokens, b_tokens = a.split(), b.split()
        coverage = (
            min(len(a_tokens), len(b_tokens)) / max(len(a_tokens), len(b_tokens))
            if a_tokens and b_tokens
            else 0.0
        )
        return max(sort_ratio, set_ratio * coverage)
    except Exception:
        return SequenceMatcher(None, a, b).ratio()


def title_similarity(t1: str, t2: str) -> float:
    n1, n2 = normalize_title(t1), normalize_title(t2)
    return fuzzy_ratio(n1, n2) if n1 and n2 else 0.0


def year_from_str(year_val) -> int:
    if not year_val:
        return 0
    m = re.search(r"(\d{4})", str(year_val))
    return int(m.group(1)) if m else 0


def strip_symbols(text: str) -> str:
    if not text:
        return ""
    text = _APOSTROPHE_RE.sub("", text)
    text = _SYMBOL_STRIP_RE.sub(" ", text)
    return re.sub(r"\s+", " ", text).strip()


def score_candidate(
    query_title: str,
    query_year: Optional[int],
    result_title: str,
    result_year: int,
    year_reliable: bool = True,
    year_lower_bound: bool = False,
) -> float:
    score = title_similarity(query_title, result_title)
    if score < 0.5:
        return score

    if query_year and result_year:
        if year_lower_bound:
            if int(query_year) >= result_year and score >= 0.80:
                score += 0.15 / (1 + (int(query_year) - result_year) * 0.1)
            return score
        diff = abs(int(query_year) - result_year)
        if year_reliable:
            if diff > 2:
                score = max(0.0, score - 0.10 * (diff - 2))
            elif score >= 0.80:
                if diff == 0:
                    score = min(1.0, score + 0.20)
                elif diff == 1:
                    score = min(1.0, score + 0.07)
        elif diff == 0 and score >= 0.80:
            score = min(1.0, score + 0.05)
    elif query_year and year_reliable and not year_lower_bound:
        score = max(0.0, score - 0.20)
    return score



def collect_title_aliases(*groups) -> list:
    """Flatten title / alias fields from provider payloads into unique strings."""
    out: list = []
    seen: set = set()
    for group in groups:
        if group is None:
            continue
        if isinstance(group, str):
            items = [group]
        elif isinstance(group, dict):
            # translations / titles maps: use all values
            items = list(group.values())
        elif isinstance(group, (list, tuple, set)):
            items = []
            for x in group:
                if isinstance(x, dict):
                    # TVDB-style {"name": "..."} or {"title": "..."}
                    items.append(x.get("name") or x.get("title") or x.get("alias") or "")
                else:
                    items.append(x)
        else:
            items = [str(group)]
        for raw in items:
            t = str(raw or "").strip()
            if not t:
                continue
            key = t.lower()
            if key in seen:
                continue
            seen.add(key)
            out.append(t)
    return out


def score_candidate_aliases(
    query_title: str,
    query_year: Optional[int],
    primary_title: str,
    result_year: int,
    aliases=None,
    year_reliable: bool = True,
    year_lower_bound: bool = False,
) -> float:
    """Score a candidate using primary title + all aliases (best match wins).

    Used by TVDB / TMDB / Kitsu / Cinemeta so alternate names, translations,
    and abbreviations participate in matching β€” not only the canonical title.
    """
    titles = collect_title_aliases(primary_title, aliases)
    if not titles:
        return 0.0
    best = 0.0
    for t in titles:
        s = score_candidate(
            query_title, query_year, t, result_year,
            year_reliable=year_reliable,
            year_lower_bound=year_lower_bound,
        )
        if s > best:
            best = s
            if best >= STRONG_MATCH:
                break
    return best


def build_query_variants(title: str, year: Optional[int] = None) -> list:
    variants = [title]
    if year:
        variants.append(f"{title} {year}")
    stripped = re.sub(r"\s+", " ", re.sub(r"[^\w\s]", " ", title)).strip()
    if stripped and stripped.lower() != title.lower():
        variants.append(stripped)
        if year:
            variants.append(f"{stripped} {year}")
    no_article = re.sub(r"^\b(the|a|an)\b\s+", "", title, flags=re.IGNORECASE).strip()
    if no_article and no_article.lower() != title.lower():
        variants.append(no_article)
    seen: set = set()
    ordered = []
    for v in variants:
        key = v.lower()
        if v and key not in seen:
            seen.add(key)
            ordered.append(v)
    return ordered


def first(value):
    return value[0] if isinstance(value, list) else value


def format_runtime(minutes) -> str:
    return f"{minutes} min" if minutes else ""


def gradient_cover_path(title: str, portrait: bool = False) -> str:
    path = f"/api/image?text={quote((title or 'Media').strip() or 'Media')}&badge="
    return f"{path}&orientation=portrait" if portrait else path


def resolve_cover_url(value: str) -> str:
    value = str(value or "")
    idx = value.find("/api/image?")
    return f"{GRADIENT_COVER_BASE}{value[idx:]}" if idx != -1 else value


def format_tmdb_image(path: str, size="w500") -> str:
    return f"https://image.tmdb.org/t/p/{size}{path}" if path else ""


def format_imdb_images(imdb_id: str) -> dict:
    if not imdb_id:
        return {"poster": "", "backdrop": "", "logo": ""}
    return {
        "poster": f"https://images.metahub.space/poster/small/{imdb_id}/img",
        "backdrop": f"https://images.metahub.space/background/medium/{imdb_id}/img",
        "logo": f"https://images.metahub.space/logo/medium/{imdb_id}/img",
    }


ID_REFS = re.compile(r"(?:https?://)?(?:www\.|m\.)?(?:imdb\.com/title/tt\d+|themoviedb\.org/(?:movie|tv)/\d+)\S*|\btt\d{7,10}\b", re.I)


def has_raw_ref(text) -> bool:
    return bool(ID_REFS.search(text or ""))


#----- Caption plus the URLs hidden behind its text links (IMDB deeplinks)
def caption_with_links(message) -> str:
    urls = [e.url for e in (getattr(message, "caption_entities", None) or []) if getattr(e, "url", None)]
    return "\n".join([getattr(message, "caption", None) or "", *urls])


def extract_default_id(text: str) -> str | None:
    if not text:
        return None
    bare_imdb = re.search(r"\b(tt\d{7,10})\b", text)
    if bare_imdb:
        return bare_imdb.group(1)
    imdb_url = re.search(r"/title/(tt\d+)", text)
    if imdb_url:
        return imdb_url.group(1)
    tmdb_url = re.search(r"/(?:movie|tv)/(\d+)", text)
    if tmdb_url:
        return tmdb_url.group(1)
    return None


def split_default_id(default_id) -> tuple:
    """Returns (imdb_id, tmdb_id, explicit_imdb, use_tmdb)."""
    if not default_id:
        return None, None, False, False
    value = str(default_id).strip()
    if value.startswith("tt"):
        return value, None, True, False
    if value.isdigit():
        return None, int(value), False, True
    return None, None, False, False


def empty_payload_base() -> dict:
    return {
        "tmdb_id": None,
        "imdb_id": None,
        "title": "",
        "year": 0,
        "rate": 0,
        "description": "",
        "poster": "",
        "backdrop": "",
        "logo": "",
        "cast": [],
        "runtime": "",
        "genres": [],
        "original_language": None,
        "origin_country": [],
    }



def ensure_media_ids(payload: dict, *, seed: str = "") -> dict:
    """Guarantee usable integer tmdb_id and string imdb_id for DB / Stremio / admin UI.

    - Real provider IDs are kept when present.
    - Missing tmdb_id β†’ negative synthetic id (same pattern as manual/custom titles).
    - Missing imdb_id β†’ ``tg{abs(tmdb_id)}`` so Stremio idPrefixes (tt|tg) still work.
    """
    if not isinstance(payload, dict):
        return payload

    tmdb = payload.get("tmdb_id")
    try:
        if tmdb is not None and str(tmdb).strip().lower() not in ("", "null", "none"):
            tmdb = int(tmdb)
        else:
            tmdb = None
    except (TypeError, ValueError):
        tmdb = None

    imdb = payload.get("imdb_id")
    if imdb is not None:
        imdb = str(imdb).strip()
        if imdb.lower() in ("", "null", "none"):
            imdb = None
        elif imdb.isdigit():
            imdb = f"tt{imdb}"
    else:
        imdb = None

    if tmdb is None:
        # Stable-ish synthetic id from available seeds so re-index merges
        import hashlib
        base = (
            seed
            or imdb
            or str(payload.get("kitsu_id") or "")
            or str(payload.get("tvdb_id") or "")
            or str(payload.get("title") or "")
            or "unknown"
        )
        digest = int(hashlib.md5(base.encode("utf-8")).hexdigest()[:8], 16)
        tmdb = -(digest % 1_000_000_000 + 1)

    if not imdb:
        imdb = f"tg{abs(int(tmdb))}"

    payload["tmdb_id"] = int(tmdb)
    payload["imdb_id"] = imdb
    return payload


def coerce_int_id(value, default=None):
    """Parse query/path tmdb_id that may arrive as 'null' / '' / None."""
    if value is None:
        return default
    if isinstance(value, int):
        return value
    s = str(value).strip()
    if not s or s.lower() in ("null", "none", "undefined"):
        return default
    try:
        return int(float(s))  # tolerate "123.0"
    except (TypeError, ValueError):
        return default


def logo_from_imdb(imdb_id: str | None) -> str:
    """Metahub clearlogo built from an IMDb id (used when providers lack logos)."""
    if not imdb_id:
        return ""
    iid = str(imdb_id).strip()
    if not iid.startswith("tt"):
        iid = f"tt{iid}" if iid.isdigit() else iid
    return f"https://images.metahub.space/logo/medium/{iid}/img"


def normalize_rating(value) -> float:
    """Clamp provider scores into a 0–10 star-style rating.

    TVDB ``score`` is often a popularity rank (hundreds/thousands) β€” those
    must not surface as 953.4-style ratings.
    """
    try:
        v = float(value or 0)
    except (TypeError, ValueError):
        return 0.0
    if v <= 0:
        return 0.0
    if v <= 10:
        return round(v, 1)
    if v <= 100:
        # percentage-style (e.g. 82.5 β†’ 8.3)
        return round(v / 10.0, 1)
    # Popularity / rank scores β€” not a star rating
    return 0.0


def parse_year_range(start=None, end=None) -> tuple:
    """Return (start_year:int|0, end_year:int|None) from provider fields."""
    def _y(val):
        if val is None or val == "":
            return None
        if isinstance(val, int):
            return val if val > 0 else None
        m = re.search(r"(19|20)\d{2}", str(val))
        return int(m.group(0)) if m else None

    s = _y(start)
    e = _y(end)
    if s and e and e < s:
        s, e = e, s
    if s and e and e == s:
        e = None
    return s or 0, e