"""Configuration from environment variables."""
import os
from dataclasses import dataclass
from typing import Optional


@dataclass
class RagSaaSConfig:
    """Configuration for RagSaaS SDK."""
    api_key: str
    tenant_id: str
    base_url: str = "https://api.ragsaas.com"
    collection: Optional[str] = None
    top_k: int = 5
    threshold: Optional[float] = None
    use_hybrid: bool = False

    @classmethod
    def from_env(cls, require_tenant: bool = False) -> "RagSaaSConfig":
        """Create config from environment variables.

        Args:
            require_tenant: If True, raises error when RAGSAAS_TENANT_ID is not set.
                          For decorators/wrappers, tenant is passed explicitly so this is False.
        """
        api_key = os.environ.get("RAGSAAS_API_KEY")
        if not api_key:
            raise ValueError(
                "RAGSAAS_API_KEY environment variable is required. "
                "Get your API key at https://ragsaas.com/dashboard"
            )

        tenant_id = os.environ.get("RAGSAAS_TENANT_ID", "")
        if require_tenant and not tenant_id:
            raise ValueError(
                "RAGSAAS_TENANT_ID environment variable is required. "
                "This is your tenant/customer identifier."
            )

        return cls(
            api_key=api_key,
            tenant_id=tenant_id,
            base_url=os.environ.get("RAGSAAS_BASE_URL", "https://api.ragsaas.com"),
            collection=os.environ.get("RAGSAAS_COLLECTION"),
            top_k=int(os.environ.get("RAGSAAS_TOP_K", "5")),
            threshold=float(os.environ.get("RAGSAAS_THRESHOLD")) if os.environ.get("RAGSAAS_THRESHOLD") else None,
            use_hybrid=os.environ.get("RAGSAAS_USE_HYBRID", "").lower() in ("true", "1", "yes"),
        )


def get_config(require_tenant: bool = False, **overrides) -> RagSaaSConfig:
    """Get configuration with optional overrides.

    Args:
        require_tenant: If True, raises error when tenant_id is not available.
        **overrides: Override any config value (api_key, tenant_id, base_url, etc.)
    """
    # Check if tenant_id is being provided in overrides
    has_tenant_override = overrides.get("tenant_id") is not None
    config = RagSaaSConfig.from_env(require_tenant=require_tenant and not has_tenant_override)

    for key, value in overrides.items():
        if hasattr(config, key) and value is not None:
            setattr(config, key, value)
    return config
