"""Anthropic Claude service for AI critique and analysis."""

import httpx
from typing import Optional, List, Dict

ANTHROPIC_API_URL = "https://api.anthropic.com/v1"


async def critique_with_claude(
    text: str,
    original_analysis: str,
    api_key: str,
    model: str = "claude-3-haiku-20240307",
    max_tokens: int = 2000
) -> dict:
    """
    Use Claude to critique and improve an analysis.

    Args:
        text: Original transcription text
        original_analysis: The analysis to critique
        api_key: Anthropic API key
        model: Claude model to use
        max_tokens: Max response tokens

    Returns:
        Dict with critique and improved analysis
    """
    url = f"{ANTHROPIC_API_URL}/messages"

    headers = {
        "x-api-key": api_key,
        "anthropic-version": "2023-06-01",
        "Content-Type": "application/json"
    }

    system_prompt = """You are a critical analyst. Your task is to:
1. Review the provided analysis of a transcription
2. Identify any inaccuracies, gaps, or areas for improvement
3. Provide a more comprehensive and accurate analysis
4. Note any claims that should be fact-checked

Be constructive but thorough in your critique."""

    user_message = f"""Original Transcription:
{text[:5000]}

Original Analysis:
{original_analysis}

Please provide:
1. A critique of the original analysis
2. An improved, more accurate analysis
3. Key points that may need fact-checking"""

    payload = {
        "model": model,
        "max_tokens": max_tokens,
        "system": system_prompt,
        "messages": [
            {"role": "user", "content": user_message}
        ]
    }

    async with httpx.AsyncClient(timeout=60.0) as client:
        response = await client.post(url, headers=headers, json=payload)
        response.raise_for_status()
        result = response.json()

        # Extract text from Claude response
        content = result.get("content", [])
        text_response = ""
        for block in content:
            if block.get("type") == "text":
                text_response += block.get("text", "")

        return {
            "critique": text_response,
            "model": model,
            "usage": result.get("usage", {})
        }


async def analyze_with_claude(
    text: str,
    api_key: str,
    analysis_type: str = "comprehensive",
    model: str = "claude-3-haiku-20240307",
    max_tokens: int = 2000
) -> dict:
    """
    Analyze text using Claude.

    Args:
        text: Text to analyze
        api_key: Anthropic API key
        analysis_type: Type of analysis
        model: Claude model to use
        max_tokens: Max response tokens

    Returns:
        Analysis results
    """
    url = f"{ANTHROPIC_API_URL}/messages"

    headers = {
        "x-api-key": api_key,
        "anthropic-version": "2023-06-01",
        "Content-Type": "application/json"
    }

    prompts = {
        "comprehensive": """Analyze this transcription and provide:
1. A concise summary (2-3 sentences)
2. Main topics and themes
3. Key points and takeaways
4. Notable quotes or statements
5. Overall tone and sentiment""",

        "summary": "Provide a clear, concise summary of this transcription in 3-5 sentences.",

        "topics": "Identify and list the main topics discussed in this transcription with brief descriptions.",

        "sentiment": "Analyze the sentiment and tone of this transcription. Is it positive, negative, or neutral? What emotions are conveyed?",

        "key_points": "Extract the key points and main arguments from this transcription as a bulleted list.",

        "critique": """Critically analyze this transcription:
1. What claims are made?
2. What evidence is provided?
3. Are there any logical gaps or unsupported assertions?
4. What biases might be present?"""
    }

    system_prompt = "You are an expert analyst providing clear, insightful analysis."
    user_prompt = prompts.get(analysis_type, prompts["comprehensive"])

    payload = {
        "model": model,
        "max_tokens": max_tokens,
        "system": system_prompt,
        "messages": [
            {"role": "user", "content": f"{user_prompt}\n\nTranscription:\n{text[:8000]}"}
        ]
    }

    async with httpx.AsyncClient(timeout=60.0) as client:
        response = await client.post(url, headers=headers, json=payload)
        response.raise_for_status()
        result = response.json()

        content = result.get("content", [])
        text_response = ""
        for block in content:
            if block.get("type") == "text":
                text_response += block.get("text", "")

        return {
            "analysis": text_response,
            "analysis_type": analysis_type,
            "model": model,
            "usage": result.get("usage", {})
        }


async def chat_with_claude(
    messages: List[Dict],
    api_key: str,
    system: str = None,
    model: str = "claude-3-haiku-20240307",
    max_tokens: int = 1000
) -> dict:
    """
    Chat completion using Claude.

    Args:
        messages: List of message dicts with 'role' and 'content'
        api_key: Anthropic API key
        system: Optional system prompt
        model: Claude model to use
        max_tokens: Max response tokens

    Returns:
        Chat response
    """
    url = f"{ANTHROPIC_API_URL}/messages"

    headers = {
        "x-api-key": api_key,
        "anthropic-version": "2023-06-01",
        "Content-Type": "application/json"
    }

    payload = {
        "model": model,
        "max_tokens": max_tokens,
        "messages": messages
    }

    if system:
        payload["system"] = system

    async with httpx.AsyncClient(timeout=60.0) as client:
        response = await client.post(url, headers=headers, json=payload)
        response.raise_for_status()
        result = response.json()

        content = result.get("content", [])
        text_response = ""
        for block in content:
            if block.get("type") == "text":
                text_response += block.get("text", "")

        return {
            "response": text_response,
            "model": model,
            "usage": result.get("usage", {})
        }


def critique_with_claude_sync(
    text: str,
    original_analysis: str,
    api_key: str,
    model: str = "claude-3-haiku-20240307"
) -> str:
    """Synchronous wrapper for Claude critique."""
    import asyncio

    try:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        result = loop.run_until_complete(
            critique_with_claude(text, original_analysis, api_key, model)
        )
    finally:
        loop.close()

    return result.get("critique", "")


def analyze_with_claude_sync(
    text: str,
    api_key: str,
    analysis_type: str = "comprehensive",
    model: str = "claude-3-haiku-20240307"
) -> str:
    """Synchronous wrapper for Claude analysis."""
    import asyncio

    try:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        result = loop.run_until_complete(
            analyze_with_claude(text, api_key, analysis_type, model)
        )
    finally:
        loop.close()

    return result.get("analysis", "")
