import requests
import json
from pathlib import Path

CLIENT_ID = "1000.ZNQ17ZU1F48Z6DTTBKPRS8HYYGPU2C"
CLIENT_SECRET = "31128c41fe165770eabec0110a9f121b8a9e0846d9"
AUTH_CODE = "1000.c93eb3f36267b1266d7d2d65abb21588.c537f0d10b43e39e160325d28ffd7085"
REDIRECT_URI = "https://www.zoho.com"

url = "https://accounts.zoho.com/oauth/v2/token"
data = {
    "client_id": CLIENT_ID,
    "client_secret": CLIENT_SECRET,
    "grant_type": "authorization_code",
    "code": AUTH_CODE,
    "redirect_uri": REDIRECT_URI
}

try:
    response = requests.post(url, data=data, timeout=30)
    print(f"[INFO] HTTP Status Code: {response.status_code}")

    try:
        resp_json = response.json()
    except json.JSONDecodeError:
        resp_json = None

    if response.status_code == 200 and resp_json:
        tokens = resp_json
        token_file = Path("tokens.json")
        token_file.write_text(json.dumps(tokens, indent=2), encoding="utf-8")
        print(f"[INFO] Tokens saved to {token_file.resolve()}")
    else:
        print("[ERROR] Failed to fetch tokens")
        if resp_json:
            print("[ERROR] Response JSON:", json.dumps(resp_json, indent=2))
        else:
            print("[ERROR] Response Text:", response.text)

except requests.exceptions.ConnectTimeout:
    print("[ERROR] Connection timed out. Please check your internet or proxy settings.")

except requests.exceptions.ConnectionError as e:
    print("[ERROR] Connection error:", str(e))

except requests.exceptions.RequestException as e:
    print("[ERROR] An unexpected error occurred:", str(e))
