import os
import logging
from typing import Optional

# Versuche Pydantic zu nutzen, Fallback auf os.environ
try:
    from pydantic_settings import BaseSettings
    from pydantic import Extra
    
    class Settings(BaseSettings):
        # App Info
        APP_NAME: str = "Company Explorer"
        VERSION: str = "0.7.3"
        DEBUG: bool = True
        
        # Database (FINAL CORRECT PATH for Docker Container)
        DATABASE_URL: str = "sqlite:////data/companies_v3_fixed_2.db"
        
        # API Keys
        GEMINI_API_KEY: Optional[str] = None
        OPENAI_API_KEY: Optional[str] = None
        SERP_API_KEY: Optional[str] = None
        
        # Paths
        LOG_DIR: str = "/app/Log_from_docker"

        # Public URL
        APP_BASE_URL: str = "http://localhost:8090"

        class Config:
            env_file = ".env"
            extra = 'ignore'

    settings = Settings()

except ImportError:
    # Fallback wenn pydantic-settings nicht installiert ist
    class FallbackSettings:
        APP_NAME = "Company Explorer"
        VERSION = "0.7.3"
        DEBUG = True
        # HARDCODED PATH TO FORCE CONSISTENCY
        DATABASE_URL = "sqlite:////data/companies_v3_fixed_2.db" 
        GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
        OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
        SERP_API_KEY = os.getenv("SERP_API_KEY")
        LOG_DIR = "/app/Log_from_docker"
    
    settings = FallbackSettings()

# Ensure Log Dir
try:
    os.makedirs(settings.LOG_DIR, exist_ok=True)
except FileExistsError:
    pass
except Exception as e:
    logging.warning(f"Could not create log directory {settings.LOG_DIR}: {e}")

# API Key Loading Helper (from file if env missing)
def load_api_key_from_file(filename: str) -> Optional[str]:
    try:
        if os.path.exists(filename):
            with open(filename, 'r') as f:
                return f.read().strip()
    except Exception as e:
        logging.warning(f"Could not load key from {filename}: {e}")
    return None

# Auto-load keys assuming the app runs in the Docker container's /app context
if not settings.GEMINI_API_KEY:
    settings.GEMINI_API_KEY = load_api_key_from_file("/app/gemini_api_key.txt")

if not settings.SERP_API_KEY:
    settings.SERP_API_KEY = load_api_key_from_file("/app/serpapikey.txt")