#!/usr/bin/env python3
"""Build the eBay OAuth2 consent URL and print it for the user to open.

After the seller approves access, eBay redirects to the callback endpoint
which exchanges the code for tokens automatically.

Usage:
    python scripts/ebay_authorize.py
"""

from __future__ import annotations

import sys
from urllib.parse import quote

from agent_samochodowy.compliance.settings import ComplianceSettings


def build_consent_url(settings: ComplianceSettings) -> str:
    """Construct the eBay OAuth2 authorization URL."""
    base = "https://auth.ebay.com/oauth2/authorize"
    params = (
        f"client_id={quote(settings.ebay_client_id)}"
        f"&redirect_uri={quote(settings.ebay_redirect_uri)}"
        f"&response_type=code"
        f"&scope={quote(settings.ebay_oauth_scopes)}"
    )
    return f"{base}?{params}"


def main() -> None:
    settings = ComplianceSettings()

    if not settings.ebay_client_id:
        print("ERROR: EBAY_CLIENT_ID not set in .env", file=sys.stderr)
        sys.exit(1)

    url = build_consent_url(settings)

    print()
    print("=" * 70)
    print("eBay OAuth2 — Autoryzacja sprzedawcy")
    print("=" * 70)
    print()
    print("Otwórz poniższy URL w przeglądarce i zaloguj się kontem SPRZEDAWCY:")
    print()
    print(url)
    print()
    print("Po zatwierdzeniu zgody eBay przekieruje na:")
    print("  https://api.agent.dgx.dev/ebay/oauth/callback?code=...")
    print()
    print("Callback automatycznie wymieni code na access_token + refresh_token")
    print("i zapisze je w:", settings.ebay_token_path)
    print()
    print("Od tego momentu token będzie odnawiany automatycznie.")
    print("=" * 70)


if __name__ == "__main__":
    main()
