"""
Direct access authentication validation for v1 config.

This module owns the canonical set of v1 authenticators that support direct
access and provides a reusable validation helper.

DA_SUPPORTED_AUTHENTICATORS is the single source of truth — both the
translator (v1_to_v0_translator.py) and the v1 wiring layer
(client/wiring/wiring.py) import from here.

When v0 executors are fully migrated, import validate_direct_access_auth
from here instead of from v1_to_v0_translator (which will be deleted).
"""

from typing import Any, Dict

from .config import Config

# v1 authenticator names (as written in raiconfig.yaml) that support direct access.
# Imported by client/wiring/wiring.py — do not duplicate.
DA_SUPPORTED_AUTHENTICATORS = frozenset({
    "jwt",
    "oauth_authorization_code",
    "programmatic_access_token",
})


def validate_direct_access_auth(config: Config, result: Dict[str, Any]) -> None:
    """
    Validate that the connection authenticator supports direct access.

    If direct_access=True but the v1 authenticator is not in
    DA_SUPPORTED_AUTHENTICATORS, emits a v1-formatted RAIWarning and sets
    result["use_direct_access"]=False so that any downstream v0 code never
    fires its own (v0-named) warning.

    Args:
        config: V1 Config instance.
        result: Output dict being built (modified in-place on failure).
    """
    if not config.direct_access:
        return

    from .connections.snowflake import SnowflakeConnectionBase

    try:
        conn = config.get_default_connection()
    except Exception:
        return

    if not isinstance(conn, SnowflakeConnectionBase):
        return

    authenticator = getattr(conn, "authenticator", None)
    if authenticator in DA_SUPPORTED_AUTHENTICATORS:
        return

    from relationalai.util.error import warn
    valid_rich = ", ".join(f"[cyan]{a}[/cyan]" for a in sorted(DA_SUPPORTED_AUTHENTICATORS))
    warn(
        "DirectAccessInvalidAuth",
        f"Authenticator '{authenticator}' does not support direct access.",
        parts=[
            f"[cyan]{authenticator}[/cyan] does not support [cyan]direct_access: true[/cyan]. "
            f"Falling back to [cyan]direct_access: false[/cyan].",
            f"Supported authenticators: {valid_rich}.",
        ],
    )
    result["use_direct_access"] = False
