"""Research service for finding references and sources using multiple AI providers."""

import os
import httpx
from typing import Optional, List, Dict
from openai import OpenAI


async def search_with_perplexity(
    query: str,
    api_key: str,
    context: str = None
) -> Dict:
    """
    Search for references and sources using Perplexity API.

    Args:
        query: The search query or question
        api_key: Perplexity API key
        context: Optional context from transcription

    Returns:
        Dict with answer, citations, and sources
    """
    url = "https://api.perplexity.ai/chat/completions"

    system_prompt = """You are a research assistant that finds credible sources and references.
When answering questions, always:
1. Cite specific books, academic papers, articles, or authoritative sources
2. Include author names and publication years when available
3. Distinguish between primary sources and secondary commentary
4. Note when information comes from the provided context vs external sources
5. Be honest about certainty levels and limitations"""

    messages = [
        {"role": "system", "content": system_prompt}
    ]

    if context:
        messages.append({
            "role": "user",
            "content": f"Context from transcription:\n{context[:8000]}\n\nBased on this context and your knowledge, {query}"
        })
    else:
        messages.append({"role": "user", "content": query})

    async with httpx.AsyncClient(timeout=60.0) as client:
        response = await client.post(
            url,
            headers={
                "Authorization": f"Bearer {api_key}",
                "Content-Type": "application/json"
            },
            json={
                "model": "llama-3.1-sonar-large-128k-online",
                "messages": messages,
                "return_citations": True,
                "return_related_questions": True
            }
        )
        response.raise_for_status()
        data = response.json()

    answer = data["choices"][0]["message"]["content"]
    citations = data.get("citations", [])
    related = data.get("related_questions", [])

    return {
        "answer": answer,
        "citations": citations,
        "related_questions": related,
        "provider": "perplexity"
    }


def answer_with_chatgpt(
    question: str,
    transcription_text: str,
    api_key: str
) -> Dict:
    """
    Answer a question about the transcription using ChatGPT.

    Args:
        question: The user's question
        transcription_text: The transcription text to analyze
        api_key: OpenAI API key

    Returns:
        Dict with answer and key points
    """
    client = OpenAI(api_key=api_key)

    # Truncate if too long
    max_chars = 40000
    if len(transcription_text) > max_chars:
        transcription_text = transcription_text[:max_chars] + "\n\n[... content truncated ...]"

    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "system",
                "content": """You are a helpful assistant that answers questions about transcriptions.
Base your answers ONLY on the content provided in the transcription.
If the answer cannot be found in the transcription, say so clearly.
Be concise but thorough. Respond in the same language as the question.

Format your response as:
1. Direct answer to the question
2. Key quotes or timestamps from the transcription that support your answer
3. Any caveats or limitations"""
            },
            {
                "role": "user",
                "content": f"Transcription:\n{transcription_text}\n\nQuestion: {question}"
            }
        ],
        max_tokens=1500,
        temperature=0.3
    )

    return {
        "answer": response.choices[0].message.content.strip(),
        "provider": "chatgpt",
        "based_on": "transcription_only"
    }


async def comprehensive_qa(
    question: str,
    transcription_text: str,
    openai_api_key: str,
    perplexity_api_key: str = None,
    find_references: bool = True
) -> Dict:
    """
    Comprehensive Q&A that combines ChatGPT analysis with Perplexity research.

    Args:
        question: The user's question
        transcription_text: The transcription text
        openai_api_key: OpenAI API key
        perplexity_api_key: Optional Perplexity API key for finding references
        find_references: Whether to search for external references

    Returns:
        Dict with answers from both providers and combined insights
    """
    result = {
        "question": question,
        "transcription_answer": None,
        "references": None,
        "combined_analysis": None
    }

    # Get answer from ChatGPT based on transcription
    chatgpt_response = answer_with_chatgpt(question, transcription_text, openai_api_key)
    result["transcription_answer"] = chatgpt_response

    # If Perplexity key provided and references requested, find external sources
    if perplexity_api_key and find_references:
        try:
            # Create a research query based on the question and context
            context_summary = transcription_text[:2000] if len(transcription_text) > 2000 else transcription_text

            research_query = f"""Find academic sources, books, and authoritative references related to this question: {question}

Look for:
- Relevant books and their authors
- Academic papers or studies
- Expert opinions from credible sources
- Historical context if applicable"""

            perplexity_response = await search_with_perplexity(
                research_query,
                perplexity_api_key,
                context_summary
            )
            result["references"] = perplexity_response

            # Generate combined analysis using ChatGPT
            client = OpenAI(api_key=openai_api_key)
            combined = client.chat.completions.create(
                model="gpt-4o-mini",
                messages=[
                    {
                        "role": "system",
                        "content": """You are a research analyst that synthesizes information from multiple sources.
Compare and critique the answers provided, noting:
1. Where they agree and disagree
2. What the transcription claims vs what external sources say
3. Gaps in information or areas needing further research
4. Overall assessment of accuracy and completeness"""
                    },
                    {
                        "role": "user",
                        "content": f"""Question: {question}

Answer based on transcription:
{chatgpt_response['answer']}

External research and references:
{perplexity_response['answer']}

Citations found: {perplexity_response.get('citations', [])}

Please provide a combined analysis that critiques both sources and provides the most accurate answer."""
                    }
                ],
                max_tokens=1500,
                temperature=0.5
            )
            result["combined_analysis"] = combined.choices[0].message.content.strip()

        except Exception as e:
            result["references_error"] = str(e)

    return result


def find_book_references(
    topic: str,
    api_key: str,
    context: str = None
) -> Dict:
    """
    Find book recommendations related to a topic using ChatGPT.
    Fallback when Perplexity is not available.

    Args:
        topic: The topic to find books about
        api_key: OpenAI API key
        context: Optional context from transcription

    Returns:
        Dict with book recommendations
    """
    client = OpenAI(api_key=api_key)

    prompt = f"Based on this topic: {topic}"
    if context:
        prompt = f"Based on this transcription context:\n{context[:3000]}\n\nAnd this topic: {topic}"

    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "system",
                "content": """You are a knowledgeable librarian and research assistant.
When recommending books or resources:
1. Suggest 3-5 relevant books with full titles and authors
2. Briefly explain why each book is relevant
3. Include publication year if you're confident about it
4. Mention the credibility/reputation of each source
5. Note any seminal works or "must-reads" in the field
6. If applicable, suggest academic papers or articles too"""
            },
            {
                "role": "user",
                "content": f"{prompt}\n\nPlease recommend relevant books and resources for deeper learning."
            }
        ],
        max_tokens=1200,
        temperature=0.5
    )

    return {
        "recommendations": response.choices[0].message.content.strip(),
        "provider": "chatgpt",
        "note": "These are AI-generated recommendations. Please verify availability and relevance."
    }
