"""Request an AI Experiments token using CloudFerro portal credentials."""

import os
import sys

import requests

TOKEN_URL = (
    "https://identity.cloudferro.com/auth/realms/CloudFerro-Cloud/"
    "protocol/openid-connect/token"
)
CLIENT_ID = "mlflow-cli-authservice"


def get_token() -> str:
    missing = [name for name in ("MLFLOW_USERNAME", "MLFLOW_PASSWORD")
               if not os.environ.get(name)]
    if missing:
        raise RuntimeError("Set these environment variables: " + ", ".join(missing))

    totp = os.environ.get("MLFLOW_TOTP", "").strip()
    if not totp:
        print("TOTP code (6 digits): ", end="", file=sys.stderr, flush=True)
        totp = input().strip()

    response = requests.post(
        TOKEN_URL,
        data={
            "client_id": CLIENT_ID,
            "grant_type": "password",
            "username": os.environ["MLFLOW_USERNAME"],
            "password": os.environ["MLFLOW_PASSWORD"],
            "totp": totp,
        },
        timeout=30,
    )
    try:
        response.raise_for_status()
    except requests.HTTPError:
        try:
            details = response.json()
        except ValueError:
            details = {}
        fields = []
        if isinstance(details, dict):
            for name in ("error", "error_description"):
                value = details.get(name)
                if isinstance(value, str) and value:
                    fields.append(f"{name}={value}")
        message = "; ".join(fields) or "No OAuth error details returned."
        for secret in (os.environ["MLFLOW_USERNAME"],
                       os.environ["MLFLOW_PASSWORD"], totp):
            if secret:
                message = message.replace(secret, "[redacted]")
        raise RuntimeError(
            f"Token request failed (HTTP {response.status_code}): {message}"
        ) from None
    token = response.json().get("access_token")
    if not isinstance(token, str) or not token:
        raise RuntimeError("The identity service returned no access token.")
    return token


if __name__ == "__main__":
    print(get_token())
