#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
OAuth Setup — Google Search Console + GA4 + Google Business Profile
Dipisahkan dari skill google-workspace karena scope-nya berbeda.

Cara pakai:
  1. python3 oauth_seo.py --client-secret /path/ke/client_secret.json
  2. python3 oauth_seo.py --auth-url
  3. (buka URL di browser, izinkan, copy URL hasil redirect)
  4. python3 oauth_seo.py --auth-code "URL_ATAU_CODE"
  5. python3 oauth_seo.py --check
"""
import argparse, json, os, sys, webbrowser

BASE = os.path.dirname(os.path.abspath(__file__))
TOKEN = os.path.join(BASE, "google_token_atun.json")
CLIENT = os.path.join(BASE, "client_secret.json")
PENDING = os.path.join(BASE, "oauth_pending.json")

SCOPES = [
    "https://www.googleapis.com/auth/webmasters.readonly",   # Search Console (baca)
    "https://www.googleapis.com/auth/analytics.readonly",    # GA4 (baca)
    "https://www.googleapis.com/auth/business.manage",       # Google Business Profile
]

REDIRECT_URI = "http://localhost:1/"


def load_client():
    if not os.path.exists(CLIENT):
        print(f"❌ client_secret.json belum ada di {CLIENT}")
        print("   Jalankan: python3 oauth_seo.py --client-secret /path/file.json")
        sys.exit(1)
    data = json.load(open(CLIENT))
    # dukung format 'installed' (desktop) atau 'web'
    key = "installed" if "installed" in data else ("web" if "web" in data else None)
    if not key:
        print("❌ Format client secret tidak dikenali (harus 'installed' atau 'web').")
        sys.exit(1)
    return data[key]


def save_client(path):
    src = json.load(open(path))
    json.dump(src, open(CLIENT, "w"), indent=1)
    key = "installed" if "installed" in src else ("web" if "web" in src else "?")
    cid = (src.get(key) or {}).get("client_id", "")[:30]
    print(f"✅ client secret disimpan → {CLIENT}")
    print(f"   tipe: {key} | client_id: {cid}...")


def cmd_auth_url():
    from google_auth_oauthlib.flow import Flow
    cfg = load_client()
    flow = Flow.from_client_config(
        {"installed": cfg} if "client_id" in cfg else cfg, scopes=SCOPES, redirect_uri=REDIRECT_URI
    )
    url, state = flow.authorization_url(
        access_type="offline", include_granted_scopes="true", prompt="consent"
    )
    # SIMPAN code_verifier — wajib untuk PKCE saat exchange
    json.dump({"state": state, "code_verifier": flow.code_verifier}, open(PENDING, "w"))
    print("🔗 Buka URL ini di browser (login akun Google yang punya akses properti):\n")
    print(url)
    print("\nSetelah klik 'Izinkan', browser akan gagal membuka localhost:1 — itu NORMAL.")
    print("Copy SELURUH URL dari address bar, lalu kirim ke saya.")


def cmd_auth_code(code):
    from google_auth_oauthlib.flow import Flow
    cfg = load_client()
    flow = Flow.from_client_config(
        {"installed": cfg} if "client_id" in cfg else cfg, scopes=SCOPES, redirect_uri=REDIRECT_URI
    )
    # muat code_verifier yang tersimpan (PKCE)
    if os.path.exists(PENDING):
        pend = json.load(open(PENDING))
        if pend.get("code_verifier"):
            flow.code_verifier = pend["code_verifier"]
            print("(code_verifier dimuat dari sesi sebelumnya)")
    # kalau user menempel URL lengkap, ambil parameter code
    if "code=" in code:
        import urllib.parse as up
        q = up.parse_qs(up.urlparse(code).query)
        code = q.get("code", [code])[0]
    flow.fetch_token(code=code)
    creds = flow.credentials
    json.dump({
        "token": creds.token, "refresh_token": creds.refresh_token,
        "token_uri": creds.token_uri, "client_id": creds.client_id,
        "client_secret": creds.client_secret, "scopes": list(creds.scopes or SCOPES),
    }, open(TOKEN, "w"), indent=1)
    print(f"✅ Token disimpan → {TOKEN}")
    print("   scopes:", ", ".join(creds.scopes or SCOPES))


def cmd_check():
    if not os.path.exists(TOKEN):
        print("❌ Belum ada token. Jalankan --auth-url lalu --auth-code.")
        return
    t = json.load(open(TOKEN))
    print("✅ TOKEN ADA")
    print("   scopes:", ", ".join(t.get("scopes", [])))
    print("   refresh_token:", "ADA" if t.get("refresh_token") else "TIDAK ADA (akan expire)")
    # test cepat ke Search Console
    try:
        from google.oauth2.credentials import Credentials
        from googleapiclient.discovery import build
        creds = Credentials(**{k: t[k] for k in
                              ("token", "refresh_token", "token_uri", "client_id", "client_secret")})
        sc = build("searchconsole", "v1", credentials=creds, cache_discovery=False)
        sites = sc.sites().list().execute()
        print("\n📊 Search Console — properti yang bisa diakses:")
        for s in sites.get("siteEntry", []):
            print("   -", s.get("siteUrl"), "|", s.get("permissionLevel"))
    except Exception as e:
        print("\n⚠️ Gagal cek Search Console:", str(e)[:200])


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--client-secret")
    ap.add_argument("--auth-url", action="store_true")
    ap.add_argument("--auth-code")
    ap.add_argument("--check", action="store_true")
    a = ap.parse_args()
    if a.client_secret:
        save_client(a.client_secret)
    elif a.auth_url:
        cmd_auth_url()
    elif a.auth_code:
        cmd_auth_code(a.auth_code)
    elif a.check:
        cmd_check()
    else:
        ap.print_help()
