"""The ``mgf-cloud-web`` command — launch the local cloud console.

The whole distribution is the web GUI, so the command launches it directly (no
subcommands). Credential resolution mirrors ``mgf-cloud``: ``--clouds-yaml`` →
``$MGF_CLOUD_CLOUDS_YAML`` → ``OS_*`` env → standard ``clouds.yaml`` paths, with
``--cloud`` selecting the entry (default ``openstack``).
"""

from __future__ import annotations

import argparse
import sys
from typing import TYPE_CHECKING

from mgf.cloud import config
from mgf.cloud.exceptions import (
    ConfigError,
    OperationError,
    ProviderError,
    ResourceAlreadyExistsError,
    ResourceNotFoundError,
)
from mgf.cloud.providers import get_provider
from mgf.common.observability import get_logger

from mgf.cloud_web import __version__

if TYPE_CHECKING:
    from mgf.cloud.providers.base import CloudProvider

LOG = get_logger(__name__)

_CLOUD_ERRORS = (
    ConfigError,
    ProviderError,
    ResourceNotFoundError,
    ResourceAlreadyExistsError,
    OperationError,
)


def build_parser() -> argparse.ArgumentParser:
    """Build the ``mgf-cloud-web`` argument parser."""
    parser = argparse.ArgumentParser(
        prog="mgf-cloud-web",
        description="Magogi Foundation cloud console — local single-user web GUI.",
    )
    parser.add_argument("--version", action="version", version=f"mgf-cloud-web {__version__}")
    parser.add_argument(
        "--provider",
        default="infomaniak",
        help="cloud provider (default: infomaniak; 'fake' for a local dry test)",
    )
    parser.add_argument("--clouds-yaml", default=None, help="path to an OpenStack clouds.yaml")
    parser.add_argument(
        "--cloud",
        default="openstack",
        help=(
            "clouds.yaml entry to use (default: openstack). Infomaniak's downloaded "
            "file names its entry PCP-<id>-<region>, e.g. PCP-HOESFJV-dc3-a"
        ),
    )
    parser.add_argument("--host", default="127.0.0.1", help="bind address (default: localhost)")
    parser.add_argument("--port", type=int, default=8787, help="bind port (default: 8787)")
    return parser


def _resolve_provider(args: argparse.Namespace) -> CloudProvider:
    if args.provider == "fake":
        return get_provider("fake")
    credentials = config.load(clouds_yaml=args.clouds_yaml, cloud=args.cloud)
    return get_provider(args.provider, credentials)


def main(argv: list[str] | None = None) -> int:
    """Entry point: resolve the provider and serve the GUI."""
    args = build_parser().parse_args(argv)
    try:
        provider = _resolve_provider(args)
        from mgf.cloud_web.web import serve

        serve(provider, args.host, args.port)
    except _CLOUD_ERRORS as exc:
        LOG.warning("mgf-cloud-web command failed: %s", exc)
        print(f"mgf-cloud-web: {exc}", file=sys.stderr)
        return 1
    return 0
