"""
Generate OAuth2 refresh token with GA4 Analytics scope.
Manual approach - no local server needed.
"""
import os
import urllib.parse
import requests
from dotenv import load_dotenv

load_dotenv()

CLIENT_ID = os.getenv("GOOGLE_ADS_OAUTH2_CLIENT_ID")
CLIENT_SECRET = os.getenv("GOOGLE_ADS_OAUTH2_CLIENT_SECRET")

SCOPES = "https://www.googleapis.com/auth/analytics.readonly"
REDIRECT_URI = "http://localhost"

# Step 1: Build auth URL
params = {
    "client_id": CLIENT_ID,
    "redirect_uri": REDIRECT_URI,
    "response_type": "code",
    "scope": SCOPES,
    "access_type": "offline",
    "prompt": "consent",
}
auth_url = "https://accounts.google.com/o/oauth2/auth?" + urllib.parse.urlencode(params)

print("=" * 60)
print("KROK 1: Otworz ten URL w przegladarce:")
print("=" * 60)
print(auth_url)
print("=" * 60)
print()
print("KROK 2: Zaloguj sie i zezwol na dostep.")
print("Przegladarka przekieruje na http://localhost/?code=XXXXXX")
print("Strona NIE zaladuje sie (to normalne!).")
print("Skopiuj CALY URL z paska adresu przegladarki i wklej tutaj:")
print()

redirect_url = input("Wklej URL z paska adresu: ").strip()

# Step 2: Extract code from URL
parsed = urllib.parse.urlparse(redirect_url)
query_params = urllib.parse.parse_qs(parsed.query)

if "code" not in query_params:
    print("Blad: nie znaleziono kodu w URL. Upewnij sie ze skopiowales caly URL.")
    exit(1)

code = query_params["code"][0]

# Step 3: Exchange code for tokens
token_response = requests.post("https://oauth2.googleapis.com/token", data={
    "code": code,
    "client_id": CLIENT_ID,
    "client_secret": CLIENT_SECRET,
    "redirect_uri": REDIRECT_URI,
    "grant_type": "authorization_code",
})

if token_response.status_code != 200:
    print(f"Blad: {token_response.text}")
    exit(1)

tokens = token_response.json()
refresh_token = tokens.get("refresh_token")

print()
print("=" * 60)
print("GA4 REFRESH TOKEN:")
print("=" * 60)
print(refresh_token)
print("=" * 60)
