"""OAuth flow for YouTube upload-only tokens."""

from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import Sequence, TextIO
import sys

from autoshorts.youtube.upload_only import (
    ALLOWED_UPLOAD_SCOPE,
    BROAD_YOUTUBE_SCOPES,
    CLIENT_SECRET_PATH,
    TOKEN_PATH,
    load_token_scopes,
    validate_upload_token_scopes,
    warn_if_youtube_api_key_present,
)


def main(argv: Sequence[str] | None = None, *, stdout: TextIO | None = None) -> int:
    parser = argparse.ArgumentParser(description="Authorize YouTube upload-only OAuth token.")
    parser.add_argument("--client-secret", default=str(CLIENT_SECRET_PATH))
    parser.add_argument("--token", default=str(TOKEN_PATH))
    parser.add_argument("--validate-only", action="store_true")
    args = parser.parse_args(argv)
    out = stdout or sys.stdout
    warning = warn_if_youtube_api_key_present()
    if warning:
        print(warning, file=out)
    client_secret = Path(args.client_secret)
    token = Path(args.token)
    if args.validate_only:
        if not token.exists():
            print(f"Token missing: {token}", file=out)
            return 2
        result = load_token_scopes(token)
        print(f"OAuth upload-only status: {'safe' if result.is_safe else 'unsafe'}", file=out)
        print(f"Allowed scope: {ALLOWED_UPLOAD_SCOPE}", file=out)
        print(f"Forbidden scopes: {', '.join(sorted(BROAD_YOUTUBE_SCOPES))}", file=out)
        if result.forbidden_scopes:
            print(f"Forbidden granted: {', '.join(result.forbidden_scopes)}", file=out)
        return 0 if result.is_safe else 3
    if not client_secret.exists():
        print(f"Client secret missing: {client_secret}", file=out)
        return 2
    try:
        from google_auth_oauthlib.flow import InstalledAppFlow  # type: ignore
    except Exception:
        print("google-auth-oauthlib is not installed; cannot run OAuth flow in this environment.", file=out)
        print(f"Requested scope would be: {ALLOWED_UPLOAD_SCOPE}", file=out)
        return 2
    flow = InstalledAppFlow.from_client_secrets_file(str(client_secret), scopes=[ALLOWED_UPLOAD_SCOPE])
    # Remote/headless-safe: print the authorization URL instead of trying to
    # open a desktop browser inside the agent container. The local callback
    # server still receives Google's redirect after the user authorizes.
    creds = flow.run_local_server(port=0, open_browser=False)
    scopes = getattr(creds, "scopes", None) or [ALLOWED_UPLOAD_SCOPE]
    result = validate_upload_token_scopes(scopes)
    if not result.is_safe:
        print("Token unsafe; not writing token file.", file=out)
        print(result.message, file=out)
        return 3
    token.parent.mkdir(parents=True, exist_ok=True)
    token.write_text(creds.to_json(), encoding="utf-8")
    # Re-validate serialized token because stored shape can differ by library version.
    stored = json.loads(token.read_text(encoding="utf-8"))
    stored.setdefault("scopes", list(result.granted_scopes))
    token.write_text(json.dumps(stored, indent=2), encoding="utf-8")
    final = load_token_scopes(token)
    print(f"OAuth upload-only status: {'safe' if final.is_safe else 'unsafe'}", file=out)
    print(f"Token path: {token}", file=out)
    print(f"Allowed scope: {ALLOWED_UPLOAD_SCOPE}", file=out)
    return 0 if final.is_safe else 3


if __name__ == "__main__":
    raise SystemExit(main())
