import argparse
import sys
from typing import Optional

from pygeai_gam import GAMClient
from pygeai_gam.exceptions import GAMClientError


def main():
    parser = argparse.ArgumentParser(
        prog="gam-cli",
        description="GeneXus Access Manager (GAM) OAuth CLI"
    )
    
    subparsers = parser.add_subparsers(dest="command", help="Available commands")
    
    token_parser = subparsers.add_parser("token", help="Get access token")
    token_subparsers = token_parser.add_subparsers(dest="grant_type", help="Grant type")
    
    password_parser = token_subparsers.add_parser("password", help="Password grant flow")
    password_parser.add_argument("--base-url", required=True, help="GAM base URL")
    password_parser.add_argument("--client-id", required=True, help="OAuth client ID")
    password_parser.add_argument("--client-secret", required=True, help="OAuth client secret")
    password_parser.add_argument("--username", required=True, help="Username")
    password_parser.add_argument("--password", required=True, help="Password")
    password_parser.add_argument("--scope", default="gam_user_data", help="OAuth scope")
    
    auth_code_parser = token_subparsers.add_parser("auth-code", help="Authorization code flow")
    auth_code_parser.add_argument("--base-url", required=True, help="GAM base URL")
    auth_code_parser.add_argument("--client-id", required=True, help="OAuth client ID")
    auth_code_parser.add_argument("--client-secret", help="OAuth client secret (optional for PKCE)")
    auth_code_parser.add_argument("--redirect-uri", required=True, help="Redirect URI")
    auth_code_parser.add_argument("--scope", default="gam_user_data", help="OAuth scope")
    auth_code_parser.add_argument("--use-pkce", action="store_true", help="Use PKCE flow")
    
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        return 0
    
    try:
        if args.command == "token":
            if args.grant_type == "password":
                client = GAMClient(
                    base_url=args.base_url,
                    client_id=args.client_id,
                    client_secret=args.client_secret
                )
                result = client.get_access_token_password_grant(
                    username=args.username,
                    password=args.password,
                    scope=args.scope
                )
                print(f"Access Token: {result['access_token']}")
                if "refresh_token" in result:
                    print(f"Refresh Token: {result['refresh_token']}")
                return 0
                
            elif args.grant_type == "auth-code":
                client = GAMClient(
                    base_url=args.base_url,
                    client_id=args.client_id,
                    client_secret=args.client_secret,
                    use_pkce=args.use_pkce
                )
                result = client.get_access_token_authorization_code(
                    redirect_uri=args.redirect_uri,
                    scope=args.scope
                )
                print(f"Access Token: {result['access_token']}")
                if "refresh_token" in result:
                    print(f"Refresh Token: {result['refresh_token']}")
                return 0
            else:
                token_parser.print_help()
                return 1
        else:
            parser.print_help()
            return 1
            
    except GAMClientError as e:
        print(f"Error: {e}", file=sys.stderr)
        return 1
    except KeyboardInterrupt:
        print("\nOperation cancelled by user", file=sys.stderr)
        return 130
    except Exception as e:
        print(f"Unexpected error: {e}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())
