#!/usr/bin/env python3
import sys as _sys
_sys.path.insert(0, "/root/aria/lib")
from aria_logging import get_logger as _get_logger
_log = _get_logger("aria-akp-channel-validate")

"""Channel-Mass-Validate — pruefe alle Channels in youtube-channel-subscriptions.md
ob sie noch existieren + ob yt-dlp Videos fetchen kann. Output: Report mit
Empfehlungen pro Channel.

Run: python3 aria-akp-channel-validate.py [--max N]
"""
import argparse
import re
import subprocess
import sys
import time
from pathlib import Path
from datetime import datetime, timezone

SUBS = Path("/root/aria/brain/05-Referenzen/youtube-channel-subscriptions.md")
OUT = Path(f"/root/aria/brain/02-Wissen/yt-channel-validate-{datetime.now(timezone.utc).strftime('%Y-%m-%d')}.md")
COOKIES = Path("/root/aria/cookies.txt")
PROXY_FILE = Path("/root/aria/.env")


def parse_channels(text: str) -> list[str]:
    channels = []
    for line in text.splitlines():
        m = re.match(r"^-\s+(@[\w\-_.]+|UC[\w\-_]{20,})", line)
        if m:
            channels.append(m.group(1))
    return channels


def validate(handle: str, timeout: int = 60) -> dict:
    url = f"https://www.youtube.com/{handle}/videos" if handle.startswith("@") else f"https://www.youtube.com/channel/{handle}"
    cmd = ["yt-dlp", "--flat-playlist", "--playlist-end", "1", "--dump-json",
           "--no-warnings", "--quiet", "--socket-timeout", "20"]
    if COOKIES.exists():
        cmd += ["--cookies", str(COOKIES)]
    cmd.append(url)
    try:
        r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
    except subprocess.TimeoutExpired:
        return {"status": "timeout", "error": "yt-dlp timeout"}
    if r.returncode != 0:
        err = (r.stderr or "").strip().splitlines()
        msg = err[-1] if err else "unknown error"
        if "ERROR: " in msg:
            return {"status": "fail", "error": msg[:200]}
        return {"status": "fail", "error": msg[:200]}
    line = r.stdout.strip().splitlines()
    if not line:
        return {"status": "empty", "error": "no video found"}
    try:
        import json
        d = json.loads(line[0])
        return {
            "status": "ok",
            "channel_name": d.get("uploader") or d.get("channel") or "",
            "channel_id": d.get("channel_id") or "",
            "latest_video_title": (d.get("title") or "")[:80],
            "latest_video_id": d.get("id", ""),
        }
    except Exception as e:
        return {"status": "parse_error", "error": str(e)[:80]}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--max", type=int, default=None)
    ap.add_argument("--only-handle", type=str, default=None, help="validate only specific handle")
    args = ap.parse_args()

    channels = parse_channels(SUBS.read_text())
    if args.only_handle:
        channels = [c for c in channels if c == args.only_handle]
    if args.max:
        channels = channels[: args.max]
    print(f"# validating {len(channels)} channels", file=sys.stderr)

    results = []
    for i, ch in enumerate(channels, 1):
        print(f"  [{i}/{len(channels)}] {ch}", file=sys.stderr, flush=True)
        r = validate(ch)
        r["handle"] = ch
        results.append(r)
        time.sleep(1.5)

    ok = [r for r in results if r["status"] == "ok"]
    fail = [r for r in results if r["status"] != "ok"]

    lines = [
        "---",
        f"title: YT-Channel-Validate Report {datetime.now(timezone.utc).strftime('%Y-%m-%d')}",
        "type: audit",
        "tags: [akp, channel-validation, video-strategy]",
        f"date: {datetime.now(timezone.utc).strftime('%Y-%m-%d')}",
        "status: aktiv",
        "related: [[youtube-channel-subscriptions]] [[video-knowledge-strategy-audit-2026-05-21]]",
        "linear: KAR-350",
        "---",
        "",
        f"# YT-Channel-Validate Report {datetime.now(timezone.utc).strftime('%Y-%m-%d')}",
        "",
        f"Total validated: **{len(results)}**",
        f"- OK (channel existiert, hat Videos): **{len(ok)}**",
        f"- Fail (404, blocked, oder leer): **{len(fail)}**",
        "",
        "## FAIL — Removal-Kandidaten",
        "",
        "| Handle | Status | Error |",
        "|---|---|---|",
    ]
    for r in fail:
        err = (r.get("error") or "").replace("|", "\\|").replace("\n", " ")[:120]
        lines.append(f"| `{r['handle']}` | {r['status']} | {err} |")
    lines.append("")
    lines.append("## OK — funktionierende Channels (mit letztem Video)")
    lines.append("")
    lines.append("| Handle | Channel-Name | Letztes Video |")
    lines.append("|---|---|---|")
    for r in ok:
        lines.append(f"| `{r['handle']}` | {r.get('channel_name','')} | {r.get('latest_video_title','').replace('|', '\\|')} |")
    lines.append("")
    lines.append("## Empfehlung")
    lines.append("")
    lines.append("FAIL-Channels in `youtube-channel-subscriptions.md` in `## Removed`-Section verschieben mit Supersession-Pointer auf diese Audit-Note.")
    OUT.write_text("\n".join(lines))
    print(f"OK: {OUT}", file=sys.stderr)


if __name__ == "__main__":
    _log.event("script_start")
    main()
