#!/usr/bin/env python3
"""
Zoho OAuth Refresh Token Generator
This script helps you obtain a refresh token for Zoho API access.
"""

import requests
import urllib.parse

# Your Zoho OAuth credentials
CLIENT_ID = "1000.2UZYK7Z8H7AIWAWU20ZT1JUC99JPLU"
CLIENT_SECRET = "d4d0b19a4ddce9d350fa7c8943689363dae60537ad"
REDIRECT_URI = "http://localhost"
DATA_CENTER = "com"  # Change to eu, in, com.au, jp if needed

# Zoho OAuth endpoints
AUTH_URL = f"https://accounts.zoho.{DATA_CENTER}/oauth/v2/auth"
TOKEN_URL = f"https://accounts.zoho.{DATA_CENTER}/oauth/v2/token"

# Scopes for Zoho Projects
SCOPES = "ZohoProjects.projects.ALL,ZohoProjects.portals.ALL,ZohoProjects.tasks.ALL,ZohoProjects.timesheets.ALL,ZohoProjects.users.ALL"

def generate_auth_url():
    """Generate the authorization URL"""
    params = {
        "scope": SCOPES,
        "client_id": CLIENT_ID,
        "response_type": "code",
        "access_type": "offline",
        "redirect_uri": REDIRECT_URI,
        "prompt": "consent"
    }

    auth_url = f"{AUTH_URL}?{urllib.parse.urlencode(params)}"
    return auth_url

def exchange_code_for_token(auth_code):
    """Exchange authorization code for access token and refresh token"""
    data = {
        "grant_type": "authorization_code",
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "redirect_uri": REDIRECT_URI,
        "code": auth_code
    }

    response = requests.post(TOKEN_URL, data=data)

    if response.status_code == 200:
        tokens = response.json()
        return tokens
    else:
        print(f"Error: {response.status_code}")
        print(response.text)
        return None

def main():
    print("=" * 70)
    print("ZOHO OAUTH REFRESH TOKEN GENERATOR")
    print("=" * 70)
    print()
    print("STEP 1: Visit the following URL in your browser")
    print("-" * 70)

    auth_url = generate_auth_url()
    print(auth_url)
    print()
    print("-" * 70)
    print()
    print("STEP 2: After authorizing, you'll be redirected to a URL like:")
    print("http://localhost?code=1000.xxxxx.xxxxx&location=us&accounts-server=...")
    print()
    print("STEP 3: Copy the 'code' parameter value from the URL")
    print("(Everything after 'code=' and before the next '&')")
    print()

    auth_code = input("Enter the authorization code: ").strip()

    if not auth_code:
        print("Error: No authorization code provided")
        return

    print()
    print("Exchanging code for tokens...")
    print()

    tokens = exchange_code_for_token(auth_code)

    if tokens:
        print("=" * 70)
        print("SUCCESS! Here are your tokens:")
        print("=" * 70)
        print()
        print(f"Access Token: {tokens.get('access_token', 'N/A')}")
        print()
        print(f"Refresh Token: {tokens.get('refresh_token', 'N/A')}")
        print()
        print(f"Expires In: {tokens.get('expires_in', 'N/A')} seconds")
        print()
        print("=" * 70)
        print()
        print("IMPORTANT: Save your refresh token securely!")
        print("You'll use it to access the Zoho Projects API.")
        print()

        # Save to file
        with open("zoho_tokens.txt", "w") as f:
            f.write(f"Refresh Token: {tokens.get('refresh_token', 'N/A')}\n")
            f.write(f"Access Token: {tokens.get('access_token', 'N/A')}\n")
            f.write(f"Expires In: {tokens.get('expires_in', 'N/A')} seconds\n")

        print("Tokens saved to: zoho_tokens.txt")
    else:
        print("Failed to obtain tokens. Please try again.")

if __name__ == "__main__":
    main()
