#!/usr/bin/env python3
"""
Google OAuth Token Refresh Utility (Python version)
Reads credentials from /root/.clawdbot/google-oauth.json
Refreshes access_token using refresh_token
Updates the JSON file and prints new access_token
"""

import json
import sys
import os
import requests
from datetime import datetime, timezone

CREDENTIALS_FILE = "/root/.clawdbot/google-oauth.json"
TOKEN_URL = "https://oauth2.googleapis.com/token"

def main():
    # Check if credentials file exists
    if not os.path.exists(CREDENTIALS_FILE):
        print(f"Error: Credentials file not found at {CREDENTIALS_FILE}", file=sys.stderr)
        sys.exit(1)
    
    try:
        # Read credentials from JSON file
        with open(CREDENTIALS_FILE, 'r') as f:
            credentials = json.load(f)
        
        # Extract required fields
        client_id = credentials.get('client_id')
        client_secret = credentials.get('client_secret')
        refresh_token = credentials.get('refresh_token')
        
        # Validate required fields
        if not all([client_id, client_secret, refresh_token]):
            print("Error: Missing required credentials in JSON file", file=sys.stderr)
            print(f"client_id: {'present' if client_id else 'missing'}", file=sys.stderr)
            print(f"client_secret: {'present' if client_secret else 'missing'}", file=sys.stderr)
            print(f"refresh_token: {'present' if refresh_token else 'missing'}", file=sys.stderr)
            sys.exit(1)
        
        # Prepare request data
        data = {
            'client_id': client_id,
            'client_secret': client_secret,
            'refresh_token': refresh_token,
            'grant_type': 'refresh_token'
        }
        
        # Make POST request to refresh token
        try:
            response = requests.post(TOKEN_URL, data=data, timeout=30)
            response.raise_for_status()  # Raise exception for HTTP errors
        except requests.exceptions.RequestException as e:
            print(f"Error: Failed to make request to Google OAuth API: {e}", file=sys.stderr)
            sys.exit(1)
        
        # Parse response
        try:
            token_data = response.json()
        except json.JSONDecodeError as e:
            print(f"Error: Failed to parse response as JSON: {e}", file=sys.stderr)
            print(f"Response: {response.text}", file=sys.stderr)
            sys.exit(1)
        
        # Check for errors in response
        if 'error' in token_data:
            print(f"Error from Google OAuth API: {token_data.get('error_description', token_data['error'])}", file=sys.stderr)
            sys.exit(1)
        
        # Get new access_token
        new_access_token = token_data.get('access_token')
        if not new_access_token:
            print("Error: No access_token in response", file=sys.stderr)
            print(f"Response: {token_data}", file=sys.stderr)
            sys.exit(1)
        
        # Update credentials with new access_token
        credentials['access_token'] = new_access_token
        
        # Update created_at timestamp if token_data includes expires_in
        if 'expires_in' in token_data:
            # Update created_at to current UTC time
            credentials['created_at'] = datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
        
        # Write updated credentials back to file
        try:
            with open(CREDENTIALS_FILE, 'w') as f:
                json.dump(credentials, f, indent=2)
            print(f"Successfully updated {CREDENTIALS_FILE} with new access_token")
        except IOError as e:
            print(f"Error: Failed to write updated credentials to file: {e}", file=sys.stderr)
            sys.exit(1)
        
        # Print the new access_token
        print("\nNew access_token:")
        print(new_access_token)
        
        # Print additional info if available
        if 'expires_in' in token_data:
            expires_in = token_data['expires_in']
            print(f"\nToken expires in: {expires_in} seconds ({expires_in/3600:.1f} hours)")
        
        return 0
        
    except json.JSONDecodeError as e:
        print(f"Error: Failed to parse credentials file as JSON: {e}", file=sys.stderr)
        sys.exit(1)
    except Exception as e:
        print(f"Unexpected error: {e}", file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    main()