"""Authentication validation helpers."""

from __future__ import annotations

from typing import Any, Dict, List

from ..adt_types import AzureDiscoveryRequest
from .azure_clients import build_environment_config, get_credential


def validate_auth(
    request: AzureDiscoveryRequest,
    probe_connectivity: bool = False,  # noqa: FBT001, FBT002
) -> Dict[str, Any]:
    """Validate credentials can acquire tokens for ARM and Microsoft Graph.

    This is meant as a lightweight preflight check for the CLI.
    """

    env_cfg = build_environment_config(request.environment)
    credential = get_credential(request, env_cfg)

    scopes: List[str] = []
    errors: List[str] = []

    # ARM
    arm_scope = env_cfg.resource_manager.rstrip("/") + "/.default"
    try:
        credential.get_token(arm_scope)
        scopes.append(arm_scope)
    except Exception as exc:  # noqa: BLE001
        errors.append(f"ARM token failed: {exc}")

    # Microsoft Graph
    graph_scope = env_cfg.graph_endpoint.rstrip("/") + "/.default"
    try:
        credential.get_token(graph_scope)
        scopes.append(graph_scope)
    except Exception as exc:  # noqa: BLE001
        errors.append(f"Graph token failed: {exc}")

    # "probe_connectivity" is a placeholder for future checks (API calls, DNS, etc.).
    # For now, token acquisition is the primary signal.

    payload: Dict[str, Any] = {
        "ok": not errors,
        "environment": request.environment.value,
        "scopes": scopes,
        "probe_connectivity": bool(probe_connectivity),
    }
    if errors:
        payload["errors"] = errors
    return payload
