import os
from pathlib import Path
from pydantic_settings import BaseSettings, SettingsConfigDict

# Priority: clawagents_py/.env > parent dir .env (openclawVSdeepagents/.env)
cwd = Path.cwd()
local_env = cwd / ".env"
parent_env = cwd.parent / ".env"

env_file = None
if local_env.exists():
    env_file = local_env
elif parent_env.exists():
    env_file = parent_env

from dotenv import load_dotenv
if env_file:
    load_dotenv(env_file, override=True)


class EngineConfig(BaseSettings):
    model_config = SettingsConfigDict(
        env_file=env_file,
        env_file_encoding="utf-8",
        extra="ignore"
    )

    openai_api_key: str = ""
    openai_model: str = "gpt-5-nano"
    gemini_api_key: str = ""
    gemini_model: str = "gemini-3-flash-preview"
    provider: str = ""
    max_tokens: int = 4096
    context_window: int = 128000
    streaming: bool = True  # Default: streaming mode on (set STREAMING=0 to disable)

    def get_provider(self) -> str:
        """Explicit override via PROVIDER env var, otherwise auto-detect"""
        explicit_provider = os.getenv("PROVIDER", self.provider).lower()
        if explicit_provider in ("gemini", "openai"):
            return explicit_provider
        
        if self.openai_api_key:
            return "openai"
        elif self.gemini_api_key:
            return "gemini"
        
        return "openai"


def load_config() -> EngineConfig:
    return EngineConfig()
