"""Command-line interface for the Tyko client.

Usage:
    tyko login       Log in via browser (saves API key to ~/.config/tyko/credentials)
    tyko logout      Remove stored credentials
    tyko whoami      Show the currently stored API key info
"""

import sys


def _login_command() -> None:
    import os

    from ._auth import login

    api_url = os.environ.get("TYKO_API_URL", "https://api.tyko-labs.com")
    try:
        login(api_url=api_url)
    except RuntimeError as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)


def _logout_command() -> None:
    from ._auth import clear_credentials

    if clear_credentials():
        print("Logged out. Credentials removed.")
    else:
        print("No stored credentials found.")


def _whoami_command() -> None:
    from ._auth import get_stored_credentials

    creds = get_stored_credentials()
    if creds is None:
        print("Not logged in. Run `tyko login` to authenticate.")
        sys.exit(1)
    api_key = creds.get("api_key", "")
    api_url = creds.get("api_url", "https://api.tyko-labs.com")
    # Show only the public portion (first 32 chars)
    public_id = api_key[:32] if len(api_key) >= 32 else api_key
    print(f"Logged in to {api_url}")
    print(f"API key: {public_id}...")


def main() -> None:
    args = sys.argv[1:]

    if not args or args[0] in ("login",):
        _login_command()
    elif args[0] == "logout":
        _logout_command()
    elif args[0] == "whoami":
        _whoami_command()
    else:
        print(f"Unknown command: {args[0]}", file=sys.stderr)
        print("Available commands: login, logout, whoami", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
