"""CLI commands for MLD platform authentication.

Provides: mld auth login, mld auth logout, mld auth status
"""

from __future__ import annotations

import argparse
import getpass
import sys

from mld_sdk.client._config import get_default_host, get_stored_token, get_stored_username


def register_auth_parser(subparsers: argparse._SubParsersAction) -> None:
    """Register the 'auth' subcommand group."""
    auth_parser = subparsers.add_parser(
        "auth",
        help="Manage platform authentication",
        description="Login, logout, and check authentication status.",
    )
    auth_sub = auth_parser.add_subparsers(dest="auth_command")

    # -- auth login --
    login_parser = auth_sub.add_parser(
        "login",
        help="Authenticate to an MLD platform instance",
        description="Login with username/password and store the token locally.",
    )
    login_parser.add_argument(
        "--url",
        help="Platform URL (e.g. http://localhost:8001)",
    )
    login_parser.add_argument(
        "--username",
        "-u",
        help="Username (prompted if not provided)",
    )

    # -- auth logout --
    logout_parser = auth_sub.add_parser(
        "logout",
        help="Clear stored credentials",
    )
    logout_parser.add_argument(
        "--url",
        help="Platform URL to logout from (defaults to current host)",
    )

    # -- auth status --
    auth_sub.add_parser(
        "status",
        help="Show current authentication status",
    )


def cmd_auth(args: argparse.Namespace) -> None:
    """Dispatch auth subcommands."""
    if args.auth_command == "login":
        _cmd_login(args)
    elif args.auth_command == "logout":
        _cmd_logout(args)
    elif args.auth_command == "status":
        _cmd_status(args)
    else:
        print("Usage: mld auth <login|logout|status>", file=sys.stderr)
        sys.exit(1)


def _cmd_login(args: argparse.Namespace) -> None:
    """Interactive login to MLD platform."""
    url = args.url or get_default_host()
    if not url:
        url = input("Platform URL: ").strip()
        if not url:
            print("Error: Platform URL is required.", file=sys.stderr)
            sys.exit(1)

    username = args.username
    if not username:
        username = input("Username: ").strip()
        if not username:
            print("Error: Username is required.", file=sys.stderr)
            sys.exit(1)

    password = getpass.getpass("Password: ")

    try:
        from mld_sdk.client import MLDClient

        client = MLDClient(base_url=url)
        result = client.login(username, password)
        user = result.get("user", {})
        print(f"Logged in as {user.get('username', username)} ({user.get('role', 'user')})")
        print(f"Host: {url}")
        client.close()
    except ImportError:
        print(
            "Error: httpx is required for the MLD client. Install with: pip install mld-sdk[client]",
            file=sys.stderr,
        )
        sys.exit(1)
    except Exception as e:
        print(f"Login failed: {e}", file=sys.stderr)
        sys.exit(1)


def _cmd_logout(args: argparse.Namespace) -> None:
    """Clear stored credentials."""
    from mld_sdk.client._config import remove_token

    url = args.url or get_default_host()
    if not url:
        print("No host configured. Nothing to do.", file=sys.stderr)
        return

    remove_token(url)
    print(f"Logged out from {url}")


def _cmd_status(args: argparse.Namespace) -> None:
    """Show current auth status."""
    host = get_default_host()
    if not host:
        print("Not logged in (no host configured)")
        print("  Run: mld auth login --url <URL>")
        return

    token = get_stored_token(host)
    username = get_stored_username(host)

    if not token:
        print(f"Host: {host}")
        print("Status: Not logged in")
        print("  Run: mld auth login")
        return

    print(f"Host: {host}")
    print(f"User: {username or 'unknown'}")
    print("Status: Authenticated")

    # Optionally verify the token is still valid
    try:
        from mld_sdk.client import MLDClient

        client = MLDClient(base_url=host)
        info = client.auth.verify()
        if info.get("valid"):
            user_info = info.get("user", {})
            role = user_info.get("role", "")
            if role:
                print(f"Role: {role}")
            expires = info.get("expires_at")
            if expires:
                print(f"Expires: {expires}")
        client.close()
    except Exception:
        print("(could not verify token — server may be unreachable)")
