#!/usr/bin/env python3
"""AKP Proxy Health-Check (KAR-741).

Tests the YouTube ingest proxy (YT_PROXY) end-to-end and sends a Telegram alert
if it is dead — so a dead proxy never again silently kills the video pipeline
for weeks. Run daily before the nightly AKP ingest.

Healthy = proxy returns a residential exit IP AND a YouTube channel listing
returns >0 entries. Otherwise alert Kais with the failure reason.
"""
import json
import os
import subprocess
import sys
import urllib.parse
import urllib.request
from pathlib import Path

CHANNEL_TEST_URL = "https://www.youtube.com/@aiDotEngineer/videos"
EXIT_IP_URL = "https://ipv4.webshare.io/"
ENV_PATH = "/root/aria/.env"
STATE = Path("/root/aria/state/proxy-health.json")


def load_env_value(key: str, path: str = ENV_PATH) -> str | None:
    try:
        for line in Path(path).read_text().splitlines():
            line = line.strip()
            if line.startswith("#") or "=" not in line:
                continue
            k, _, v = line.partition("=")
            if k.strip() == key:
                return v.strip().strip('"').strip("'")
    except OSError:
        pass
    return os.environ.get(key)


def get_telegram_token() -> str | None:
    for path in ("/root/.claude/channels/telegram/.env", "/root/aria/.env", "/root/.env"):
        if not Path(path).exists():
            continue
        for line in Path(path).read_text().splitlines():
            line = line.strip()
            if not line or line.startswith("#") or "=" not in line:
                continue
            k, _, v = line.partition("=")
            if k.strip() in ("TG_TOKEN", "TELEGRAM_BOT_TOKEN", "TELEGRAM_TOKEN") and v.strip():
                return v.strip().strip('"').strip("'")
    return os.environ.get("TG_TOKEN") or os.environ.get("TELEGRAM_BOT_TOKEN")


def send_telegram(text: str) -> bool:
    token = get_telegram_token()
    chat_id = load_env_value("TELEGRAM_CHAT_ID") or "1164395546"
    if not token:
        print("[proxy-health] no telegram token", file=sys.stderr)
        return False
    data = urllib.parse.urlencode({
        "chat_id": chat_id, "text": text,
        "parse_mode": "MarkdownV2", "disable_web_page_preview": "true",
    }).encode()
    req = urllib.request.Request(
        f"https://api.telegram.org/bot{token}/sendMessage", data=data, method="POST")
    try:
        with urllib.request.urlopen(req, timeout=15) as resp:
            return resp.status == 200
    except Exception as e:
        print(f"[proxy-health] telegram error: {e}", file=sys.stderr)
        return False


def run(cmd: list[str], timeout: int) -> tuple[int, str, str]:
    try:
        r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
        return r.returncode, r.stdout, r.stderr
    except subprocess.TimeoutExpired:
        return 124, "", "timeout"


def check() -> tuple[bool, str]:
    proxy = load_env_value("YT_PROXY")
    if not proxy:
        return False, "YT_PROXY ist leer/nicht gesetzt"
    # 1) exit IP through proxy
    rc, out, err = run(["curl", "-s", "--proxy", proxy, EXIT_IP_URL], 30)
    exit_ip = out.strip()
    own = (load_env_value("YT_PROXY") or "")
    if not exit_ip or "407" in err or "407" in out:
        return False, f"Proxy liefert keine Exit-IP (407/leer). curl rc={rc}"
    # 2) youtube channel listing through proxy
    rc, out, err = run(["yt-dlp", "--flat-playlist", "-J", "--playlist-end", "3",
                        "--no-warnings", "--socket-timeout", "25", "--proxy", proxy,
                        CHANNEL_TEST_URL], 60)
    try:
        n = len(json.loads(out).get("entries") or []) if out.strip() else 0
    except json.JSONDecodeError:
        n = 0
    if n < 1:
        tail = (err or "").strip().splitlines()[-1:] or [""]
        return False, f"YouTube-Listing 0 Videos durch Proxy. {tail[0][:120]}"
    return True, f"ok (exit-IP {exit_ip}, {n} videos)"


def main() -> int:
    ok, detail = check()
    STATE.parent.mkdir(parents=True, exist_ok=True)
    prev_ok = True
    if STATE.exists():
        try:
            prev_ok = json.loads(STATE.read_text()).get("ok", True)
        except Exception:
            pass
    STATE.write_text(json.dumps({"ok": ok, "detail": detail}))
    print(f"[proxy-health] {'OK' if ok else 'FAIL'}: {detail}")
    if not ok:
        # Alert (escape MarkdownV2 specials in detail)
        esc = detail
        for ch in r"_*[]()~`>#+-=|{}.!":
            esc = esc.replace(ch, "\\" + ch)
        send_telegram(
            "\U0001F6A8 *AKP Proxy DOWN* \\(KAR\\-741\\)\n\n"
            f"Der YouTube\\-Ingest\\-Proxy antwortet nicht: {esc}\n\n"
            "Die Video\\-Pipeline ingestet gerade *nichts*\\. "
            "Wahrscheinlich Webshare\\-Plan/Bandbreite/IP\\-Auth prüfen "
            "\\(dashboard\\.webshare\\.io\\)\\."
        )
    elif not prev_ok:
        send_telegram("✅ *AKP Proxy wieder OK* \\(KAR\\-741\\)\\. Video\\-Pipeline läuft\\.")
    return 0 if ok else 1


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