#!/usr/bin/env python3
"""Harman kaynak saglik testi (LXC'de systemd timer ile 12 saatte bir calisir).

Her kaynak icin sirayla:
  1. domain  : giris adresi hala ayni host'a mi cikiyor (DoH + TCP ping + HTTP).
               Gomulu domaini SABIT olan kaynakta host degismisse eklenti kirik
               demektir -> oynatma testleri atlanir, "domain degismis" alarmi gider.
               Domaini dinamik izleyen kaynakta (yonlendirme/ayna/uzak config) degisim
               yalnizca bilgi olarak raporlanir, testlere devam edilir.
  2. katalog : eklentinin ana sayfa satiriyla ayni istek -> rastgele bir icerik.
  3. arama   : o icerigin basligini ara -> en az 1 sonuc.
  4. linkler : eklentinin loadLinks zinciri -> m3u8/mp4 adresi.
  5. akis    : playlist -> (varyant) -> ilk parcanin ilk baytlari indirilir.

Sorun varsa Telegram'a bildirim atar (--always ile her kosuda ozet atar).
Adresler/anahtarlar eklentideki Obf degerlerinin AYNISIDIR (tools/obf.py); eklentide
bir kaynagin domaini/anahtari degisirse buradaki SOURCES sabitleri de guncellenmeli.

Kullanim:
  harman_health.py                 # tum kaynaklar, sorun varsa Telegram
  harman_health.py --only wdt,dbx  # secili kaynaklar
  harman_health.py --always        # sorun olmasa da ozet gonder
  harman_health.py --no-notify     # yalniz konsol
  harman_health.py --telegram-test # bot/chat ayarini dogrula
  harman_health.py --telegram-chat-id  # bota yazan son sohbetlerin id'leri
"""
import argparse
import base64
import copy
import hashlib
import hmac
import html
import json
import os
import random
import re
import socket
import subprocess
import sys
import time
import traceback
import uuid
from pathlib import Path
from urllib.parse import quote, urljoin, urlsplit

import requests
from bs4 import BeautifulSoup
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

STATE_DIR = Path(os.environ.get("HARMAN_STATE_DIR", "/var/lib/harman-health"))
UA = "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Mobile Safari/537.36"
TIMEOUT = 20
DOH_URL = "https://cloudflare-dns.com/dns-query"
# Normal hatta basarisiz kaynak bir kez daha denenir; bu kosuda dogrudan baglanamayan her istek bu proxy
# (CT 123 vpngw, yalniz wg0'dan cikan SOCKS5) ile tekrarlanir. Tum kaynagi VPN'den kosmak olmaz: ornegin
# Dizipal'in sitesi yalniz TR'ye acik, video CDN'i ise TR'den engelli. Bos ise karsilastirma yapilmaz.
VPN_PROXY_DEFAULT = ""
VIA = None        # o anki kosunun yedek proxy'si (None = yalniz dogrudan)
VPN_USED = set()  # bu kosuda yalniz VPN ile ulasilabilen host'lar

# --- Obf (core/Obf.kt ile ayni anahtar) -------------------------------------------------
_KEY = bytes([0x3F, 0x5A, 0x11, 0x77, 0x2C, 0x64, 0x08, 0x19])


def obf(payload: str) -> str:
    data = base64.b64decode(payload)
    return bytes(b ^ _KEY[i % len(_KEY)] for i, b in enumerate(data)).decode()


class CheckError(Exception):
    """Beklenen (site kaynakli) test hatasi; mesaji rapora aynen gider."""


class DomainChanged(CheckError):
    pass


class Unreleased(CheckError):
    """Icerik henuz yayinlanmamis (site 'Yakinda' diyor); try_items deneme hakki harcamadan atlar."""


def host_of(url: str) -> str:
    return (urlsplit(url).hostname or "").lower()


def origin(url: str) -> str:
    u = urlsplit(url)
    return f"{u.scheme}://{u.netloc}"


def soup(text: str) -> BeautifulSoup:
    return BeautifulSoup(text, "html.parser")


def short(text, n=160) -> str:
    text = re.sub(r"\s+", " ", str(text)).strip()
    return text if len(text) <= n else text[: n - 1] + "…"


# --- Ag yardimcilari ----------------------------------------------------------------------
class Net:
    def __init__(self, fallback=None):
        self.s = requests.Session()
        self.s.headers["User-Agent"] = UA
        self.fallback = fallback

    def _req(self, method, url, **kw):
        kw.setdefault("timeout", TIMEOUT)
        try:
            return self.s.request(method, url, **kw)
        except (requests.ConnectionError, requests.Timeout):
            if not self.fallback:
                raise
        r = self.s.request(method, url, proxies={"http": self.fallback, "https": self.fallback}, **kw)
        VPN_USED.add(host_of(url))
        return r

    def get(self, url, **kw):
        return self._req("GET", url, **kw)

    def post(self, url, **kw):
        return self._req("POST", url, **kw)

    def ok(self, resp, what):
        if resp.status_code >= 400:
            raise CheckError(f"{what}: HTTP {resp.status_code} ({host_of(resp.url)})")
        return resp


def doh_resolve(host: str) -> list:
    ips = []
    for rtype in ("A", "AAAA"):
        try:
            r = requests.get(DOH_URL, params={"name": host, "type": rtype},
                             headers={"Accept": "application/dns-json"}, timeout=10)
            data = r.json()
            ips += [a["data"] for a in data.get("Answer", []) if a.get("type") in (1, 28)]
        except Exception:
            pass
    return ips


def tcp_ping(host: str, port=443, tries=3):
    """ICMP'yi Cloudflare arkasindaki siteler hep yanitlamiyor; TCP el sikisma suresi olculur."""
    best = None
    for _ in range(tries):
        t0 = time.monotonic()
        try:
            with socket.create_connection((host, port), timeout=5):
                ms = (time.monotonic() - t0) * 1000
                best = ms if best is None else min(best, ms)
        except OSError:
            pass
    if best is None and VIA:
        import socks  # python3-socks
        u = urlsplit(VIA)
        t0 = time.monotonic()
        try:
            with socks.create_connection((host, port), timeout=10, proxy_type=socks.SOCKS5,
                                         proxy_addr=u.hostname, proxy_port=u.port, proxy_rdns=True):
                best = (time.monotonic() - t0) * 1000
                VPN_USED.add(host)
        except OSError:
            pass
    return best


def icmp_ping(host: str):
    try:
        out = subprocess.run(["ping", "-c", "2", "-W", "2", host], capture_output=True, text=True, timeout=10).stdout
        m = re.search(r"= [\d.]+/([\d.]+)/", out)
        return float(m.group(1)) if m else None
    except Exception:
        return None


def domain_probe(net: Net, url: str, what: str):
    """Host'u DoH ile coz, ping'le, GET ile yonlendirmeleri izle. (final_url, detay) doner."""
    host = host_of(url)
    ips = doh_resolve(host)
    if not ips:
        raise DomainChanged(f"{host} DNS'te yok (DoH NXDOMAIN) — domain degismis/kapanmis olabilir")
    tcp = tcp_ping(host)
    if tcp is None:
        raise CheckError(f"{what}: {host} 443'e baglanilamiyor ({ips[0]})")
    icmp = icmp_ping(host)
    try:
        r = net.get(url, allow_redirects=True)
    except requests.RequestException as e:
        raise CheckError(f"{what}: {host} yanit vermiyor ({type(e).__name__})")
    net.ok(r, what)
    ping = f"tcp {tcp:.0f}ms" + (f", icmp {icmp:.0f}ms" if icmp is not None else "")
    return r, f"{host} → {host_of(r.url)} [{ping}, HTTP {r.status_code}]"


# --- HLS / video akis testi -------------------------------------------------------------
def probe_stream(net: Net, url: str, headers: dict, kind="m3u8", depth=0) -> str:
    """Oynaticinin yaptigi gibi playlist -> varyant -> ilk parca; parcadan ~256KB indirir."""
    h = {"User-Agent": UA, **headers}
    if kind in ("mp4", "video"):
        return _probe_bytes(net, url, h, "video")
    r = net.get(url, headers=h)
    net.ok(r, "playlist")
    text = r.text.lstrip("﻿").strip()
    if not text.startswith("#EXTM3U"):
        raise CheckError(f"playlist m3u8 degil: {short(text, 60)!r}")
    lines = [l.strip() for l in text.splitlines()]
    uris = [l for l in lines if l and not l.startswith("#")]
    if not uris:
        raise CheckError("playlist bos (parca/varyant yok)")
    if "#EXT-X-STREAM-INF" in text:
        if depth > 2:
            raise CheckError("playlist varyant dongusu")
        return probe_stream(net, urljoin(r.url, uris[0]), headers, kind, depth + 1)
    seg = urljoin(r.url, uris[0])
    return f"{len(uris)} parca, " + _probe_bytes(net, seg, h, "parca")


def _probe_bytes(net: Net, url: str, headers: dict, what: str) -> str:
    t0 = time.monotonic()
    with net.get(url, headers={**headers, "Range": "bytes=0-262143"}, stream=True) as r:
        net.ok(r, what)
        got = b""
        for chunk in r.iter_content(32768):
            got += chunk
            if len(got) >= 262144:
                break
    dt = max(time.monotonic() - t0, 1e-3)
    if not got:
        raise CheckError(f"{what} bos geldi")
    head = got[:64].lstrip().lower()
    if head.startswith(b"<!doctype") or head.startswith(b"<html"):
        raise CheckError(f"{what} yerine HTML geldi ({host_of(url)})")
    return f"{what} {len(got) // 1024}KB @ {len(got) / dt / 1024:.0f}KB/s ({host_of(url)})"


# --- Kaynaklar ------------------------------------------------------------------------------
class Source:
    id = ""
    name = ""
    dynamic_domain = False  # True: eklenti domain degisimini kendisi takip ediyor

    def __init__(self, net: Net, state: dict):
        self.net = net
        self.state = state  # kaynagin kalici durumu (bilinen host vb.)
        self.steps = []     # (adim, ok|warn|fail|skip, detay)
        self.info = []

    def step(self, name, status, detail=""):
        self.steps.append((name, status, detail))
        log(f"  [{status.upper():4}] {name}: {detail}")

    def note_host(self, key: str, new: str, label: str):
        old = self.state.get(key)
        if old and old != new:
            self.info.append(f"{label} degisti: {old} → {new} (eklenti otomatik takip ediyor)")
        self.state[key] = new

    def run(self):
        raise NotImplementedError

    def try_items(self, items, play, tries=3):
        """Rastgele icerikleri sirayla dene; ilk oynayani kabul et."""
        items = list(items)
        random.shuffle(items)
        errors, skipped = [], 0
        for item in items:
            if len(errors) >= tries:
                break
            try:
                return play(item)
            except Unreleased as e:
                skipped += 1
                log(f"    ~ {short(item_title(item), 40)}: {e} (atlandi)")
            except (CheckError, requests.RequestException) as e:
                errors.append(f"{short(item_title(item), 40)}: {e if isinstance(e, CheckError) else type(e).__name__}")
                log(f"    - {errors[-1]}")
        if not errors:
            raise CheckError(f"{skipped} icerigin hepsi yayinlanmamis (Yakinda); denenecek icerik yok")
        raise CheckError(f"{len(errors)} rastgele icerikte akis yok → " + " | ".join(errors))


def item_title(item):
    return item.get("title", "?") if isinstance(item, dict) else str(item)


# ---------------------------------------------------------------- Web Drama Turkey (wdt)
class WebDramaTurkey(Source):
    id, name = "wdt", "Web Drama Turkey"
    BASE = obf("Vy5lB19eJzZIP3MTXgVleEsvYxxJHTo3XDV8")

    @staticmethod
    def search_fallback(q):
        parts = [p.strip() for p in re.split(r"[^\w\s]+|_+", q) if p.strip()]
        return max(parts, key=len) if parts and parts != [q.strip()] else None

    def cards(self, doc):
        out = []
        for div in doc.select("div.list-movie"):
            a = div.select_one("a.list-media") or div.select_one("a.list-title")
            if not a or not a.get("href"):
                continue
            t = div.select_one("a.list-title")
            out.append({"title": (t.get_text(strip=True) if t else a.get("title", "")), "url": urljoin(self.BASE, a["href"])})
        return out

    def run(self):
        r, d = domain_probe(self.net, self.BASE, "domain")
        if host_of(r.url) != host_of(self.BASE):
            raise DomainChanged(f"{host_of(self.BASE)} → {host_of(r.url)} yonleniyor; eklentideki domain guncellenmeli")
        self.step("domain", "ok", d)

        path = random.choice(["diziler", "filmler"])
        doc = soup(self.net.ok(self.net.get(f"{self.BASE}/{path}?page=1"), "katalog").text)
        items = self.cards(doc)
        if not items:
            raise CheckError(f"katalog /{path}: div.list-movie kart yok (selector kirik?)")
        self.step("katalog", "ok", f"/{path}: {len(items)} kart")

        pick = random.choice(items)
        q = pick["title"][:40]
        res, note = self.cards(soup(self.net.ok(self.net.get(f"{self.BASE}/arama/{quote(q)}"), "arama").text)), ""
        fb = self.search_fallback(q)
        if not res and fb:  # WebDramaTurkeyParser.searchFallback: site sorgudaki noktalamayi atiyor, basliktakini degil
            res, note = self.cards(soup(self.net.ok(self.net.get(f"{self.BASE}/arama/{quote(fb)}"), "arama").text)), f" (yedek sorgu {fb!r})"
        self.step("arama", "ok" if res else "fail", f"{q!r} → {len(res)} sonuc{note}")

        self.step("akis", "ok", self.try_items(items, self.play))

    def play(self, item):
        url = item["url"]
        if "/film/" not in url:
            doc = soup(self.net.ok(self.net.get(url), "detay").text)
            eps = list(dict.fromkeys(urljoin(url, a["href"]) for a in doc.select("a[href*='-sezon/'][href*='-bolum']")))
            if not eps:
                # Katalogda 'Yakinda' diziler de listeleniyor: bolum listesi bos, eklenti de bos gosterir (hata degil)
                status = {a.get_text(strip=True): t.get_text(strip=True) for f in doc.select("div.featured-attr")
                          for a, t in [(f.select_one(".attr"), f.select_one(".text"))] if a and t}
                if "Yakında" in (status.get("Yayın durumu"), status.get("Çeviri durumu")):
                    raise Unreleased("detay: yayinlanmamis (Yakında), bolum yok")
                raise CheckError("detay: bolum linki yok")
            url = random.choice(eps)
        doc = soup(self.net.ok(self.net.get(url), "bolum").text)
        servers = [(b["data-embed"], short(b.select_one(".name").get_text() if b.select_one(".name") else "", 20))
                   for b in doc.select("button.btn-service.dropdown-source[data-embed]")]
        if not servers:
            raise CheckError("bolum kilitli (yayinlanmamis)" if doc.select_one("div.embed-lock") else "sunucu butonu yok (selector kirik?)")
        hosts = []
        for eid, sname in servers:
            emb = self.net.post(f"{self.BASE}/ajax/embed", data={"id": eid}, headers={"X-Requested-With": "XMLHttpRequest", "Referer": url}).text
            m = re.search(r'src="([^"]*video\.php[^"]*)"', emb)
            if not m:
                continue
            ifr = soup(self.net.get(m.group(1), headers={"Referer": self.BASE}).text).select_one("iframe#main-iframe")
            real = ifr.get("src") if ifr else None
            if not real:
                continue
            fire = re.match(r"^(https?://[^/]+)/video/([0-9a-fA-F]+)", real)
            if not fire:
                hosts.append(host_of(real))  # vk/ok/filemoon: CloudStream extractor'u cozer
                continue
            h, vid = fire.groups()
            j = self.net.post(f"{h}/player/index.php?data={vid}&do=getVideo", data={"hash": vid},
                              headers={"X-Requested-With": "XMLHttpRequest", "Referer": f"{h}/video/{vid}"}).text
            m3 = re.search(r'"securedLink":"([^"]+)"', j) or re.search(r'"videoSource":"([^"]+)"', j)
            if not m3:
                raise CheckError(f"FirePlayer getVideo link vermedi ({host_of(h)})")
            res = probe_stream(self.net, m3.group(1).replace("\\/", "/"), {"Referer": f"{h}/"})
            return f"{short(item['title'], 40)} [{sname or 'FirePlayer'}] {res}"
        raise CheckError(f"FirePlayer sunucusu yok ({len(servers)} sunucu; digerleri: {', '.join(sorted(set(hosts))) or '-'})")


# ---------------------------------------------------------------- Dizipal (dp) — PASIF, SOURCES'ta yok
class Dizipal(Source):
    id, name = "dp", "Dizipal"
    dynamic_domain = True
    ENTRY = obf("Vy5lB19eJzZbM2seXAVkN1Y3")

    UNINDEXED = {"about", "are", "com", "for", "from", "how", "that", "the", "this", "was",
                 "what", "when", "where", "who", "will", "with", "und", "www"}

    @classmethod
    def search_fallback(cls, q):
        words = [w for w in re.split(r"[\W_]+", q) if w]
        kept = [w for w in words if len(w) >= 3 and w.lower() not in cls.UNINDEXED]
        return " ".join(kept) if kept and kept != words else None

    def cards(self, doc, base):
        out = []
        for it in doc.select(".post-item"):
            a = it.select_one("a[href]")
            if a:
                t = (a.get("title") or a.get_text()).strip()
                if t:
                    out.append({"title": t, "url": urljoin(base, a["href"])})
        return list({c["url"]: c for c in out}.values())

    def run(self):
        r, d = domain_probe(self.net, self.ENTRY, "domain")
        self.base = origin(r.url)
        self.note_host("host", host_of(self.base), "Guncel adres")
        self.step("domain", "ok", d)

        path = random.choice(["diziler", "filmler"])
        rr = self.net.ok(self.net.get(f"{self.base}/{path}/"), "katalog")
        items = self.cards(soup(rr.text), rr.url)
        if not items:
            raise CheckError(f"katalog /{path}/: .post-item kart yok (selector kirik?)")
        self.step("katalog", "ok", f"/{path}/: {len(items)} kart")

        q = random.choice(items)["title"][:40]
        rr = self.net.ok(self.net.get(f"{self.base}/?s={quote(q)}"), "arama")
        res, note = self.cards(soup(rr.text), rr.url), ""
        fb = self.search_fallback(q)
        if not res and fb:  # DizipalParser.searchFallback: yeni yazilarin indeksinde stopword/kisa kelime yok
            rr = self.net.ok(self.net.get(f"{self.base}/?s={quote(fb)}"), "arama")
            res, note = self.cards(soup(rr.text), rr.url), f" (yedek sorgu {fb!r})"
        self.step("arama", "ok" if res else "fail", f"{q!r} → {len(res)} sonuc{note}")

        self.step("akis", "ok", self.try_items(items, self.play))

    def play(self, item):
        rr = self.net.ok(self.net.get(item["url"]), "detay")
        doc, page = soup(rr.text), rr.url
        eps = [urljoin(page, it.select_one("a[href]")["href"]) for it in doc.select(".episode-item") if it.select_one("a[href]")]
        eps = [e for e in eps if re.search(r"-(\d+)-sezon-(\d+)-bolum(?:-|/|$)", e)]
        if eps:
            rr = self.net.ok(self.net.get(random.choice(eps)), "bolum")
            doc, page = soup(rr.text), rr.url
        elif "/dizi/" in page or "/anime/" in page:
            raise CheckError("dizi sayfasinda .episode-item yok (selector kirik?)")
        embeds = list(dict.fromkeys(
            urljoin(page, f.get("data-src") or f.get("src") or "")
            for f in doc.select(".video-player-area iframe, .responsive-player iframe") if (f.get("data-src") or f.get("src"))))
        if not embeds:
            raise CheckError("oynatici iframe'i yok (selector kirik?)")
        for emb in embeds:
            p = self.net.get(emb, headers={"Referer": page})
            if p.status_code >= 400:
                continue
            m = re.search(r"""fetch\(\s*["']([^"']*\bop=get_stream\b[^"']*)["']\s*\)""", p.text)
            if not m:
                continue
            endpoint, o = urljoin(p.url, m.group(1)), origin(p.url)
            s = self.net.get(endpoint, headers={"Referer": p.url, "Accept": "*/*", "Origin": o, "Sec-Fetch-Dest": "empty",
                                                "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "same-origin"})
            if s.status_code >= 400:
                raise CheckError(f"get_stream HTTP {s.status_code}")
            url = (s.json() or {}).get("url")
            if not url:
                raise CheckError(f"get_stream url vermedi: {short(s.text, 80)}")
            return f"{short(item['title'], 40)} " + probe_stream(self.net, urljoin(p.url, url), {"Referer": f"{o}/"})
        raise CheckError(f"yerel oynatici (get_stream) yok; embed'ler: {', '.join(host_of(e) for e in embeds)}")


# ---------------------------------------------------------------- Dizibox (dbx)
def cryptojs_decrypt(ct: str, passphrase: str):
    """CryptoJS passphrase modu: "Salted__" + EVP_BytesToKey(MD5), AES-256-CBC (DiziboxParser.cryptoJsDecrypt)."""
    from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
    raw = base64.b64decode(ct)
    if raw[:8] != b"Salted__":
        return None
    salt, key, prev = raw[8:16], b"", b""
    while len(key) < 48:
        prev = hashlib.md5(prev + passphrase.encode() + salt).digest()
        key += prev
    dec = Cipher(algorithms.AES(key[:32]), modes.CBC(key[32:48])).decryptor()
    out = dec.update(raw[16:]) + dec.finalize()
    return out[:-out[-1]].decode("utf-8", "replace")


class Dizibox(Source):
    id, name = "dbx", "Dizibox"
    dynamic_domain = True
    ENTRY = obf("Vy5lB19eJzZILWZZSA1ycF01aVlADX58")
    # Eklentiyle ayni: masaustu UA + dbxu cerezi (yoksa arama/arsiv Cloudflare 520 verir).
    UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128 Safari/537.36"
    ROWS = ["dizi-arsivi/", "efsane-diziler/", "dizi-arsivi/?imdb=7", "dizi-arsivi/?tur%5B0%5D=aksiyon"]

    def cards(self, doc, base):
        out = []
        for art in doc.select("article.detailed-article, article.article-series-poster"):
            a = art.select_one("h3 a[href], a.poster-title[href]")
            if a and "/diziler/" in a["href"]:
                t = a.get_text(strip=True) or a.get("title", "").strip()
                if t:
                    out.append({"title": t, "url": urljoin(base, a["href"])})
        return list({c["url"]: c for c in out}.values())

    @staticmethod
    def unwrap(text):
        out, layer = text, text
        for _ in range(3):
            dec = [cryptojs_decrypt(c, p) for c, p in re.findall(r'CryptoJS\.AES\.decrypt\(\s*"([^"]+)"\s*,\s*"([^"]+)"\s*\)', layer)]
            dec += [base64.b64decode(requests.utils.unquote(x)).decode("utf-8", "replace")
                    for x in re.findall(r"""atob\(\s*unescape\(\s*["']([^"']+)["']\s*\)\s*\)""", layer)]
            dec = [d for d in dec if d]
            if not dec:
                break
            layer = "\n".join(dec)
            out += "\n" + layer
        return out

    @staticmethod
    def player_file(text):
        files = [f for f in re.findall(r"""\bfile\s*:\s*["']([^"']+)["']""", text)
                 if f.startswith("http") and not re.search(r"\.(jpe?g|png|webp|vtt|srt)(\?|$)", f)]
        return next((f for f in files if ".m3u8" in f), files[0] if files else None)

    def run(self):
        self.net.s.headers["User-Agent"] = self.UA
        self.net.s.cookies.set("dbxu", "1744054959089")
        r, d = domain_probe(self.net, f"{self.ENTRY}/robots.txt", "domain")
        self.base = origin(r.url)
        self.note_host("host", host_of(self.base), "Guncel adres")
        self.step("domain", "ok", d)

        row = random.choice(self.ROWS)
        path, _, query = row.partition("?")
        rr = self.net.ok(self.net.get(f"{self.base}/{path}" + (f"?{query}" if query else "")), "katalog")
        items = self.cards(soup(rr.text), rr.url)
        if not items:
            raise CheckError(f"katalog /{row}: article.detailed-article kart yok (selector kirik?)")
        self.step("katalog", "ok", f"/{row}: {len(items)} kart")

        q = random.choice(items)["title"][:40]
        rr = self.net.ok(self.net.get(f"{self.base}/?s={quote(q)}"), "arama")
        res = self.cards(soup(rr.text), rr.url)
        self.step("arama", "ok" if res else "fail", f"{q!r} → {len(res)} sonuc")

        self.step("akis", "ok", self.try_items(items, self.play))

    def resolve(self, url, referer, depth=0):
        """(m3u8, referer) ya da None. vidmoly/ok.ru CloudStream extractor'una da gider; burada dogrudan
        jwplayer file'i aranir (eklentinin yedek yolu)."""
        if depth > 3 or "ok.ru" in host_of(url):
            return None
        p = self.net.get(url, headers={"Referer": referer})
        if p.status_code >= 400:
            return None
        text = self.unwrap(p.text)
        f = self.player_file(text)
        if f:
            return f, origin(p.url) + "/"
        for fr in soup(text).select("iframe[src]"):
            got = self.resolve(urljoin(p.url, fr["src"]), p.url, depth + 1)
            if got:
                return got
        return None

    def play(self, item):
        rr = self.net.ok(self.net.get(item["url"]), "detay")
        doc = soup(rr.text)
        eps = [urljoin(rr.url, a["href"]) for a in doc.select("article.grid-box a.season-episode[href]")]
        if not eps:
            raise CheckError("dizi sayfasinda article.grid-box bolum yok (selector kirik?)")
        rr = self.net.ok(self.net.get(random.choice(eps)), "bolum")
        doc, page = soup(rr.text), rr.url
        mirrors = [(o.get_text(strip=True), urljoin(page, o.get("value") or o.get("href") or page))
                   for o in doc.select("select.woca-linkpages-dd option")] or [("Dizibox", page)]
        tried = []
        for name, murl in mirrors:
            mdoc = doc if murl == page else soup(self.net.get(murl, headers={"Referer": page}).text)
            for fr in mdoc.select("#video-area iframe"):
                src = fr.get("data-src") or fr.get("src")
                if not src:
                    continue
                got = self.resolve(urljoin(murl, src), murl)
                tried.append(f"{name}:{'ok' if got else '-'}")
                if got:
                    return f"{short(item['title'], 40)} [{name}] " + probe_stream(self.net, got[0], {"Referer": got[1], "User-Agent": self.UA})
        if not tried:
            raise CheckError("oynatici iframe'i (#video-area) yok (selector kirik?)")
        raise CheckError(f"hicbir sunucu akis vermedi ({', '.join(tried)})")


# ---------------------------------------------------------------- HDFilmCehennemi (hdf)
def hdf_decode_stream(parts, host: str = "", decoder=None):
    """HdfilmCehennemiParser.decodeStream'in birebir portu (parts: bolunmus payload, decoder: JS cozucu govdesi)."""
    # Eski closeplayer seed'e oynatici hostname'ini ekliyordu; once hostlu, olmazsa hostsuz dene.
    return (host and _hdf_decode(parts, host, decoder or "")) or _hdf_decode(parts, "", decoder or "")


def hdf_function_body(scripts: str, name: str):
    """HdfilmCehennemiParser.functionBody portu."""
    m = re.search(r"(?:function\s+%s|\b%s\s*=\s*function)\s*\(\w*\)\s*\{" % (re.escape(name), re.escape(name)), scripts)
    if not m:
        return None
    depth, i = 1, m.end()
    while i < len(scripts) and depth:
        depth += {"{": 1, "}": -1}.get(scripts[i], 0)
        i += 1
    return scripts[m.end():i]


def _hdf_decode(parts, host: str, body: str):
    # Site cozucunun sabitlerini (carpanlar, modlar, islem harfleri) ve bicimini (seed/islemler payload'da
    # ya da fonksiyon icinde sabit) surekli degistiriyor; hepsi JS govdesinden okunur, yoksa ilk bicim varsayilir.
    try:
        parts = list(parts)

        def nums(rx, *default):
            m = re.search(rx, body)
            return [int(g) if g else 1 for g in m.groups()] if m else list(default)
        hm = re.search(r"(\w+)=(\w+)\.charCodeAt\((\w+)\);(\w+)=\(\4\*(\d+)\+\1\)%(\d+);(\w+)=\(([^;]*)\)&255", body)
        lits = dict(re.findall(r"""\b(\w+)=["']([^"']*)["']""", body))
        om = re.search(r"=(\w+)\.charAt\(", body)
        if hm and om and hm.group(2) in lits and om.group(1) in lits:
            seed, ops = lits[hm.group(2)], lits[om.group(1)]
        else:
            m1, b2, m2 = nums(r"=\w+\.length-2,\w+=\w+%(\d+),\w+=(\d+)\+\(\w+%(\d+)\)", 7, 8, 5)
            count = len(parts) - 2
            if count < b2:
                return None
            ops = parts.pop(b2 + count % m2)
            seed = parts.pop(count % m1) + host
        text = "".join(parts)
        hmul, hmod, expr = (int(hm.group(5)), int(hm.group(6)), hm.group(8)) if hm else (37, 241, "<<1")
        sh = re.search(r"<<(\d+)", expr)
        hsh = sm = 0
        for i, c in enumerate(seed):
            hsh = (hsh * hmul + ord(c)) % hmod
            sm = (sm + ((ord(c) << int(sh.group(1))) ^ i)) & 255 if sh else (sm ^ (ord(c) + i)) & 255
        env = {hm.group(4): hsh, hm.group(7): sm} if hm else {"h": hsh, "s": sm}
        im = re.search(r"=\((\w+)(?:\*(\d+))?\+(\w+)\)%256,\w+=\((\w+)%(\d+)\)\+(\d+),\w+=\(\((\w+)\*(\d+)\+(\w+)\)%(\d+)\)\+1", body)
        a, am, b, c_, cm, ca, d, dm, e, emod = im.groups() if im else ("h", "3", "s", "s", "11", "5", "s", "251", "h", "65519")
        state = (env[a] * int(am or 1) + env[b]) % 256
        step = env[c_] % int(cm) + int(ca)
        shuffle = (env[d] * int(dm) + env[e]) % int(emod) + 1
        m = re.search(r"""===["'](.)["']\)\{\w+=atob\(""", body)
        b64 = m.group(1) if m else "7"
        m = re.search(r"""===["'](.)["']\)\{\w+=\w+\.split\(''\)\.reverse""", body)
        rev = m.group(1) if m else "3"
        base, = nums(r"charCodeAt\(0\)-(\d+)\)%26", 96)
        smul, sadd, smod = nums(r"=\(\w+\*(\d+)\+(\d+)\)%(\d+);\w+\[\w+\]=", 97, 41, 65519)
        xmul, = nums(r"=\(\w+(?:\*(\d+))?\+\w+\)%256;\w+\+=String\.fromCharCode", 5)
        for op in reversed(ops):
            if op == b64:
                t = text.replace("-", "+").replace("_", "/")
                text = base64.b64decode(t + "=" * (-len(t) % 4)).decode("latin-1")
            elif op == rev:
                text = text[::-1]
            elif "a" <= op <= "z" or "A" <= op <= "Z":
                shift = (26 - (ord(op) - base) % 26) % 26
                text = "".join(chr((ord(c) - s + shift) % 26 + s) if (s := 65 if "A" <= c <= "Z" else 97 if "a" <= c <= "z" else -1) >= 0 else c for c in text)
            else:
                return None
        chars = list(text)
        swaps = [0] * len(chars)
        for i in range(len(chars) - 1, 0, -1):
            shuffle = (shuffle * smul + sadd) % smod
            swaps[i] = shuffle % (i + 1)
        for i in range(1, len(chars)):
            j = swaps[i]
            chars[i], chars[j] = chars[j], chars[i]
        out = []
        for c in chars:
            state = (state * xmul + step) % 256
            out.append(chr(ord(c) ^ state))
            state = (state + ord(c)) % 256
        res = "".join(out)
        return res if res.startswith(("https://", "http://")) else None
    except Exception:
        return None


def hdf_unpack(script: str) -> str:
    """HdfilmCehennemiParser.unpack portu: Dean Edwards packer bloklarini JS calistirmadan acar."""
    out = []
    for m in re.finditer(r"""\}\('((?:[^'\\]|\\.)*)',\s*(\d+),\s*(\d+),\s*'((?:[^'\\]|\\.)*)'\.split\('\|'\)""", script):
        radix, count, words = int(m.group(2)), int(m.group(3)), m.group(4).split("|")

        def enc(n):
            d = n % radix
            return ("" if n < radix else enc(n // radix)) + (chr(d + 29) if d > 35 else "0123456789abcdefghijklmnopqrstuvwxyz"[d])
        table = {enc(i): (words[i] if i < len(words) and words[i] else enc(i)) for i in range(count)}
        body = m.group(1).replace("\\'", "'").replace("\\\\", "\\")
        out.append(re.sub(r"\b\w+\b", lambda w: table.get(w.group(0), w.group(0)), body, flags=re.A))
    return "\n".join(out)


class HdfilmCehennemi(Source):
    id, name = "hdf", "HDFilmCehennemi"
    BASE = obf("Vy5lB19eJzZXO2MaTQolcVo7fQNESm5wUXdzEk4LeDdLKT8ZSRAncVs8PkAaU2ssW2ojREkFbHsLOyRGGFZuLA9tJg==")
    FETCH = {"X-Requested-With": "fetch", "Content-Type": "application/json"}

    @staticmethod
    def search_fallback(q):
        parts = [p.strip() for p in re.split(r"['’‘`´]+", q) if p.strip()]
        return max(parts, key=len) if parts and parts != [q.strip()] else None

    def search(self, q):
        rr = self.net.ok(self.net.get(f"{self.BASE}/search?q={quote(q)}", headers=self.FETCH), "arama")
        return self.cards(soup("\n".join(rr.json().get("results", []))))

    def cards(self, doc):
        out = []
        for a in doc.select("a.poster, a.search-result"):
            if not a.get("href"):
                continue
            t = a.get("title") or (a.select_one(".poster-title, .title").get_text() if a.select_one(".poster-title, .title") else "")
            if t.strip():
                out.append({"title": t.strip(), "url": urljoin(self.BASE, a["href"])})
        return list({c["url"]: c for c in out}.values())

    def run(self):
        r, d = domain_probe(self.net, self.BASE, "domain")
        if host_of(r.url) != host_of(self.BASE):
            raise DomainChanged(f"{host_of(self.BASE)} → {host_of(r.url)} yonleniyor; eklentideki domain guncellenmeli")
        self.step("domain", "ok", d)

        typ, lang = random.choice(["1", "2"]), random.choice(["tr", "en"])
        body = {"type": typ, "lang": json.dumps([lang, "dual"]), "genres": "[]", "years": "", "imdb": "",
                "order": "posts.imdb desc", "page": "1"}
        rr = self.net.ok(self.net.post(f"{self.BASE}/film-robotu-1/", data=json.dumps(body),
                                       headers={"Content-Type": "application/json", "X-Requested-With": "fetch",
                                                "X-Mofycore-Action": "discover", "Referer": f"{self.BASE}/film-robotu-1/"}), "katalog")
        items = self.cards(soup(rr.json().get("html", "")))
        label = ("film" if typ == "1" else "dizi") + "/" + lang
        if not items:
            raise CheckError(f"katalog (film-robotu {label}): kart yok (API/selector kirik?)")
        self.step("katalog", "ok", f"{label}: {len(items)} kart")

        q = random.choice(items)["title"][:40]
        res, note = self.search(q), ""
        fb = self.search_fallback(q)
        if not res and fb:  # HdfilmCehennemiParser.searchFallback: site kesme isaretli sorguda 0 sonuc donuyor
            res, note = self.search(fb), f" (yedek sorgu {fb!r})"
        self.step("arama", "ok" if res else "fail", f"{q!r} → {len(res)} sonuc{note}")

        self.step("akis", "ok", self.try_items(items, self.play))

    def play(self, item):
        rr = self.net.ok(self.net.get(item["url"]), "detay")
        doc, page = soup(rr.text), rr.url
        if urlsplit(page).path.startswith("/dizi/"):
            eps = [urljoin(page, a["href"]) for a in doc.select(".seasons-tab-content a[href]")
                   if re.search(r"/sezon-(\d+)/bolum-(\d+)(?:[-/]|$)", urljoin(page, a["href"]))]
            if not eps:
                raise CheckError("dizi sayfasinda bolum yok (selector kirik?)")
            rr = self.net.ok(self.net.get(random.choice(eps)), "bolum")
            doc, page = soup(rr.text), rr.url
        embeds = [urljoin(page, f.get("data-src") or f.get("src")) for f in doc.select(".video-container iframe") if (f.get("data-src") or f.get("src"))]
        for b in doc.select(".alternative-links[data-lang] button[data-video]"):
            if not re.fullmatch(r"\d+", b.get("data-video", "")):
                continue
            v = self.net.get(f"{self.BASE}/video/{b['data-video']}/", headers={**self.FETCH, "Referer": page})
            try:
                ifr = soup(v.json()["data"]["html"]).select_one("iframe")
                if ifr:
                    embeds.append(urljoin(page, ifr.get("data-src") or ifr.get("src")))
            except Exception:
                pass
        embeds = list(dict.fromkeys(embeds))
        if not embeds:
            raise CheckError("oynatici iframe'i yok (selector kirik?)")
        for emb in embeds:
            p = self.net.get(emb, headers={"Referer": page})
            if p.status_code >= 400:
                continue
            scripts = "\n".join(s.get_text() for s in soup(p.text).select("script"))
            # Rapidrame (/rplayer/): ayni kodlayici packer icinde; yorum satirindaki sahte source atlanir.
            scripts = re.sub(r"(?m)^\s*//.*$", "", scripts + "\n" + hdf_unpack(scripts))
            stream = None
            m = re.search(r"""sources\s*:\s*\[\s*\{\s*file\s*:\s*["']([^"']+)["']""", scripts)
            if m:
                stream = urljoin(p.url, m.group(1).replace("\\/", "/"))
            else:
                # file: ya bir degisken (var x = coz(...)) ya da satir ici (function(){...return coz(...)})().
                call = r"""(\w+)\(\s*(?:["']([^"']+)["']\.split\(["']([^"']+)["']\)|\[([^\]]*)\])\s*\)"""
                var = re.search(r"""sources\s*:\s*\[\s*\{\s*file\s*:\s*(\(\s*function\b|\w+)""", scripts)
                if var:
                    if var.group(1).startswith("("):
                        a = re.compile(r"\breturn\s+" + call).search(scripts, var.end())
                    else:
                        a = re.search(r"\b" + re.escape(var.group(1)) + r"\s*=\s*" + call, scripts)
                    if a:
                        parts = a.group(2).split(a.group(3)) if a.group(2) else re.findall(r"""["']([^"']*)["']""", a.group(4))
                        stream = hdf_decode_stream(parts, host_of(p.url), hdf_function_body(scripts, a.group(1)))
                        if not stream:
                            raise CheckError(f"oynatici sifresi cozulemedi ({host_of(p.url)}) — decodeStream guncellenmeli")
            if stream:
                return f"{short(item['title'], 40)} " + probe_stream(self.net, stream, {"Referer": origin(p.url) + "/"})
        raise CheckError(f"oynaticida stream yok; embed'ler: {', '.join(host_of(e) for e in embeds)}")


# ---------------------------------------------------------------- Selcuk Sports (ss)
class SelcukSports(Source):
    id, name = "ss", "Selçuk Sports"
    dynamic_domain = True
    ENTRY = obf("Vy5lB19eJzZMP30UWQ97aVAoZQREACZwTA==")
    BRAND = obf("TD99FFkPe2lQKGUE")
    FALLBACK = obf("Vy5lB19eJzZILWZZXwFkekoxYgdDFnxqVz5zExRVO3tbaiERAhxxYw==")
    CONFIG_KEY = obf("Cj4jRBoAOCgLPigWFVBrfwo+KRUdXDorDGwjQRhRMHsMaidCSFM/KQk5chQbBmoh")
    SOCIAL = {"twitter.com", "x.com", "t.me", "telegram.me", "telegram.org", "facebook.com", "instagram.com",
              "youtube.com", "youtu.be", "wa.me", "whatsapp.com"}
    WASM = ("tiktokcdn.com", "tiktokcdn-eu.com", "ibyteimg.com")

    def mirrors(self, doc):
        eh = host_of(self.ENTRY).removeprefix("www.")
        anchors = doc.select("a.site-button[href]") or doc.select("a[href]")
        out = []
        for a in anchors:
            href = a["href"].strip()
            h = host_of(href).removeprefix("www.")
            if not h or urlsplit(href).scheme not in ("http", "https"):
                continue
            if h == eh or h.endswith("." + eh) or eh.endswith("." + h):
                continue
            if any(h == s or h.endswith("." + s) for s in self.SOCIAL):
                continue
            img = a.select_one("img")
            primary = bool(img and (img.get("alt") or "").strip().lower().startswith("site"))
            out.append((self.BRAND in h, primary, origin(href)))
        out.sort(key=lambda t: (not t[0], not t[1]))
        return list(dict.fromkeys(t[2] for t in out))

    def channels(self, doc):
        tab = next((a["href"][1:] for a in doc.select("a[href^='#']") if "7/24" in a.get_text()), None)
        rows = doc.select(f"[id='{tab}'] li a[data-url]") if tab else []
        if not rows:
            rows = [a for a in doc.select("li a[data-url]") if a.select_one("time") and "7/24" in a.select_one("time").get_text()]
        out = {}
        for a in rows:
            raw = a["data-url"].strip()
            if not raw.lower().startswith("http"):
                continue
            player = raw.split("#")[0]
            m = re.search(r"[?&]id=([^&]+)", player)
            if m:
                n = a.select_one(".name")
                out.setdefault(m.group(1), {"id": m.group(1), "title": n.get_text(strip=True) if n else m.group(1), "url": player})
        return list(out.values())

    def run(self):
        r, d = domain_probe(self.net, self.ENTRY, "domain")
        if host_of(r.url).removeprefix("www.") != host_of(self.ENTRY).removeprefix("www."):
            raise DomainChanged(f"giris sayfasi {host_of(self.ENTRY)} → {host_of(r.url)} yonleniyor; eklentideki landing guncellenmeli")
        cands = self.mirrors(soup(r.text))
        self.step("domain", "ok", f"{d}; {len(cands)} ayna adayi")
        if not cands:
            self.info.append("Landing'de ayna adayi bulunamadi; gomulu yedek ayna deneniyor")
        chans, tried = [], []
        for c in (cands + [self.FALLBACK])[:6]:
            try:
                rr = self.net.get(c + "/", timeout=20)
                chans = self.channels(soup(rr.text)) if rr.status_code < 400 else []
                tried.append(f"{host_of(c)}:{rr.status_code}/{len(chans)}")
            except requests.RequestException as e:
                tried.append(f"{host_of(c)}:{type(e).__name__}")
            if chans:
                self.mirror = c
                break
        if not chans:
            raise CheckError("hicbir aynada 7/24 TV sekmesi yok → " + ", ".join(tried))
        self.note_host("mirror", host_of(self.mirror), "Calisan ayna")
        self.step("katalog", "ok", f"{host_of(self.mirror)}: 7/24 {len(chans)} kanal")
        self.step("akis", "ok", self.try_items(chans, self.play, tries=4))

    @staticmethod
    def pb_fields(b):
        """Protobuf mesajinin uzunluk-onekli alanlari: {alan_no: [bytes, ...]}."""
        out, p = {}, 0
        def varint():
            nonlocal p
            r = s = 0
            while True:
                x = b[p]; p += 1; r |= (x & 0x7F) << s; s += 7
                if x < 0x80:
                    return r
        while p < len(b):
            tag = varint(); w = tag & 7
            if w == 0:
                varint()
            elif w == 1:
                p += 8
            elif w == 2:
                n = varint(); out.setdefault(tag >> 3, []).append(b[p:p + n]); p += n
            elif w == 5:
                p += 4
            else:
                raise ValueError("wire type")
        return out

    def config_url(self, env, cid):
        """api/config zarfi: 1=nonce, 2=govde; govde[i] ^ key ^ nonce ^ ((i*31+7)&255) → 1{1:baseUrl,3:suffix}."""
        try:
            f = self.pb_fields(env)
            nonce, body, k = f[1][0], f[2][0], self.CONFIG_KEY.encode()
            plain = bytes(c ^ k[i % len(k)] ^ nonce[i % len(nonce)] ^ ((i * 31 + 7) & 255) for i, c in enumerate(body))
            st = self.pb_fields(self.pb_fields(plain)[1][0])
            base = st[1][0].decode().strip()
            suffix = (st.get(3) or [b"/playlist.m3u8"])[0].decode().strip() or "/playlist.m3u8"
        except (KeyError, IndexError, ValueError, UnicodeDecodeError):
            return None
        return base + cid.strip("/") + suffix if base.startswith("http") else None

    def play(self, ch):
        p = self.net.get(ch["url"], headers={"Referer": self.mirror + "/"}, timeout=15)
        if p.status_code >= 400:
            raise CheckError(f"oynatici HTTP {p.status_code}")
        base = re.search(r"""baseStreamUrl\s*=\s*["']([^"']+)["']""", p.text)
        po = origin(p.url)
        priv = re.search(r"privateStream\s*=\s*(\d+)", p.text)
        if not base or not base.group(1).startswith("http"):
            # Yeni oynatici: taban sifreli ./api/config yanitinda (SelcukSportsParser.configStreams)
            c = self.net.get(po + "/api/config", headers={"Referer": p.url, "X-Player-Config": "1"}, timeout=15)
            if c.status_code >= 400:
                raise CheckError(f"oynaticida baseStreamUrl yok, api/config HTTP {c.status_code} (JS degismis?)")
            u = self.config_url(c.content, ch["id"])
            if not u:
                raise CheckError("api/config cozulemedi — oynatici JS'indeki config anahtari/bicimi degismis olabilir")
            urls = [u]
        elif priv and int(priv.group(1)) != 0:
            urls = [base.group(1).strip()]
        else:
            ov = re.search(r"""if\s*\(\s*true\s*\)\s*\{\s*streamId\s*=\s*["']([^"']+)["']""", p.text)
            ids = list(dict.fromkeys(x for x in [ov.group(1) if ov else None, ch["id"]] if x))
            urls = [base.group(1).strip().rstrip("/") + "/" + i.strip("/") + "/playlist.m3u8" for i in ids]
        errs = []
        for u in urls:
            pl = self.net.get(u, headers={"Referer": po + "/"}, timeout=15)
            segs = [l.strip() for l in pl.text.splitlines() if l.strip().lower().startswith("http")]
            if pl.status_code >= 400 or not segs:
                errs.append(f"playlist HTTP {pl.status_code}, {len(segs)} parca")
                continue
            if any(host_of(s) == w or host_of(s).endswith("." + w) for s in segs for w in self.WASM):
                errs.append("PNG/WASM kilifli yayin")
                continue
            return f"{ch['title']} " + probe_stream(self.net, u, {"Referer": po + "/"})
        raise CheckError("; ".join(errs) or "yayin adresi yok")


# ---------------------------------------------------------------- Rectv (rec)
class Rectv(Source):
    id, name = "rec", "Rectv"
    dynamic_domain = True
    FALLBACK = [obf("Vy5lB19eJzZSdGEFSQd8bwhoPxtDCA=="), obf("Vy5lB19eJzZedGEFSQd8bwhqPxtDCA==")]
    SUFFIX = obf("CxwkNhUnO10GGylBaiU9LXobUjJoIEwvDG8gTxlLaypcb3MTHVMlfAxtc1oYBjEtEjsoQxhJMHgMbClPTVc4LQpoPg==")
    SIGN = obf("DG8hTxpVOSgMYilFGlM9KFk+d0AbBm14Xmx3Th8BaiAMPHVFGwE+eAo7chUVVTh8CDtwEx5WPi8KbyBESAA+fA==")
    STREAM_KEY = obf("ZTdCNGMuO1FedWEvbgtZUW4DKE5eLjFqeRZwMEUiaWFeCEsVQlJwIFgJJUo=")
    CONFIG_URL = obf("Vy5lB19eJzZZM2MSTgV7fE0/fBhYAWt2UTx4EAIDZ3ZYNnQWXA17N1w1fFhaVSdpTTV7Ek8QezYIYyBCFFc4Kg5oJk4DCml0WilhFk8BezZZM2MSTgV7fAU8dANPDA==")
    CONFIG_KEY = obf("fhNrFn8dSntXKmswFCFrdlcvKA5tFm5acG9lMR1XSkhzMns7TQxr")
    APP_ID = obf("DmAmTh1RMCoPaSBFG10yeFE+YxhFADIrC25yREhROC5eOCNOFQJreF05IUZN")
    MEDIA = {"User-Agent": "SSUserAgent"}

    def __init__(self, *a):
        super().__init__(*a)
        self.client_id = str(uuid.uuid4())
        self.device_id = hashlib.sha256(self.client_id.encode()).hexdigest()

    def remote_bases(self):
        body = {"appId": self.APP_ID, "appInstanceId": "c" + self.client_id.replace("-", "")[:21], "appVersion": "22.0.0",
                "appBuild": "159", "packageName": "com.rectv.shot", "languageCode": "tr-TR", "countryCode": "TR",
                "platformVersion": "35", "sdkVersion": "22.1.1"}
        r = self.net.post(self.CONFIG_URL, json=body, headers={"X-Goog-Api-Key": self.CONFIG_KEY, "Accept": "application/json"}, timeout=10)
        self.net.ok(r, "uzak config")
        e = r.json().get("entries", {})
        out = []
        for k in ("api_url_son", "api_url", "api_url_1"):
            v = (e.get(k) or "").strip()
            if v.startswith("https://") and host_of(v):
                out.append("https://" + host_of(v))
        return list(dict.fromkeys(out))

    def api(self, endpoint, form=None):
        path = f"/api/{endpoint}/{self.SUFFIX}"
        method = "POST" if form is not None else "GET"
        body = (form or "").encode()
        errs = []
        for base in [b for b in [getattr(self, "base", None)] if b] + [b for b in self.bases if b != getattr(self, "base", None)]:
            ts, nonce = str(int(time.time())), str(uuid.uuid4())
            canon = "\n".join([method, path, ts, nonce, hashlib.sha256(body).hexdigest()])
            h = {**self.MEDIA, "X-App-Version": "159", "X-Client-Id": self.client_id, "X-Timestamp": ts, "X-Nonce": nonce,
                 "X-Signature": hmac.new(self.SIGN.encode(), canon.encode(), hashlib.sha256).hexdigest(),
                 "Content-Type": "application/x-www-form-urlencoded"}
            try:
                r = (self.net.post(base + path, data=body, headers=h, timeout=12) if form is not None
                     else self.net.get(base + path, headers=h, timeout=12))
                node = r.json() if r.status_code < 400 else None
                if isinstance(node, (list, dict)) and not (isinstance(node, dict) and "error" in node):
                    self.base = base
                    return node
                errs.append(f"{host_of(base)}:HTTP {r.status_code}")
            except (requests.RequestException, ValueError) as e:
                errs.append(f"{host_of(base)}:{type(e).__name__}")
        raise CheckError(f"API {endpoint.split('/')[0]} yanitsiz → {', '.join(errs)}")

    def stream_url(self, src):
        u = (src.get("url") or "").strip()
        if u.startswith("http"):
            return u
        enc = src.get("enc_url")
        if enc:
            raw = base64.b64decode(enc + "=" * (-len(enc) % 4))
            if len(raw) > 28:
                try:
                    out = AESGCM(base64.b64decode(self.STREAM_KEY)).decrypt(raw[:12], raw[12:], None).decode()
                    return out if out.startswith("http") else None
                except Exception:
                    raise CheckError("enc_url AES-GCM cozulemedi — yayin anahtari degismis olabilir")
        return None

    def run(self):
        try:
            remote = self.remote_bases()
        except (CheckError, requests.RequestException, ValueError) as e:
            remote = []
            self.info.append(f"Uzak config okunamadi ({short(e, 60)}); gomulu API host'lari deneniyor")
        self.bases = list(dict.fromkeys(remote + self.FALLBACK))
        node = self.api("movie/by/filtres/0/created/0")
        self.note_host("api", host_of(self.base), "API host'u")
        # "domain" adimi: calisan API host'unun DNS/ping'i (+ uzak config gomuluden farkli mi)
        ips, tcp = doh_resolve(host_of(self.base)), tcp_ping(host_of(self.base))
        extra = f"; uzak config: {', '.join(host_of(b) for b in remote)}" if remote else ""
        self.step("domain", "ok", f"API {host_of(self.base)} [{len(ips)} IP, tcp {tcp or 0:.0f}ms]{extra}")
        if remote and not set(remote) & set(self.FALLBACK):
            self.info.append("Uzak config gomulu yedek host'lardan tamamen farkli: " + ", ".join(host_of(b) for b in remote))

        movies = [{"title": m.get("title", "?"), "id": m["id"], "kind": "movie"} for m in node if m.get("id") and m.get("type", "movie") == "movie"]
        chans = [{"title": c.get("title", "?"), "id": c["id"], "kind": "channel"} for c in self.api("channel/by/filtres/0/0/0") if c.get("id")]
        if not movies or not chans:
            raise CheckError(f"katalog bos (film {len(movies)}, kanal {len(chans)})")
        self.step("katalog", "ok", f"{len(movies)} film, {len(chans)} kanal (1. sayfa)")

        q = random.choice(movies)["title"][:40]
        res = self.api("search/" + quote(q.strip(), safe=""))
        n = len(res.get("posters", [])) + len(res.get("channels", [])) if isinstance(res, dict) else 0
        self.step("arama", "ok" if n else "fail", f"{q!r} → {n} sonuc")

        self.step("akis", "ok", "film: " + self.try_items(movies, self.play))
        try:
            self.step("canli", "ok", "kanal: " + self.try_items(chans, self.play))
        except CheckError as e:
            self.step("canli", "fail", str(e))

    def play(self, item):
        node = self.api(f"{item['kind']}/by/{item['id']}")
        errs = []
        for src in node.get("sources", []):
            if src.get("kind") == "download" or (src.get("type") or "").lower() == "youtube":
                continue
            url = self.stream_url(src)
            if not url and src.get("locked") and src.get("reason") == "AD_UNLOCK_REQUIRED" and src.get("id"):
                un = self.api(f"source/unlock-ad/{src['id']}", f"device_id={self.device_id}")
                if un.get("ok") and not un.get("locked", True):
                    url = self.stream_url(un)
            if not url:
                errs.append("link yok/kilitli")
                continue
            typ = (src.get("type") or "").lower()
            kind = "m3u8" if typ == "m3u8" or url.split("?")[0].lower().endswith(".m3u8") else typ
            if kind not in ("m3u8", "mp4", "mov", "mkv"):
                errs.append(f"{kind or '?'} (extractor)")
                continue
            label = f"{short(item['title'], 40)} [{src.get('title') or 'Yayın'}] "
            try:
                return label + probe_stream(self.net, url, self.MEDIA, "m3u8" if kind == "m3u8" else "mp4")
            except (CheckError, requests.RequestException) as e:
                # Eklentideki workingPlaylist() ile ayni: sorgulu playlist 5xx → sorgusuz adres (CDN token hatasi)
                if kind == "m3u8" and "?" in url and re.search(r"playlist: HTTP 5\d\d", str(e)):
                    try:
                        return label + "(tokensiz) " + probe_stream(self.net, url.split("?", 1)[0], self.MEDIA, "m3u8")
                    except (CheckError, requests.RequestException) as e2:
                        e = e2
                errs.append(short(e, 80))
        raise CheckError("; ".join(errs) or "kaynak (sources) yok")


# Dizipal (dp) pasif: eklentide de kayitli degil (2026-10-11, yerine Dizibox). Sinifi tekrar acmak icin duruyor.
SOURCES = [Rectv, SelcukSports, WebDramaTurkey, Dizibox, HdfilmCehennemi]


# --- Calistirma / rapor ----------------------------------------------------------------
def log(msg):
    print(msg, flush=True)


def run_source(cls, state, fallback=None):
    global VIA
    VIA = fallback
    VPN_USED.clear()
    src = cls(Net(fallback), state.setdefault(cls.id, {}))
    log(f"== {src.name} ({src.id})" + (" — erisilemeyen istekler VPN uzerinden" if fallback else ""))
    status = "ok"
    try:
        src.run()
    except DomainChanged as e:
        src.step("domain", "fail", str(e))
        src.step("akis", "skip", "domain degistigi icin oynatma testi yapilmadi")
        status = "domain"
    except CheckError as e:
        src.step("hata", "fail", str(e))
    except requests.RequestException as e:
        src.step("hata", "fail", f"ag hatasi: {type(e).__name__}: {short(e, 120)}")
    except Exception as e:  # scraper kodunda beklenmedik durum = sayfa yapisi degismis
        src.step("hata", "fail", f"beklenmedik {type(e).__name__}: {short(e, 120)}")
        traceback.print_exc()
    finally:
        VIA = None
    if status != "domain" and any(s[1] == "fail" for s in src.steps):
        status = "fail"
    return {"id": src.id, "name": src.name, "status": status, "steps": src.steps, "info": src.info}


def vpn_compare(cls, state, res, proxy):
    """Normal hatta 2/2 basarisiz kaynagi, ulasilamayan istekleri VPN'den tekrarlayarak bir kez daha dene.
    Boyle calisiyorsa durum 'blocked' olur (kod degil erisim sorunu)."""
    log("  ↻ ulasilamayan istekler VPN uzerinden tekrarlanarak deneniyor")
    v = run_source(cls, copy.deepcopy(state), proxy)  # bu kosu bilinen host durumunu degistirmesin
    used = sorted(VPN_USED)
    if v["status"] == "ok" and used:
        res["status"] = "blocked"
        play = next((d for n, st, d in v["steps"] if n in ("akis", "canli") and st == "ok"), "")
        res["info"].append(f"VPN ile erişiliyor, normal erişim yok: {', '.join(used[:4])} → ISS/ülke engeli olabilir "
                           "(kod sorunu değil, autofix'e iletilmedi)" + (f". VPN'li akis: {short(play, 120)}" if play else ""))
    elif v["status"] == "ok":
        res["info"].append("3. denemede VPN'e gerek kalmadan çalıştı (geçici sorun olabilir)")
    elif v["status"] == "fail":
        fail = next((d for _, st, d in v["steps"] if st == "fail"), "?")
        res["info"].append(f"VPN üzerinden de başarısız: {short(fail, 140)}")
    return res


def esc(text):
    return html.escape(str(text), quote=False)


def format_report(results, elapsed, host):
    icon = {"ok": "✅", "fail": "❌", "domain": "🔀", "blocked": "🚫"}
    bad = [r for r in results if r["status"] != "ok"]
    head = "🩺 <b>Harman sağlık testi</b> — " + ("hepsi OK" if not bad else f"{len(bad)}/{len(results)} kaynakta sorun")
    lines = [head]
    for r in results:
        lines.append(f"\n{icon[r['status']]} <b>{esc(r['name'])}</b>")
        for name, st, detail in r["steps"]:
            if r["status"] == "ok" and name not in ("akis", "canli"):
                continue  # saglikli kaynakta yalniz akis ozetini goster
            mark = {"ok": "·", "fail": "✗", "skip": "–", "warn": "!"}.get(st, "·")
            lines.append(f"  {mark} {name}: {esc(short(detail, 220))}")
        for i in r["info"] + ([r["note"]] if r.get("note") else []):
            lines.append(f"  ℹ️ {esc(i)}")
    lines.append(f"\n<i>{time.strftime('%Y-%m-%d %H:%M')} · {elapsed:.0f}s · {esc(host)}</i>")
    return "\n".join(lines)


def telegram(text, buttons=None):
    token, chat = os.environ.get("TELEGRAM_BOT_TOKEN"), os.environ.get("TELEGRAM_CHAT_ID")
    if not token or not chat:
        log("! TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID yok; bildirim atlandi")
        return False
    for attempt in range(3):
        try:
            r = requests.post(f"https://api.telegram.org/bot{token}/sendMessage", timeout=20,
                              json={"chat_id": chat, "text": text[:4000], "parse_mode": "HTML", "disable_web_page_preview": True,
                                    **({"reply_markup": {"inline_keyboard": buttons}} if buttons else {})})
            if r.ok:
                return True
            log(f"! Telegram HTTP {r.status_code}: {short(r.text, 200)}")
            if r.status_code < 500:
                return False
        except requests.RequestException as e:
            log(f"! Telegram hatasi: {e}")
        time.sleep(5 * (attempt + 1))
    return False


def forward_autofix(results):
    """Bozuk kaynaklari CT 118'deki harman-autofix'e iletir (SSH forced-command; yalniz rapor gider)."""
    payload = json.dumps({"at": time.strftime("%Y-%m-%dT%H:%M:%S"), "results": results}, ensure_ascii=False)
    key = os.environ.get("AUTOFIX_SSH_KEY", "/root/.ssh/harman_autofix")
    try:
        r = subprocess.run(["ssh", "-i", key, "-o", "BatchMode=yes", "-o", "ConnectTimeout=10",
                            "-o", "StrictHostKeyChecking=accept-new", os.environ["AUTOFIX_SSH"]],
                           input=payload, capture_output=True, text=True, timeout=60)
        out = short((r.stdout + r.stderr).strip(), 120)
        log(f"autofix: {out}")
        if r.returncode == 0:
            return "🤖 Claude Code'a iletildi" + (" — düzeltme durumu ayrı mesajla gelecek" if "kuyruga" in out else f" ({esc(out)})")
        return f"🤖 Claude Code'a iletilemedi: {esc(out)}"
    except Exception as e:
        return f"🤖 Claude Code'a iletilemedi: {esc(type(e).__name__)}"


def load_env(path="/etc/harman-health.env"):
    p = Path(path)
    if p.exists():
        for line in p.read_text().splitlines():
            if "=" in line and not line.lstrip().startswith("#"):
                k, v = line.split("=", 1)
                os.environ.setdefault(k.strip(), v.strip().strip('"').strip("'"))


def main():
    ap = argparse.ArgumentParser(description="Harman kaynak saglik testi")
    ap.add_argument("--only", help="virgulle kaynak id'leri: " + ",".join(c.id for c in SOURCES))
    ap.add_argument("--always", action="store_true", help="sorun olmasa da Telegram ozeti gonder")
    ap.add_argument("--no-notify", action="store_true", help="Telegram'a gonderme")
    ap.add_argument("--retry-delay", type=int, default=60, help="basarisiz kaynagi yeniden denemeden once bekleme (sn)")
    ap.add_argument("--no-vpn", action="store_true", help="basarisiz kaynagi VPN uzerinden tekrar deneme")
    ap.add_argument("--telegram-test", action="store_true")
    ap.add_argument("--telegram-chat-id", action="store_true", help="bota yazan sohbetlerin id'lerini listele")
    args = ap.parse_args()
    load_env()
    vpn = None if args.no_vpn else (os.environ.get("VPN_PROXY") or VPN_PROXY_DEFAULT or None)

    if args.telegram_chat_id:
        r = requests.get(f"https://api.telegram.org/bot{os.environ['TELEGRAM_BOT_TOKEN']}/getUpdates", timeout=20).json()
        for u in r.get("result", []):
            c = (u.get("message") or u.get("channel_post") or {}).get("chat", {})
            if c:
                print(c.get("id"), c.get("type"), c.get("title") or c.get("username") or c.get("first_name"))
        return 0
    if args.telegram_test:
        return 0 if telegram("🩺 Harman sağlık testi: Telegram bağlantısı çalışıyor.") else 1

    STATE_DIR.mkdir(parents=True, exist_ok=True)
    import fcntl
    lock = open(STATE_DIR / "run.lock", "w")
    try:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        log("baska bir test calisiyor")
        return 3
    state_file = STATE_DIR / "state.json"
    state = json.loads(state_file.read_text()) if state_file.exists() else {}
    wanted = set(args.only.split(",")) if args.only else None
    t0 = time.monotonic()
    results = []
    for cls in SOURCES:
        if wanted and cls.id not in wanted:
            continue
        res = run_source(cls, state)
        if res["status"] == "fail" and args.retry_delay >= 0:
            # Tek seferlik ag/CDN hiccup'i alarm sebebi olmasin: bir kez daha dene.
            log(f"  ↻ {args.retry_delay}s sonra yeniden deneniyor")
            time.sleep(args.retry_delay)
            res = run_source(cls, state)
            if res["status"] != "ok":
                res["info"].append("ilk denemede de basarisizdi (2/2)")
            else:
                res["note"] = "ilk denemede basarisiz, tekrarda duzeldi"  # tek basina bildirim sebebi degil
        if res["status"] == "fail" and vpn:
            res = vpn_compare(cls, state, res, vpn)
        results.append(res)
    elapsed = time.monotonic() - t0

    prev = state.get("_last", {})
    state["_last"] = {r["id"]: r["status"] for r in results}
    state["_ran_at"] = time.strftime("%Y-%m-%dT%H:%M:%S")
    state_file.write_text(json.dumps(state, indent=2, ensure_ascii=False))
    with open(STATE_DIR / "history.jsonl", "a") as f:
        f.write(json.dumps({"at": state["_ran_at"], "elapsed": round(elapsed), "results": results}, ensure_ascii=False) + "\n")

    bad = [r for r in results if r["status"] != "ok"]
    recovered = [r for r in results if r["status"] == "ok" and prev.get(r["id"], "ok") != "ok"]
    infos = [r for r in results if r["info"]]
    report = format_report(results, elapsed, socket.gethostname())
    if recovered:
        report += "\n\n🟢 Düzelen: " + ", ".join(esc(r["name"]) for r in recovered)
    # "blocked" (yalniz VPN'de calisiyor) kodla duzeltilemez; autofix'e yalniz gercek bozukluk gider
    if any(r["status"] in ("fail", "domain") for r in bad) and not args.no_notify and os.environ.get("AUTOFIX_SSH"):
        report += "\n\n" + forward_autofix(results)
    log("\n" + html.unescape(re.sub(r"</?[bi]>", "", report)))
    if not args.no_notify and (bad or recovered or infos or args.always):
        buttons = [[{"text": "🔁 Tekrar test et", "callback_data": "test:" + ",".join(r["id"] for r in bad)}]] if bad else None
        telegram(report, buttons)
    return 1 if bad else 0


if __name__ == "__main__":
    sys.exit(main())
