"""``mgf-cloud manager`` — read the Infomaniak Manager account (hosting / DNS).

Distinct from the OpenStack ``provider``/``vm``/… verbs: the Manager API governs
the *account's* products (web hosting, domains, DNS) and authenticates with a
Bearer token (``--token-file`` or ``$MGF_INFOMANIAK_TOKEN``), not clouds.yaml.
Read-only. ``--provider fake`` exercises the surface with seeded data — no token,
no network — so the command is demoable + testable offline.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

from mgf.cloud.cli._output import emit
from mgf.cloud.manager import get_manager, load_manager_credentials

if TYPE_CHECKING:
    import argparse

    from mgf.cloud.manager.base import ManagerApi

__all__ = ["run_manager"]


def _resolve_manager(args: argparse.Namespace) -> ManagerApi:
    if args.manager_provider == "fake":
        return get_manager("fake")
    credentials = load_manager_credentials(token_file=args.token_file)
    return get_manager("infomaniak", credentials)


def run_manager(args: argparse.Namespace) -> int:
    """Argparse callback for the ``manager`` subcommand group."""
    manager = _resolve_manager(args)
    as_json = bool(getattr(args, "as_json", False))
    action = args.action
    if action == "products":
        emit(list(manager.list_products()), as_json=as_json)
    elif action == "hostings":
        emit(list(manager.list_web_hostings()), as_json=as_json)
    elif action == "hosting":
        emit(manager.get_web_hosting(args.hosting_id), as_json=as_json)
    elif action == "sites":
        emit(list(manager.list_sites(args.hosting_id)), as_json=as_json)
    elif action == "dns":
        emit(list(manager.list_dns_records(args.fqdn)), as_json=as_json)
    else:  # pragma: no cover - argparse 'required=True' prevents this
        return 2
    return 0
