"""
Environment variable backend.

Reads secrets from environment variables. Always available, read-only.
First-class support for CI/CD pipelines.

Naming convention: {PREFIX}{KEY}
Example: G_GREMLIN_APOLLO_API_KEY, G_GREMLIN_ZENDESK_API_TOKEN
"""

from __future__ import annotations

import os
from typing import List, Optional

from g_gremlin.credentials.models import (
    INTEGRATION_REGISTRY,
    SecretSource,
    SecretValue,
)


class EnvVarBackend:
    """
    Backend that reads secrets from environment variables.

    Naming convention: {PREFIX}{KEY}
    Example: G_GREMLIN_APOLLO_API_KEY, G_GREMLIN_ZENDESK_API_TOKEN

    This backend is always available and is the primary mechanism for CI.
    """

    @property
    def source(self) -> SecretSource:
        return SecretSource.ENV_VAR

    @property
    def is_available(self) -> bool:
        return True  # Always available

    @property
    def is_read_only(self) -> bool:
        return True  # Cannot write to env vars from within the process

    def get_secret(
        self,
        integration: str,
        key: str,
        profile: str = "default",
    ) -> Optional[SecretValue]:
        """
        Get secret from environment variable.

        Tries the integration-specific env var name first.
        """
        spec = INTEGRATION_REGISTRY.get(integration)
        if spec is None:
            # Fallback naming for unknown integrations
            env_name = f"G_GREMLIN_{integration.upper()}_{key.upper()}"
        else:
            env_name = spec.get_env_var_name(key)

        value = os.environ.get(env_name)
        if value is None or value.strip() == "":
            return None

        return SecretValue(
            value=value.strip(),
            source=SecretSource.ENV_VAR,
            integration=integration,
            key=key,
            profile=profile,
            metadata={"env_var": env_name},
        )

    def set_secret(
        self,
        integration: str,
        key: str,
        value: str,
        profile: str = "default",
    ) -> None:
        """Not supported - environment variables are read-only."""
        raise NotImplementedError(
            "Cannot write to environment variables. "
            "Set them in your shell or CI configuration."
        )

    def delete_secret(
        self,
        integration: str,
        key: str,
        profile: str = "default",
    ) -> bool:
        """Not supported - environment variables are read-only."""
        return False

    def list_secrets(
        self,
        integration: Optional[str] = None,
        profile: str = "default",
    ) -> List[tuple]:
        """List secrets that are set via env vars."""
        found: List[tuple] = []

        if integration:
            specs = [INTEGRATION_REGISTRY[integration]] if integration in INTEGRATION_REGISTRY else []
        else:
            specs = list(INTEGRATION_REGISTRY.values())

        for spec in specs:
            for key in spec.get_all_keys():
                env_name = spec.get_env_var_name(key)
                if os.environ.get(env_name):
                    found.append((spec.name, key))

        return found
