"""Multi-provider AI service router."""

from typing import Optional, Dict
from ..config import (
    load_config,
    get_api_key,
    get_anthropic_api_key,
    get_eden_api_key,
    get_perplexity_api_key,
    get_provider_settings
)


def get_analysis_client(provider: str = None):
    """
    Get the appropriate analysis client based on provider setting.

    Args:
        provider: Override provider (uses settings if None)

    Returns:
        Tuple of (provider_name, api_key, analyze_function)
    """
    if provider is None:
        settings = get_provider_settings()
        provider = settings.get("analysis_provider", "openai")

    if provider == "openai":
        api_key = get_api_key()
        if not api_key:
            raise ValueError("OpenAI API key not configured")
        return "openai", api_key

    elif provider == "anthropic":
        api_key = get_anthropic_api_key()
        if not api_key:
            raise ValueError("Anthropic API key not configured")
        return "anthropic", api_key

    elif provider == "eden":
        api_key = get_eden_api_key()
        if not api_key:
            raise ValueError("Eden.ai API key not configured")
        return "eden", api_key

    else:
        raise ValueError(f"Unknown provider: {provider}")


def analyze_with_provider(
    text: str,
    analysis_type: str = "comprehensive",
    provider: str = None
) -> dict:
    """
    Analyze text using the configured provider.

    Args:
        text: Text to analyze
        analysis_type: Type of analysis
        provider: Override provider (uses settings if None)

    Returns:
        Analysis results
    """
    provider_name, api_key = get_analysis_client(provider)

    if provider_name == "openai":
        from .analyzer import analyze_transcription
        return analyze_transcription(text, api_key, analysis_type)

    elif provider_name == "anthropic":
        from .anthropic_ai import analyze_with_claude_sync
        result = analyze_with_claude_sync(text, api_key, analysis_type)
        return {"analysis": result}

    elif provider_name == "eden":
        from .eden_ai import comprehensive_analysis_eden
        import asyncio
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            result = loop.run_until_complete(
                comprehensive_analysis_eden(text, api_key)
            )
        finally:
            loop.close()
        return result


def critique_with_provider(
    text: str,
    original_analysis: str,
    provider: str = None
) -> str:
    """
    Critique an analysis using the configured provider.

    Args:
        text: Original transcription
        original_analysis: The analysis to critique
        provider: Override provider (uses settings if None)

    Returns:
        Critique text
    """
    if provider is None:
        settings = get_provider_settings()
        provider = settings.get("critique_provider", "anthropic")

    if provider == "anthropic":
        api_key = get_anthropic_api_key()
        if not api_key:
            raise ValueError("Anthropic API key not configured")
        from .anthropic_ai import critique_with_claude_sync
        return critique_with_claude_sync(text, original_analysis, api_key)

    elif provider == "openai":
        api_key = get_api_key()
        if not api_key:
            raise ValueError("OpenAI API key not configured")
        from openai import OpenAI
        client = OpenAI(api_key=api_key)
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {
                    "role": "system",
                    "content": """You are a critical analyst. Review the provided analysis and:
1. Identify any inaccuracies or gaps
2. Provide a more comprehensive analysis
3. Note claims that need fact-checking
Be constructive but thorough."""
                },
                {
                    "role": "user",
                    "content": f"Original Text:\n{text[:5000]}\n\nAnalysis to critique:\n{original_analysis}"
                }
            ],
            max_tokens=2000
        )
        return response.choices[0].message.content.strip()

    elif provider == "eden":
        api_key = get_eden_api_key()
        if not api_key:
            raise ValueError("Eden.ai API key not configured")
        from .eden_ai import chat_with_eden
        import asyncio

        messages = [{
            "role": "user",
            "content": f"""Please critique this analysis:

Original Text (excerpt):
{text[:3000]}

Analysis:
{original_analysis}

Provide:
1. A critique of the analysis
2. An improved version
3. Key points to fact-check"""
        }]

        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            result = loop.run_until_complete(chat_with_eden(messages, api_key))
        finally:
            loop.close()

        # Extract response from Eden format
        for provider_result in result.values():
            if isinstance(provider_result, dict) and 'generated_text' in provider_result:
                return provider_result['generated_text']
        return str(result)

    else:
        raise ValueError(f"Unknown critique provider: {provider}")


def find_resources_with_provider(
    topic: str,
    context: str = None,
    provider: str = None
) -> dict:
    """
    Find external resources using the configured provider.

    Args:
        topic: Topic to search for
        context: Optional context from transcription
        provider: Override provider (uses settings if None)

    Returns:
        Resources and references
    """
    if provider is None:
        settings = get_provider_settings()
        provider = settings.get("resources_provider", "perplexity")

    if provider == "perplexity":
        api_key = get_perplexity_api_key()
        if not api_key:
            raise ValueError("Perplexity API key not configured")
        from .research import find_book_references
        import asyncio
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            result = loop.run_until_complete(
                find_book_references(topic, api_key, context)
            )
        finally:
            loop.close()
        return result

    elif provider == "eden":
        api_key = get_eden_api_key()
        if not api_key:
            raise ValueError("Eden.ai API key not configured")
        from .eden_ai import chat_with_eden
        import asyncio

        query = f"Find books, articles, and academic resources about: {topic}"
        if context:
            query += f"\n\nContext: {context[:1000]}"

        messages = [{
            "role": "user",
            "content": f"""{query}

Please provide:
1. Relevant books (title, author, year)
2. Academic papers or articles
3. Online resources or courses
4. Why each resource is relevant"""
        }]

        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            result = loop.run_until_complete(chat_with_eden(messages, api_key))
        finally:
            loop.close()

        # Extract and format response
        response_text = ""
        for provider_result in result.values():
            if isinstance(provider_result, dict) and 'generated_text' in provider_result:
                response_text = provider_result['generated_text']
                break

        return {
            "resources": response_text,
            "provider": "eden",
            "topic": topic
        }

    else:
        raise ValueError(f"Unknown resources provider: {provider}")


def answer_question_with_provider(
    text: str,
    question: str,
    provider: str = None
) -> dict:
    """
    Answer a question using the configured provider.

    Args:
        text: Transcription text
        question: User's question
        provider: Override provider (uses settings if None)

    Returns:
        Answer and metadata
    """
    provider_name, api_key = get_analysis_client(provider)

    if provider_name == "openai":
        from .analyzer import answer_question
        answer = answer_question(text, api_key, question)
        return {"answer": answer, "provider": "openai"}

    elif provider_name == "anthropic":
        from .anthropic_ai import chat_with_claude
        import asyncio

        messages = [{
            "role": "user",
            "content": f"Based on this transcription:\n\n{text[:8000]}\n\nQuestion: {question}"
        }]

        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            result = loop.run_until_complete(
                chat_with_claude(
                    messages,
                    api_key,
                    system="Answer questions based only on the provided transcription. Be accurate and cite relevant parts."
                )
            )
        finally:
            loop.close()

        return {"answer": result.get("response", ""), "provider": "anthropic"}

    elif provider_name == "eden":
        from .eden_ai import chat_with_eden
        import asyncio

        messages = [{
            "role": "user",
            "content": f"Transcription:\n{text[:6000]}\n\nQuestion: {question}"
        }]

        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            result = loop.run_until_complete(chat_with_eden(messages, api_key))
        finally:
            loop.close()

        answer = ""
        for provider_result in result.values():
            if isinstance(provider_result, dict) and 'generated_text' in provider_result:
                answer = provider_result['generated_text']
                break

        return {"answer": answer, "provider": "eden"}


def comprehensive_qa(
    text: str,
    question: str,
    find_references: bool = True
) -> dict:
    """
    Comprehensive Q&A with optional critique and references.

    Args:
        text: Transcription text
        question: User's question
        find_references: Whether to find external references

    Returns:
        Complete Q&A response with all provider results
    """
    settings = get_provider_settings()
    result = {}

    # 1. Get initial answer from analysis provider
    try:
        answer_result = answer_question_with_provider(text, question)
        result["initial_answer"] = answer_result
    except Exception as e:
        result["initial_answer_error"] = str(e)

    # 2. Get critique from critique provider (if different from analysis)
    if settings["critique_provider"] != settings["analysis_provider"]:
        try:
            initial_answer = result.get("initial_answer", {}).get("answer", "")
            if initial_answer:
                critique = critique_with_provider(text, initial_answer)
                result["critique"] = critique
        except Exception as e:
            result["critique_error"] = str(e)

    # 3. Find external references if requested
    if find_references:
        try:
            # Extract topic from question for search
            resources = find_resources_with_provider(question, text[:2000])
            result["references"] = resources
        except Exception as e:
            result["references_error"] = str(e)

    return result
