"""AI analysis service for transcriptions."""

from openai import OpenAI
from typing import Optional


def analyze_transcription(
    text: str,
    api_key: str,
    analysis_type: str = "full"
) -> dict:
    """
    Analyze transcription text using OpenAI.
    Responds in the same language as the transcription.

    Args:
        text: The transcription text to analyze
        api_key: OpenAI API key
        analysis_type: Type of analysis - "summary", "takeaways", "topics", or "full"

    Returns:
        Dictionary with analysis results
    """
    client = OpenAI(api_key=api_key)

    # Truncate text if too long (keep ~12000 tokens worth)
    max_chars = 40000
    if len(text) > max_chars:
        text = text[:max_chars] + "\n\n[... content truncated for analysis ...]"

    if analysis_type == "summary":
        return {"summary": _get_summary(client, text)}
    elif analysis_type == "takeaways":
        return {"takeaways": _get_takeaways(client, text)}
    elif analysis_type == "topics":
        return {"topics": _get_topics(client, text)}
    else:
        # Full analysis
        return {
            "summary": _get_summary(client, text),
            "takeaways": _get_takeaways(client, text),
            "topics": _get_topics(client, text),
        }


def translate_text(
    text: str,
    api_key: str,
    target_language: str = "English"
) -> str:
    """
    Translate transcription text to a target language.

    Args:
        text: The transcription text to translate
        api_key: OpenAI API key
        target_language: Target language for translation

    Returns:
        Translated text
    """
    client = OpenAI(api_key=api_key)

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

    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "system",
                "content": f"You are a professional translator. Translate the following text to {target_language}. Maintain the original meaning, tone, and formatting. Only output the translation, nothing else."
            },
            {
                "role": "user",
                "content": text
            }
        ],
        max_tokens=4000,
        temperature=0.3
    )
    return response.choices[0].message.content.strip()


def _get_summary(client: OpenAI, text: str) -> str:
    """Generate a concise summary in the same language as the text."""
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "system",
                "content": "You are a helpful assistant that creates concise summaries. Provide a clear, well-structured summary in 2-3 paragraphs. Focus on the main message and key information. IMPORTANT: Respond in the SAME LANGUAGE as the transcription text."
            },
            {
                "role": "user",
                "content": f"Please summarize the following transcription:\n\n{text}"
            }
        ],
        max_tokens=500,
        temperature=0.5
    )
    return response.choices[0].message.content.strip()


def _get_takeaways(client: OpenAI, text: str) -> list:
    """Extract key takeaways in the same language as the text."""
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "system",
                "content": "You are a helpful assistant that extracts key takeaways. Provide 3-7 key points as a numbered list. Each point should be a clear, actionable or informative insight. Return ONLY the numbered list, no introduction or conclusion. IMPORTANT: Respond in the SAME LANGUAGE as the transcription text."
            },
            {
                "role": "user",
                "content": f"Extract the key takeaways from this transcription:\n\n{text}"
            }
        ],
        max_tokens=400,
        temperature=0.5
    )

    # Parse the numbered list
    content = response.choices[0].message.content.strip()
    lines = content.split('\n')
    takeaways = []
    for line in lines:
        line = line.strip()
        if line and (line[0].isdigit() or line.startswith('-')):
            # Remove numbering/bullets
            clean = line.lstrip('0123456789.-) ').strip()
            if clean:
                takeaways.append(clean)

    return takeaways if takeaways else [content]


def _get_topics(client: OpenAI, text: str) -> list:
    """Identify main topics discussed in the same language as the text."""
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "system",
                "content": "You are a helpful assistant that identifies topics. List 3-5 main topics or themes discussed. Return ONLY the topics as short phrases (2-4 words each), one per line, no numbering or bullets. IMPORTANT: Respond in the SAME LANGUAGE as the transcription text."
            },
            {
                "role": "user",
                "content": f"What are the main topics discussed in this transcription?\n\n{text}"
            }
        ],
        max_tokens=150,
        temperature=0.5
    )

    content = response.choices[0].message.content.strip()
    topics = [line.strip().lstrip('0123456789.-) ').strip()
              for line in content.split('\n')
              if line.strip()]

    return topics[:5]  # Max 5 topics
