"""CLI command for platform status check.

Provides: mld status
"""

from __future__ import annotations

import argparse
import sys

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


def cmd_status(args: argparse.Namespace) -> None:
    """Show platform connectivity, auth, and plugin info."""
    host = get_default_host()
    if not host:
        print("Not connected (no host configured)")
        print("  Run: mld auth login --url <URL>")
        return

    print(f"Host: {host}")

    username = get_stored_username(host)
    token = get_stored_token(host)
    if username and token:
        print(f"User: {username}")
    else:
        print("Auth: Not logged in")
        return

    # Check platform health and plugins
    try:
        from mld_sdk.client import MLDClient

        client = MLDClient(base_url=host)

        # Health check
        try:
            health = client._http.get("/health")
            print("Platform: Online")
            plugins = health.get("plugins", [])
            if plugins:
                print(f"Plugins: {len(plugins)} loaded")
                for p in plugins:
                    if isinstance(p, dict):
                        name = p.get("name", "?")
                        version = p.get("version", "")
                        ptype = p.get("plugin_type", "")
                        print(f"  - {name} {version} ({ptype})")
                    else:
                        print(f"  - {p}")
        except Exception:
            print("Platform: Unreachable")

        # Verify auth
        try:
            info = client.auth.verify()
            if info.get("valid"):
                print("Token: Valid")
                expires = info.get("expires_at")
                if expires:
                    print(f"Expires: {expires}")
            else:
                print("Token: Invalid (re-login required)")
        except Exception:
            print("Token: Could not verify")

        client.close()
    except ImportError:
        print("(install mld-sdk[client] for full status)")
    except Exception as e:
        print(f"Error: {e}")
