"""سكربت محلي لاستخراج Refresh Token من جوجل لحساب Google Ads.

الطريقة:
  1. هات Client ID + Client Secret من Google Cloud Console (نوع OAuth: Desktop app).
  2. شغّل: python google_oauth_setup.py
  3. السكربت هيفتح المتصفح، اختار الحساب اللي عليه Google Ads ووافق.
  4. الـ refresh_token هيتحفظ تلقائياً في config.json

لازم تكون مفعّل Google Ads API في نفس المشروع على Google Cloud.
"""

import http.server
import json
import os
import socketserver
import sys
import threading
import urllib.parse
import urllib.request
import webbrowser

if hasattr(sys.stdout, 'reconfigure'):
    sys.stdout.reconfigure(encoding='utf-8', errors='replace')

DATA_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_FILE = os.path.join(DATA_DIR, 'config.json')
PORT = 8765
REDIRECT_URI = f"http://127.0.0.1:{PORT}/"
SCOPE = "https://www.googleapis.com/auth/adwords"


def load_config():
    if os.path.exists(CONFIG_FILE):
        try:
            with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception:
            pass
    return {}


def save_config(cfg):
    with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
        json.dump(cfg, f, ensure_ascii=False, indent=2)


class Handler(http.server.BaseHTTPRequestHandler):
    code = None
    error = None

    def do_GET(self):
        parsed = urllib.parse.urlparse(self.path)
        params = urllib.parse.parse_qs(parsed.query)
        if 'code' in params:
            Handler.code = params['code'][0]
            body = "<h3>تم بنجاح ✅</h3><p>ارجع للـ terminal لإكمال الإعداد.</p>"
            status = 200
        else:
            Handler.error = params.get('error', ['unknown'])[0]
            body = f"<h3>فشل الإعداد ❌</h3><p>{Handler.error}</p>"
            status = 400
        data = f"<html dir='rtl'><meta charset='utf-8'><body style='font-family:sans-serif'>{body}</body></html>".encode('utf-8')
        self.send_response(status)
        self.send_header('Content-Type', 'text/html; charset=utf-8')
        self.send_header('Content-Length', str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def log_message(self, *args):
        pass


def exchange_code(client_id, client_secret, code):
    body = urllib.parse.urlencode({
        'code': code,
        'client_id': client_id,
        'client_secret': client_secret,
        'redirect_uri': REDIRECT_URI,
        'grant_type': 'authorization_code',
    }).encode()
    req = urllib.request.Request(
        'https://oauth2.googleapis.com/token', data=body, method='POST',
        headers={'Content-Type': 'application/x-www-form-urlencoded'})
    with urllib.request.urlopen(req, timeout=30) as resp:
        return json.loads(resp.read().decode('utf-8'))


def main():
    cfg = load_config()
    google = cfg.setdefault('google_ads', {})

    client_id = (google.get('client_id') or '').strip()
    client_secret = (google.get('client_secret') or '').strip()

    if not client_id:
        print("\nمحتاج OAuth Client ID من Google Cloud Console")
        print("(APIs & Services > Credentials > Create Credentials > OAuth client ID > Desktop app)\n")
        client_id = input("Client ID: ").strip()
    if not client_secret:
        client_secret = input("Client Secret: ").strip()

    if not client_id or not client_secret:
        print("❌ لازم Client ID و Client Secret")
        return 1

    auth_url = "https://accounts.google.com/o/oauth2/v2/auth?" + urllib.parse.urlencode({
        'client_id': client_id,
        'redirect_uri': REDIRECT_URI,
        'response_type': 'code',
        'scope': SCOPE,
        'access_type': 'offline',
        'prompt': 'consent',
    })

    print("\nهفتح المتصفح دلوقتي... لو مفتحش، افتح الرابط ده يدوياً:\n")
    print(auth_url)
    print()

    with socketserver.TCPServer(("127.0.0.1", PORT), Handler) as httpd:
        thread = threading.Thread(target=httpd.handle_request, daemon=True)
        thread.start()
        webbrowser.open(auth_url)
        thread.join(timeout=300)

    if not Handler.code:
        print("❌ مفيش authorization code. السبب:", Handler.error or "انتهت المدة")
        return 1

    try:
        tokens = exchange_code(client_id, client_secret, Handler.code)
    except Exception as e:
        print("❌ فشل تبادل الكود:", e)
        return 1

    refresh = tokens.get('refresh_token')
    if not refresh:
        print("⚠️ جوجل مرجّعش refresh_token. جرّب تشيل صلاحية التطبيق من")
        print("   https://myaccount.google.com/permissions ثم أعد المحاولة.")
        return 1

    google['client_id'] = client_id
    google['client_secret'] = client_secret
    google['refresh_token'] = refresh
    cfg['google_ads'] = google
    save_config(cfg)

    print("\n✅ تم حفظ Refresh Token في config.json")
    print("   باقي تدخل Developer Token و Customer ID من واجهة اللوحة أو من config.json")

    customer = input("\nCustomer ID (10 أرقام، سيبه فاضي لو مش عايز): ").strip()
    if customer:
        google['customer_id'] = customer.replace('-', '').replace(' ', '')
        save_config(cfg)
        print("✅ تم حفظ Customer ID")
    return 0


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