"""Export service for generating downloadable content."""

from datetime import datetime
from typing import Optional
import json


def export_to_markdown(item: dict) -> str:
    """
    Export item data to Markdown format.

    Args:
        item: Full item data including transcription, analysis, Q&A, etc.

    Returns:
        Markdown formatted string
    """
    lines = []

    # Title and metadata
    lines.append(f"# {item.get('title', 'Untitled')}")
    lines.append("")

    # Metadata
    if item.get('url'):
        lines.append(f"**Source:** {item.get('url')}")
    if item.get('duration'):
        lines.append(f"**Duration:** {item.get('duration')}")
    if item.get('created_at'):
        try:
            dt = datetime.fromisoformat(item['created_at'].replace('Z', '+00:00'))
            lines.append(f"**Date:** {dt.strftime('%Y-%m-%d %H:%M')}")
        except:
            lines.append(f"**Date:** {item.get('created_at')}")
    if item.get('thumbnail'):
        lines.append(f"**Thumbnail:** {item.get('thumbnail')}")
    lines.append("")

    # Tags/Topics
    topics = item.get('topics', [])
    if topics:
        lines.append("## Tags")
        lines.append(", ".join(f"`{t}`" for t in topics))
        lines.append("")

    # Cost summary
    costs = item.get('costs', {})
    if costs.get('total_cost'):
        lines.append(f"**Total Cost:** ${costs['total_cost']:.4f}")
        lines.append("")

    lines.append("---")
    lines.append("")

    # Transcription
    lines.append("## Transcription")
    lines.append("")
    transcription = item.get('transcription', '')
    if transcription:
        lines.append(transcription)
    else:
        lines.append("*No transcription available*")
    lines.append("")

    # Analysis
    analysis = item.get('analysis')
    if analysis:
        lines.append("---")
        lines.append("")
        lines.append("## AI Analysis")
        lines.append("")
        if isinstance(analysis, dict):
            # Extract main analysis text
            analysis_text = analysis.get('analysis', '')
            if isinstance(analysis_text, dict):
                analysis_text = analysis_text.get('analysis', str(analysis_text))
            lines.append(analysis_text)
            lines.append("")

            # Include analysis topics if present (separate from item tags)
            analysis_topics = analysis.get('topics', [])
            if analysis_topics and isinstance(analysis_topics, list):
                lines.append("### Analysis Topics")
                lines.append(", ".join(f"`{t}`" for t in analysis_topics))
        else:
            lines.append(str(analysis))
        lines.append("")

    # Q&A History
    qa_history = item.get('qa_history', [])
    if qa_history:
        lines.append("---")
        lines.append("")
        lines.append("## Questions & Answers")
        lines.append("")
        for i, qa in enumerate(qa_history, 1):
            lines.append(f"### Q{i}: {qa.get('question', '')}")
            lines.append("")
            lines.append(qa.get('answer', ''))
            lines.append("")
            # References
            refs = qa.get('references')
            if refs:
                ref_text = refs.get('resources') or refs.get('answer', '')
                if ref_text:
                    lines.append("**References:**")
                    lines.append("")
                    lines.append(ref_text)
                    lines.append("")

    # Resources
    resources = item.get('resources')
    if resources:
        lines.append("---")
        lines.append("")
        lines.append("## Resources & Citations")
        lines.append("")
        if isinstance(resources, dict):
            res_text = resources.get('resources') or resources.get('answer', '')
            lines.append(res_text if res_text else str(resources))
        else:
            lines.append(str(resources))
        lines.append("")

    # Cost breakdown
    if costs.get('entries'):
        lines.append("---")
        lines.append("")
        lines.append("## Cost Breakdown")
        lines.append("")
        lines.append("| Operation | Provider | Model | Cost |")
        lines.append("|-----------|----------|-------|------|")
        for entry in costs['entries']:
            op = entry.get('operation', '-')
            provider = entry.get('provider', '-')
            model = entry.get('model', '-')
            cost = entry.get('cost_usd', 0)
            lines.append(f"| {op} | {provider} | {model} | ${cost:.4f} |")
        lines.append("")
        lines.append(f"**Total:** ${costs.get('total_cost', 0):.4f}")
        lines.append("")

    # Footer
    lines.append("---")
    lines.append("")
    lines.append(f"*Exported from Whisper Scribe on {datetime.now().strftime('%Y-%m-%d %H:%M')}*")

    return "\n".join(lines)


def export_to_text(item: dict) -> str:
    """
    Export item data to plain text format.

    Args:
        item: Full item data

    Returns:
        Plain text formatted string
    """
    lines = []
    sep = "=" * 60

    # Title
    lines.append(sep)
    lines.append(item.get('title', 'Untitled').upper())
    lines.append(sep)
    lines.append("")

    # Metadata
    if item.get('url'):
        lines.append(f"Source: {item.get('url')}")
    if item.get('thumbnail'):
        lines.append(f"Thumbnail: {item.get('thumbnail')}")
    if item.get('duration'):
        lines.append(f"Duration: {item.get('duration')}")
    if item.get('created_at'):
        lines.append(f"Date: {item.get('created_at')}")

    topics = item.get('topics', [])
    if topics:
        lines.append(f"Tags: {', '.join(topics)}")

    costs = item.get('costs', {})
    if costs.get('total_cost'):
        lines.append(f"Total Cost: ${costs['total_cost']:.4f}")

    lines.append("")
    lines.append("-" * 60)
    lines.append("TRANSCRIPTION")
    lines.append("-" * 60)
    lines.append("")

    transcription = item.get('transcription', '')
    lines.append(transcription if transcription else "(No transcription available)")
    lines.append("")

    # Analysis
    analysis = item.get('analysis')
    if analysis:
        lines.append("-" * 60)
        lines.append("AI ANALYSIS")
        lines.append("-" * 60)
        lines.append("")
        if isinstance(analysis, dict):
            analysis_text = analysis.get('analysis', '')
            if isinstance(analysis_text, dict):
                analysis_text = analysis_text.get('analysis', str(analysis_text))
            lines.append(analysis_text)
            lines.append("")

            # Include analysis topics if present
            analysis_topics = analysis.get('topics', [])
            if analysis_topics and isinstance(analysis_topics, list):
                lines.append("Analysis Topics: " + ", ".join(analysis_topics))
        else:
            lines.append(str(analysis))
        lines.append("")

    # Q&A History
    qa_history = item.get('qa_history', [])
    if qa_history:
        lines.append("-" * 60)
        lines.append("QUESTIONS & ANSWERS")
        lines.append("-" * 60)
        lines.append("")
        for i, qa in enumerate(qa_history, 1):
            lines.append(f"Q{i}: {qa.get('question', '')}")
            lines.append("")
            lines.append(f"A: {qa.get('answer', '')}")
            lines.append("")
            refs = qa.get('references')
            if refs:
                ref_text = refs.get('resources') or refs.get('answer', '')
                if ref_text:
                    lines.append("References:")
                    lines.append(ref_text)
                    lines.append("")

    # Resources
    resources = item.get('resources')
    if resources:
        lines.append("-" * 60)
        lines.append("RESOURCES & CITATIONS")
        lines.append("-" * 60)
        lines.append("")
        if isinstance(resources, dict):
            res_text = resources.get('resources') or resources.get('answer', '')
            lines.append(res_text if res_text else str(resources))
        else:
            lines.append(str(resources))
        lines.append("")

    # Footer
    lines.append(sep)
    lines.append(f"Exported from Whisper Scribe on {datetime.now().strftime('%Y-%m-%d %H:%M')}")
    lines.append(sep)

    return "\n".join(lines)


def export_to_json(item: dict) -> str:
    """
    Export item data to JSON format.

    Args:
        item: Full item data

    Returns:
        JSON formatted string
    """
    # Create a clean export structure
    export_data = {
        "title": item.get('title', 'Untitled'),
        "url": item.get('url'),
        "thumbnail": item.get('thumbnail'),
        "duration": item.get('duration'),
        "created_at": item.get('created_at'),
        "exported_at": datetime.now().isoformat(),
        "tags": item.get('topics', []),
        "transcription": item.get('transcription'),
        "analysis": None,
        "qa_history": [],
        "resources": None,
        "costs": item.get('costs')
    }

    # Clean up analysis - preserve full structure
    analysis = item.get('analysis')
    if analysis:
        if isinstance(analysis, dict):
            # Include both the analysis text and topics
            analysis_text = analysis.get('analysis', '')
            if isinstance(analysis_text, dict):
                analysis_text = analysis_text.get('analysis', str(analysis_text))
            export_data["analysis"] = {
                "text": analysis_text,
                "topics": analysis.get('topics', [])
            }
        else:
            export_data["analysis"] = {"text": str(analysis), "topics": []}

    # Clean up Q&A
    for qa in item.get('qa_history', []):
        export_data["qa_history"].append({
            "question": qa.get('question'),
            "answer": qa.get('answer'),
            "timestamp": qa.get('timestamp'),
            "references": qa.get('references', {}).get('resources') if qa.get('references') else None
        })

    # Clean up resources
    resources = item.get('resources')
    if resources:
        if isinstance(resources, dict):
            export_data["resources"] = resources.get('resources') or resources.get('answer')
        else:
            export_data["resources"] = resources

    return json.dumps(export_data, ensure_ascii=False, indent=2)


def get_export_filename(item: dict, format: str) -> str:
    """
    Generate a safe filename for export.

    Args:
        item: Item data
        format: Export format (md, txt, json)

    Returns:
        Safe filename string (ASCII only for HTTP headers)
    """
    title = item.get('title', 'export')

    # Convert to ASCII-safe characters only (for HTTP headers)
    # Keep only ASCII alphanumeric, spaces, hyphens, underscores
    safe_title = "".join(c for c in title if c.isascii() and (c.isalnum() or c in ' -_')).strip()

    # Replace spaces with underscores
    safe_title = safe_title.replace(' ', '_')

    # Limit length
    safe_title = safe_title[:50]

    # Fallback if empty (e.g., all non-ASCII title)
    if not safe_title:
        item_id = item.get('id', 'export')[:8]
        safe_title = f"whisper_scribe_{item_id}"

    date_str = datetime.now().strftime('%Y%m%d')

    extensions = {
        'markdown': 'md',
        'md': 'md',
        'text': 'txt',
        'txt': 'txt',
        'json': 'json'
    }
    ext = extensions.get(format, 'txt')

    return f"{safe_title}_{date_str}.{ext}"
