"""
LLM Provider — factory with bridge to SOPHOS provider registry.

When called, returns a BiasClear-compatible LLMProvider that delegates
to whichever SOPHOS provider is currently active. This ensures the
BiasClear engine uses the same model as the SOPHOS pipeline.

Falls back to direct GeminiProvider if SOPHOS providers aren't available.
"""

import os
from ..llm import LLMProvider


class _BiasClearBridge(LLMProvider):
    """
    Bridges SOPHOS's SOPHOSProvider to BiasClear's LLMProvider interface.

    SOPHOSProvider.ask(prompt, system_instruction, response_mime_type, ...)
    → LLMProvider.generate(prompt, system_instruction, temperature, json_mode)
    """

    def __init__(self, sophos_provider):
        self._provider = sophos_provider

    async def generate(
        self,
        prompt: str,
        system_instruction=None,
        temperature: float = 0.7,
        json_mode: bool = False,
    ) -> str:
        return await self._provider.ask(
            prompt=prompt,
            system_instruction=system_instruction,
            response_mime_type="application/json" if json_mode else None,
            temperature=temperature,
        )


def get_provider(provider_name: str = None) -> LLMProvider:
    """
    Factory — returns a BiasClear-compatible LLM provider.

    Bridges to the active SOPHOS provider by default, falling back
    to direct GeminiProvider if the SOPHOS provider layer isn't
    initialized.
    """
    try:
        from app.providers import get_active_provider
        sophos = get_active_provider()
        return _BiasClearBridge(sophos)
    except Exception:
        # Fallback: direct GeminiProvider (standalone BiasClear mode)
        from ..llm.gemini import GeminiProvider
        return GeminiProvider()

