from getpass import getpass

from huggingface_hub import get_token, login, model_info, whoami
from huggingface_hub.errors import GatedRepoError, HfHubHTTPError

MODEL_ID = "bodhan-ai/indic-speak"


def describe_http_error(error):
    try:
        response_body = error.response.json()
    except ValueError:
        response_body = {}
    detail = response_body.get("error") or response_body.get("message")
    if not detail:
        detail = error.response.text.strip()
    detail_text = f" Hub detail: {detail}" if detail else ""
    return f"HTTP {error.response.status_code}.{detail_text}"


def main():
    token = getpass(
        "Paste your NEW Hugging Face read token (input stays invisible), then press Enter.\n"
        "Press Enter without typing only if you already have a saved login:\n> "
    ).strip()
    if token:
        print("Token input received; checking Hugging Face sign-in...")
    else:
        token = get_token()
        if not token:
            raise SystemExit(
                "No saved Hugging Face login. Enter a read token or run this helper again with one."
            )

    try:
        account = whoami(token=token)
    except HfHubHTTPError as error:
        raise SystemExit(
            "Hugging Face rejected the token during sign-in. "
            f"{describe_http_error(error)} Check the token and its read permission."
        ) from error

    login(token=token, add_to_git_credential=False)
    print(f"Signed in to Hugging Face as {account.get('name', 'your account')}.")

    try:
        model_info(MODEL_ID, token=token)
    except GatedRepoError as error:
        raise SystemExit(
            f"Sign-in worked, but this account does not have access to {MODEL_ID}. "
            "Open the model page using the same account, complete its access form/license, "
            "and wait for approval if it is still pending."
        ) from error
    except HfHubHTTPError as error:
        raise SystemExit(
            f"Sign-in worked, but checking model access failed. "
            f"{describe_http_error(error)} Confirm this account has access to the model."
        ) from error

    print(f"Model access verified for {MODEL_ID}.")
    print("The token is saved in your local Hugging Face credential store, not this project.")


if __name__ == "__main__":
    main()
