"""Configuration module for trax project
Loads environment variables from the root project's .env file.
"""

import os
from pathlib import Path
from typing import Optional

from dotenv import load_dotenv

# Find the root project directory (two levels up from src/)
TRAX_DIR = Path(__file__).parent.parent
ROOT_PROJECT_DIR = TRAX_DIR.parent.parent

# Load environment variables from root project
ROOT_ENV_FILE = ROOT_PROJECT_DIR / ".env"
LOCAL_ENV_FILE = TRAX_DIR / ".env.local"

# Load root .env file first
if ROOT_ENV_FILE.exists():
    load_dotenv(ROOT_ENV_FILE)
    print(f"✅ Loaded environment from: {ROOT_ENV_FILE}")
else:
    print(f"⚠️  Root .env file not found at: {ROOT_ENV_FILE}")

# Load local overrides if they exist
if LOCAL_ENV_FILE.exists():
    load_dotenv(LOCAL_ENV_FILE, override=True)
    print(f"✅ Loaded local overrides from: {LOCAL_ENV_FILE}")


class Config:
    """Centralized configuration for the trax project."""

    # Project paths
    PROJECT_ROOT = TRAX_DIR
    DATA_DIR = TRAX_DIR / "data"

    # API Keys - AI Services
    ANTHROPIC_API_KEY: Optional[str] = os.getenv("ANTHROPIC_API_KEY")
    DEEPSEEK_API_KEY: Optional[str] = os.getenv("DEEPSEEK_API_KEY")
    DEEPSEEK_API_KEY_1: Optional[str] = os.getenv("DEEPSEEK_API_KEY_1")
    DEEPSEEK_API_KEY_2: Optional[str] = os.getenv("DEEPSEEK_API_KEY_2")
    DEEPSEEK_API_KEY_3: Optional[str] = os.getenv("DEEPSEEK_API_KEY_3")
    OPENAI_API_KEY: Optional[str] = os.getenv("OPENAI_API_KEY")
    OPENROUTER_API_KEY: Optional[str] = os.getenv("OPENROUTER_API_KEY")
    PERPLEXITY_API_KEY: Optional[str] = os.getenv("PERPLEXITY_API_KEY")

    # API Keys - Google Services
    GOOGLE_CLIENT_ID: Optional[str] = os.getenv("GOOGLE_CLIENT_ID")
    GOOGLE_CLIENT_SECRET: Optional[str] = os.getenv("GOOGLE_CLIENT_SECRET")
    GOOGLE_API_KEY: Optional[str] = os.getenv("GOOGLE_API_KEY")

    # API Keys - Other Services
    SLACK_BOT_TOKEN: Optional[str] = os.getenv("SLACK_BOT_TOKEN")
    SLACK_APP_TOKEN: Optional[str] = os.getenv("SLACK_APP_TOKEN")
    GITHUB_PERSONAL_ACCESS: Optional[str] = os.getenv("GITHUB_PERSONAL_ACCESS")
    GITEA_API_KEY: Optional[str] = os.getenv("GITEA_API_KEY")

    # Directus Configuration
    DIRECTUS_URL: str = os.getenv("DIRECTUS_URL", "https://enias.zeabur.app")
    DIRECTUS_TOKEN: Optional[str] = os.getenv("DIRECTUS_TOKEN")

    # YouTube API
    YOUTUBE_API_KEY: Optional[str] = os.getenv("YOUTUBE_API_KEY")

    # Database Configuration
    DATABASE_URL: str = os.getenv("DATABASE_URL", "postgresql://localhost/trax")
    DATABASE_POOL_SIZE: int = int(os.getenv("DATABASE_POOL_SIZE", "10"))
    DATABASE_MAX_OVERFLOW: int = int(os.getenv("DATABASE_MAX_OVERFLOW", "20"))
    DATABASE_POOL_TIMEOUT: int = int(os.getenv("DATABASE_POOL_TIMEOUT", "30"))
    DATABASE_POOL_RECYCLE: int = int(os.getenv("DATABASE_POOL_RECYCLE", "3600"))

    # Default AI Model Settings
    DEEPSEEK_MODEL: str = os.getenv("DEEPSEEK_MODEL", "deepseek-chat")
    ANTHROPIC_MODEL: str = os.getenv("ANTHROPIC_MODEL", "claude-3-5-haiku-20241022")
    OPENAI_MODEL: str = os.getenv("OPENAI_MODEL", "gpt-4")

    @classmethod
    def validate_required_keys(cls, required_keys: list[str]) -> bool:
        """Validate that required API keys are present.

        Args:
            required_keys: List of required environment variable names

        Returns:
            True if all required keys are present, False otherwise

        """
        missing_keys = []
        for key in required_keys:
            if not getattr(cls, key, None):
                missing_keys.append(key)

        if missing_keys:
            print(f"❌ Missing required API keys: {', '.join(missing_keys)}")
            return False

        return True

    @classmethod
    def get_available_ai_services(cls) -> list[str]:
        """Get list of available AI services based on API keys."""
        services = []
        if cls.ANTHROPIC_API_KEY:
            services.append("anthropic")
        if cls.DEEPSEEK_API_KEY:
            services.append("deepseek")
        if cls.OPENAI_API_KEY:
            services.append("openai")
        if cls.OPENROUTER_API_KEY:
            services.append("openrouter")
        if cls.PERPLEXITY_API_KEY:
            services.append("perplexity")
        return services

    @classmethod
    def display_config_status(cls):
        """Display current configuration status."""
        print("\n🔧 Trax Configuration Status")
        print("=" * 40)
        print(f"Root .env: {'✅' if ROOT_ENV_FILE.exists() else '❌'} {ROOT_ENV_FILE}")
        print(f"Local .env: {'✅' if LOCAL_ENV_FILE.exists() else '❌'} {LOCAL_ENV_FILE}")
        print(f"\n📚 Available AI Services: {', '.join(cls.get_available_ai_services())}")
        print(f"📁 Data Directory: {cls.DATA_DIR}")
        print("=" * 40)


# Create convenience instance
config = Config()

# Export commonly used values
ANTHROPIC_API_KEY = config.ANTHROPIC_API_KEY
DEEPSEEK_API_KEY = config.DEEPSEEK_API_KEY
OPENAI_API_KEY = config.OPENAI_API_KEY
OPENROUTER_API_KEY = config.OPENROUTER_API_KEY
