"""
ProviderSettings — single source of truth for provider configuration.

Priority: DB settings → environment variables → hardcoded defaults.
Credentials: env → DB (12-factor app standard).

The caller passes a DB settings dict; this module never imports from web/
or database modules to avoid circular dependencies.
"""

from __future__ import annotations

import logging
import os
from typing import Any

logger = logging.getLogger(__name__)

# Default provider selections
PROVIDER_DEFAULTS: dict[str, str] = {
    "image": "google_flow",
    "video": "grok",
    "tts": "elevenlabs",
}

# DB setting key → env var name fallback
ENV_FALLBACKS: dict[str, str] = {
    "image_provider": "IMAGE_PROVIDER",
    "video_provider": "VIDEO_PROVIDER",
    "tts_provider": "TTS_PROVIDER",
    "pollinations_api_key": "POLLINATIONS_API_KEY",
    "pollinations_image_model": "POLLINATIONS_IMAGE_MODEL",
    "pollinations_image_width": "POLLINATIONS_IMAGE_WIDTH",
    "pollinations_image_height": "POLLINATIONS_IMAGE_HEIGHT",
    "pollinations_video_model": "POLLINATIONS_VIDEO_MODEL",
    "pollinations_video_duration": "POLLINATIONS_VIDEO_DURATION",
    "pollinations_video_aspect": "POLLINATIONS_VIDEO_ASPECT",
    "pollinations_tts_model": "POLLINATIONS_TTS_MODEL",
    "pollinations_tts_voice": "POLLINATIONS_TTS_VOICE",
    "pollinations_tts_speed": "POLLINATIONS_TTS_SPEED",
    "pollinations_tts_format": "POLLINATIONS_TTS_FORMAT",
    "leonardo_api_key": "LEONARDO_API_KEY",
    "leonardo_resolution": "LEONARDO_RESOLUTION",
    "image_model": "IMAGE_MODEL",
    "image_size": "IMAGE_SIZE",
    "image_quality": "IMAGE_QUALITY",
    "image_style": "IMAGE_STYLE",
    "google_flow_aspect_ratio": "GOOGLE_FLOW_ASPECT_RATIO",
}


class ProviderSettings:
    """Single source of truth for provider configuration.

    Priority: DB settings → environment variables → hardcoded defaults.
    Credentials: env → DB (12-factor app standard).
    """

    def __init__(self, db_settings: dict[str, str] | None = None):
        self._db = db_settings or {}

    def get_active_provider(self, provider_type: str) -> str:
        """Return active provider name for 'image', 'video', or 'tts'."""
        db_key = f"{provider_type}_provider"
        env_key = ENV_FALLBACKS.get(db_key, f"{provider_type.upper()}_PROVIDER")
        default = PROVIDER_DEFAULTS.get(provider_type, "")
        return self._db.get(db_key) or os.environ.get(env_key, "") or default

    def get(self, key: str, default: str = "") -> str:
        """Get a setting value with DB → env → default priority."""
        env_key = ENV_FALLBACKS.get(key, key.upper())
        return self._db.get(key) or os.environ.get(env_key, "") or default

    def get_credential(self, key: str, default: str = "") -> str:
        """Get a credential with env → DB priority (12-factor app)."""
        env_key = ENV_FALLBACKS.get(key, key.upper())
        return os.environ.get(env_key, "") or self._db.get(key, "") or default

    def get_provider_config(
        self, provider_type: str, provider_name: str
    ) -> dict[str, Any]:
        """Get all config for a specific provider as a dict."""
        configs: dict[tuple[str, str], dict[str, Any]] = {
            ("image", "pollinations"): {
                "api_key": self.get_credential("pollinations_api_key"),
                "model": self.get("pollinations_image_model", "flux"),
                "width": int(self.get("pollinations_image_width", "1024")),
                "height": int(self.get("pollinations_image_height", "1024")),
            },
            ("image", "dalle3"): {
                "model": self.get("image_model", "dall-e-3"),
                "size": self.get("image_size", "1792x1024"),
                "quality": self.get("image_quality", "hd"),
                "style": self.get("image_style", "natural"),
            },
            ("image", "google_flow"): {
                "aspect_ratio": self.get("google_flow_aspect_ratio", "portrait"),
            },
            ("image", "google_flow_v2"): {
                "aspect_ratio": self.get("google_flow_aspect_ratio", "portrait"),
            },
            ("video", "grok"): {},
            ("video", "leonardo"): {
                "api_key": self.get_credential("leonardo_api_key"),
                "resolution": self.get("leonardo_resolution", "720"),
            },
            ("video", "pollinations"): {
                "api_key": self.get_credential("pollinations_api_key"),
                "model": self.get("pollinations_video_model", "seedance"),
                "duration": int(self.get("pollinations_video_duration", "5")),
                "aspect_ratio": self.get("pollinations_video_aspect", "16:9"),
            },
            ("video", "google_veo"): {},
            ("video", "runway"): {},
            ("tts", "elevenlabs"): {},
            ("tts", "pollinations"): {
                "api_key": self.get_credential("pollinations_api_key"),
                "model": self.get("pollinations_tts_model", "openai"),
                "voice": self.get("pollinations_tts_voice", "nova"),
                "speed": float(self.get("pollinations_tts_speed", "1.0")),
                "audio_format": self.get("pollinations_tts_format", "mp3"),
            },
        }
        return configs.get((provider_type, provider_name), {})
