import argparse
import asyncio
import os
import sys

from dotenv import load_dotenv

from .authenticator import FileStorage, UpstoxAuthenticator


def main():
    parser = argparse.ArgumentParser(description="Upstox Auth Pro CLI")
    parser.add_argument("--env", help="Path to .env file", default=".env")
    parser.add_argument(
        "--storage", help="Path to token storage file", default="token.json"
    )
    parser.add_argument(
        "--visible", help="Run browser in visible mode", action="store_true"
    )
    parser.add_argument("--force", help="Force refresh of token", action="store_true")
    parser.add_argument("--encrypt-key", help="Fernet key for token encryption")

    args = parser.parse_args()

    if os.path.exists(args.env):
        load_dotenv(args.env)

    # Use environment variable if arg not provided
    encrypt_key = args.encrypt_key or os.getenv("UPSTOX_ENCRYPT_KEY")

    required = [
        "UPSTOX_API_KEY",
        "UPSTOX_API_SECRET",
        "UPSTOX_MOBILE",
        "UPSTOX_PIN",
        "UPSTOX_TOTP_KEY",
    ]
    missing = [var for var in required if not os.getenv(var)]
    if missing:
        print(f"Error: Missing environment variables: {', '.join(missing)}")
        sys.exit(1)

    if encrypt_key:
        from .storage import EncryptedFileStorage
        storage = EncryptedFileStorage(args.storage, encrypt_key)
    else:
        storage = FileStorage(args.storage)

    auth = UpstoxAuthenticator(
        api_key=os.getenv("UPSTOX_API_KEY"),
        api_secret=os.getenv("UPSTOX_API_SECRET"),
        redirect_uri=os.getenv("UPSTOX_REDIRECT_URI", "https://localhost:8000/callback"),
        mobile_no=os.getenv("UPSTOX_MOBILE"),
        pin=os.getenv("UPSTOX_PIN"),
        totp_key=os.getenv("UPSTOX_TOTP_KEY"),
        storage=storage,
        headless=not args.visible
    )

    try:
        token = asyncio.run(auth.get_access_token(force_refresh=args.force))
        print(token)
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    main()
