"""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


def analyze_with_custom_prompt(
    text: str,
    api_key: str,
    prompt: str
) -> str:
    """
    Analyze transcription with a custom user-defined prompt.

    Args:
        text: The transcription text to analyze
        api_key: OpenAI API key
        prompt: The custom prompt/instruction

    Returns:
        Analysis result as string
    """
    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 analysis ...]"

    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "system",
                "content": "You are a helpful assistant that analyzes transcriptions. Follow the user's instructions carefully. Respond in the same language as the transcription."
            },
            {
                "role": "user",
                "content": f"{prompt}\n\nTranscription:\n{text}"
            }
        ],
        max_tokens=2000,
        temperature=0.5
    )
    return response.choices[0].message.content.strip()


def answer_question(
    text: str,
    api_key: str,
    question: str
) -> str:
    """
    Answer a question about the transcription.

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

    Returns:
        Answer based on the transcription content
    """
    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 ...]"

    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."""
            },
            {
                "role": "user",
                "content": f"Transcription:\n{text}\n\nQuestion: {question}"
            }
        ],
        max_tokens=1000,
        temperature=0.3
    )
    return response.choices[0].message.content.strip()


def format_transcription(
    text: str,
    api_key: str
) -> str:
    """
    Format transcription with headers and better structure.
    Organizes the content under logical section headers while preserving
    all the original text.

    Args:
        text: The transcription text to format
        api_key: OpenAI API key

    Returns:
        Formatted text with headers and sections
    """
    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 formatting ...]"

    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "system",
                "content": """You are a professional editor that formats transcriptions for better readability.

Your task:
1. Add clear section headers (using ## for main sections, ### for subsections) to organize the content logically
2. Group related content under appropriate headers
3. Add paragraph breaks where appropriate for better readability
4. Keep ALL the original text - do not remove or summarize any content
5. Fix obvious transcription errors if you spot them
6. Add bullet points for lists if appropriate

IMPORTANT:
- Preserve ALL original content - this is a formatting task, not summarization
- Use markdown headers (##, ###) for sections
- Respond in the SAME LANGUAGE as the transcription
- Make the content scannable with clear structure"""
            },
            {
                "role": "user",
                "content": f"Please format this transcription with headers and better structure:\n\n{text}"
            }
        ],
        max_tokens=8000,
        temperature=0.3
    )
    return response.choices[0].message.content.strip()
