"""Eden.ai service for AI operations - transcription, analysis, and more."""

import httpx
from typing import Optional, List, Dict
import json
import base64
from pathlib import Path


EDEN_API_URL = "https://api.edenai.run/v2"


async def transcribe_with_eden(
    file_path: str,
    api_key: str,
    language: str = "en",
    providers: List[str] = None
) -> dict:
    """
    Transcribe audio using Eden.ai speech-to-text.

    Args:
        file_path: Path to audio file
        api_key: Eden.ai API key
        language: Language code (e.g., 'en', 'es', 'fr')
        providers: List of providers to use (e.g., ['openai', 'google', 'aws'])

    Returns:
        Dict with transcription results from each provider
    """
    if providers is None:
        providers = ["openai"]  # Default to OpenAI Whisper via Eden

    url = f"{EDEN_API_URL}/audio/speech_to_text_async"

    headers = {
        "Authorization": f"Bearer {api_key}"
    }

    # Read file and encode as base64
    with open(file_path, 'rb') as f:
        file_content = f.read()

    file_name = Path(file_path).name

    async with httpx.AsyncClient(timeout=300.0) as client:
        # Upload file
        files = {
            'file': (file_name, file_content, 'audio/mpeg')
        }
        data = {
            'providers': ','.join(providers),
            'language': language,
        }

        response = await client.post(url, headers=headers, files=files, data=data)
        response.raise_for_status()
        result = response.json()

        # Eden returns async job, poll for result
        if 'public_id' in result:
            job_id = result['public_id']
            return await _poll_eden_job(client, api_key, job_id, 'audio/speech_to_text_async')

        return result


async def _poll_eden_job(client: httpx.AsyncClient, api_key: str, job_id: str, endpoint: str) -> dict:
    """Poll Eden.ai async job until complete."""
    import asyncio

    url = f"{EDEN_API_URL}/{endpoint}/{job_id}"
    headers = {"Authorization": f"Bearer {api_key}"}

    for _ in range(60):  # Max 5 minutes
        response = await client.get(url, headers=headers)
        result = response.json()

        if result.get('status') == 'finished':
            return result.get('results', result)
        elif result.get('status') == 'failed':
            raise Exception(f"Eden.ai job failed: {result.get('error', 'Unknown error')}")

        await asyncio.sleep(5)

    raise Exception("Eden.ai job timed out")


async def analyze_with_eden(
    text: str,
    api_key: str,
    analysis_type: str = "summarize",
    providers: List[str] = None
) -> dict:
    """
    Analyze text using Eden.ai.

    Args:
        text: Text to analyze
        api_key: Eden.ai API key
        analysis_type: Type of analysis ('summarize', 'sentiment', 'keyword', 'topic')
        providers: List of providers

    Returns:
        Analysis results
    """
    if providers is None:
        providers = ["openai"]

    endpoints = {
        'summarize': 'text/summarize',
        'sentiment': 'text/sentiment_analysis',
        'keyword': 'text/keyword_extraction',
        'topic': 'text/topic_extraction',
    }

    endpoint = endpoints.get(analysis_type, 'text/summarize')
    url = f"{EDEN_API_URL}/{endpoint}"

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    # Truncate if too long
    max_chars = 10000
    if len(text) > max_chars:
        text = text[:max_chars]

    payload = {
        "providers": ','.join(providers),
        "text": text,
        "language": "en"
    }

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


async def chat_with_eden(
    messages: List[Dict],
    api_key: str,
    providers: List[str] = None,
    temperature: float = 0.7,
    max_tokens: int = 1000
) -> dict:
    """
    Chat completion using Eden.ai.

    Args:
        messages: List of message dicts with 'role' and 'content'
        api_key: Eden.ai API key
        providers: List of providers (e.g., ['openai', 'anthropic', 'google'])
        temperature: Sampling temperature
        max_tokens: Max response tokens

    Returns:
        Chat completion response
    """
    if providers is None:
        providers = ["openai"]

    url = f"{EDEN_API_URL}/text/chat"

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    # Convert messages to Eden format
    eden_messages = []
    for msg in messages:
        eden_messages.append({
            "role": msg.get("role", "user"),
            "message": msg.get("content", "")
        })

    payload = {
        "providers": ','.join(providers),
        "text": eden_messages[-1]["message"] if eden_messages else "",
        "previous_history": eden_messages[:-1] if len(eden_messages) > 1 else [],
        "temperature": temperature,
        "max_tokens": max_tokens
    }

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


async def translate_with_eden(
    text: str,
    api_key: str,
    target_language: str,
    source_language: str = "en",
    providers: List[str] = None
) -> dict:
    """
    Translate text using Eden.ai.

    Args:
        text: Text to translate
        api_key: Eden.ai API key
        target_language: Target language code
        source_language: Source language code
        providers: List of providers

    Returns:
        Translation results
    """
    if providers is None:
        providers = ["google", "amazon"]

    url = f"{EDEN_API_URL}/translation/automatic_translation"

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    payload = {
        "providers": ','.join(providers),
        "text": text,
        "source_language": source_language,
        "target_language": target_language
    }

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


def transcribe_with_eden_sync(
    file_path: str,
    api_key: str,
    language: str = "en",
    providers: List[str] = None,
    progress_callback=None
) -> str:
    """
    Synchronous wrapper for Eden.ai transcription.
    Compatible with existing transcriber interface.
    """
    import asyncio

    if progress_callback:
        progress_callback(10, "Uploading to Eden.ai...")

    try:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        result = loop.run_until_complete(
            transcribe_with_eden(file_path, api_key, language, providers)
        )
    finally:
        loop.close()

    if progress_callback:
        progress_callback(90, "Processing response...")

    # Extract text from Eden response
    # Eden returns results per provider
    text = ""
    if isinstance(result, dict):
        for provider, data in result.items():
            if isinstance(data, dict) and 'text' in data:
                text = data['text']
                break
            elif isinstance(data, dict) and 'results' in data:
                for r in data.get('results', []):
                    if 'text' in r:
                        text = r['text']
                        break

    if progress_callback:
        progress_callback(100, "Complete!")

    return text


async def comprehensive_analysis_eden(
    text: str,
    api_key: str,
    providers: List[str] = None
) -> dict:
    """
    Comprehensive analysis using Eden.ai - summary, keywords, topics.

    Args:
        text: Text to analyze
        api_key: Eden.ai API key
        providers: Providers to use

    Returns:
        Dict with summary, keywords, topics
    """
    if providers is None:
        providers = ["openai"]

    results = {}

    # Get summary
    try:
        summary_result = await analyze_with_eden(text, api_key, "summarize", providers)
        for provider, data in summary_result.items():
            if isinstance(data, dict) and 'result' in data:
                results['summary'] = data['result']
                break
    except Exception as e:
        results['summary_error'] = str(e)

    # Get keywords
    try:
        keyword_result = await analyze_with_eden(text, api_key, "keyword", providers)
        keywords = []
        for provider, data in keyword_result.items():
            if isinstance(data, dict) and 'items' in data:
                keywords = [item.get('keyword', '') for item in data['items'][:10]]
                break
        results['keywords'] = keywords
    except Exception as e:
        results['keywords_error'] = str(e)

    # Get topics
    try:
        topic_result = await analyze_with_eden(text, api_key, "topic", providers)
        topics = []
        for provider, data in topic_result.items():
            if isinstance(data, dict) and 'items' in data:
                topics = [item.get('category', '') for item in data['items'][:5]]
                break
        results['topics'] = topics
    except Exception as e:
        results['topics_error'] = str(e)

    return results
