#!/usr/bin/env python3
"""YouTube-Upload via Data API v3 (videos.insert, resumable).

OAuth: ~/.secrets/youtube_oauth.json mit client_secret + refresh_token.
Fehlt die Datei/der refresh_token: klare Anleitung, kein Crash.

CLI:
  python3 upload_youtube.py --file video.mp4 --title '...' --desc '...' \
      --tags a,b --publish-at '2026-11-15T10:00:00Z' [--json meta.json]

Alternativ alle Metadaten als JSON (--json): keys title, description, tags,
categoryId, publishAt, privacyStatus, containsSyntheticMedia.
"""
import argparse
import json
import os
import sys
import time

from google.oauth2 import credentials as oauth_credentials
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload

OAUTH_FILE = os.path.expanduser("~/.secrets/youtube_oauth.json")
SCOPE = "https://www.googleapis.com/auth/youtube.upload"


def missing_token_guide():
    return f"""
==================== FEHLENDER OAUTH-REFRESH-TOKEN ====================
Die Datei {OAUTH_FILE} fehlt oder enthaelt keinen 'refresh_token'.
Der Token muss EINMALIG vom Owner im Browser erzeugt werden (danach nie wieder):

1. Google Cloud Console (https://console.cloud.google.com):
   - Projekt anlegen (oder bestehendes waehlen)
   - APIs & Services -> Library -> 'YouTube Data API v3' aktivieren
   - APIs & Services -> OAuth consent screen: External, App-Name beliebig,
     Test-User = das eigene Google-Konto (Kanal-Account) hinzufuegen
   - Credentials -> Create Credentials -> OAuth client ID -> Typ 'Desktop app'
   - Client-JSON herunterladen
2. Client-JSON in {OAUTH_FILE} legen, Format:
   {{
     "installed": {{ ... heruntergeladene client_secret-Datei ... }},
     "refresh_token": "<TOKEN>"
   }}
3. Refresh-Token erzeugen (einmalig, Browser mit dem Kanal-Account eingeloggt):
   Auf dem VPS in einem Terminal mit Port-Weiterleitung (oder lokal) ausfuehren:
     ~/.venvs/youtube/bin/python -c "from google_auth_oauthlib.flow import InstalledAppFlow; \\
       f = InstalledAppFlow.from_client_secrets_file('{OAUTH_FILE}', scopes=['{SCOPE}']); \\
       c = f.run_local_server(port=0, open_browser=False); \\
       print(c.credentials.refresh_token)"
   Angezeigte URL im Browser oeffnen, Consent bestaetigen (Test-User!),
   dann den ausgegebenen refresh_token als "refresh_token" in {OAUTH_FILE} eintragen.
4. Erneut ausfuehren.
Hinweis: Scope ist minimal ({SCOPE}); Quota seit Reform 2026: 100 Uploads/Tag.
======================================================================
"""


def get_service():
    if not os.path.exists(OAUTH_FILE):
        print(missing_token_guide())
        return None
    with open(OAUTH_FILE) as fh:
        cfg = json.load(fh)
    refresh_token = cfg.get("refresh_token")
    client = cfg.get("installed") or cfg.get("web")
    if not (refresh_token and client):
        print(missing_token_guide())
        return None

    creds = oauth_credentials.Credentials(
        token=None,
        refresh_token=refresh_token,
        token_uri="https://oauth2.googleapis.com/token",
        client_id=client.get("client_id"),
        client_secret=client.get("client_secret"),
        scopes=[SCOPE],
    )
    creds.refresh(Request())  # Access-Token aus Refresh-Token holen
    return build("youtube", "v3", credentials=creds)


def progress_cb(progress):
    pct = int(progress.progress() * 100)
    if pct % 10 == 0:
        sys.stderr.write(f"[upload] {pct}%\n")
        sys.stderr.flush()


def upload(video_file, meta):
    service = get_service()
    if service is None:
        return 2  # Token fehlt -> Anleitung wurde ausgegeben

    body = {
        "snippet": {
            "title": meta["title"],
            "description": meta.get("description", ""),
            "tags": meta.get("tags", []),
            "categoryId": str(meta.get("categoryId", "22")),
        },
        "status": {
            "privacyStatus": meta.get("privacyStatus", "public"),
            "containsSyntheticMedia": True,  # AI-Disclosure Pflicht
        },
    }
    if meta.get("publishAt"):
        body["status"]["publishAt"] = meta["publishAt"]

    media = MediaFileUpload(video_file, chunksize=8 * 1024 * 1024,
                            resumable=True, mimetype="video/mp4")
    request = service.videos().insert(part="snippet,status", body=body,
                                     media_body=media)

    retries = 0
    response = None
    while response is None:
        try:
            status, response = request.next_chunk()
            if status:
                sys.stderr.write(f"[upload] {int(status.progress() * 100)}%\n")
        except HttpError as e:
            reason = ""
            try:
                reason = json.loads(e.content)["error"]["errors"][0]["reason"]
            except Exception:
                pass
            if reason in ("quotaExceeded", "rateLimitExceeded",
                          "userRateLimitExceeded") and retries < 3:
                retries += 1
                wait = 30 * retries
                sys.stderr.write(f"[upload] {reason}, Retry in {wait}s "
                                 f"({retries}/3)\n")
                time.sleep(wait)
                continue
            if reason == "quotaExceeded":
                print(f"FEHLER: quotaExceeded — Upload-Bucket (100/Tag) "
                      f"erschöpft. Reset täglich 08:00 UTC (Pacific-Mitternacht).",
                      file=sys.stderr)
            else:
                print(f"FEHLER bei Upload ({reason}): {e}", file=sys.stderr)
            return 1

    vid = response.get("id")
    print(f"OK: https://youtu.be/{vid}")
    print(json.dumps(response, indent=2, ensure_ascii=False))
    return 0


def main():
    ap = argparse.ArgumentParser(description="YouTube Data API Upload")
    ap.add_argument("--file", required=True, help="Pfad zur Videodatei")
    ap.add_argument("--title")
    ap.add_argument("--desc")
    ap.add_argument("--tags", help="Komma-getrennt, z.B. a,b,c")
    ap.add_argument("--category-id", default="22")
    ap.add_argument("--publish-at",
                    help="ISO-8601, z.B. 2026-11-15T10:00:00Z")
    ap.add_argument("--privacy", default="public",
                    choices=["public", "unlisted", "private"])
    ap.add_argument("--json", help="Metadaten als JSON-Datei")
    args = ap.parse_args()

    meta = {"privacyStatus": args.privacy, "categoryId": args.category_id}
    if args.json:
        with open(args.json) as fh:
            meta.update(json.load(fh))
    if args.title:
        meta["title"] = args.title
    if args.desc is not None:
        meta["description"] = args.desc
    if args.tags:
        meta["tags"] = [t.strip() for t in args.tags.split(",") if t.strip()]
    if args.publish_at:
        meta["publishAt"] = args.publish_at
    if not meta.get("title"):
        ap.error("--title oder --json mit title ist erforderlich")
    if not os.path.exists(args.file):
        ap.error(f"Datei nicht gefunden: {args.file}")

    sys.exit(upload(args.file, meta))


if __name__ == "__main__":
    main()
