"""
Export utilities for Agent Expert Panel discussions.

This module provides functionality to save discussion results in various formats.
"""

import json
import csv
from datetime import datetime
from pathlib import Path
from typing import Any

from ..models import PanelResult


class DiscussionExporter:
    """Handles exporting discussion results to various formats."""

    @staticmethod
    def _convert_datetime_to_string(obj: Any) -> Any:
        """
        Recursively convert datetime objects to ISO format strings for JSON serialization.

        Args:
            obj: The object to process

        Returns:
            The object with datetime objects converted to strings
        """
        if isinstance(obj, datetime):
            return obj.isoformat()
        elif isinstance(obj, dict):
            return {
                key: DiscussionExporter._convert_datetime_to_string(value)
                for key, value in obj.items()
            }
        elif isinstance(obj, list):
            return [
                DiscussionExporter._convert_datetime_to_string(item) for item in obj
            ]
        else:
            return obj

    @staticmethod
    def to_json(result: PanelResult, output_path: Path | None = None) -> str:
        """
        Export discussion result to JSON format.

        Args:
            result: The panel discussion result
            output_path: Optional file path to save to

        Returns:
            JSON string representation
        """
        data = {
            "timestamp": datetime.now().isoformat(),
            "topic": result.topic,
            "discussion_pattern": result.discussion_pattern.value,
            "agents_participated": result.agents_participated,
            "total_rounds": result.total_rounds,
            "consensus_reached": result.consensus_reached,
            "final_recommendation": result.final_recommendation,
            "discussion_history": result.discussion_history,
        }

        # Convert datetime objects to strings for JSON serialization
        data = DiscussionExporter._convert_datetime_to_string(data)

        json_str = json.dumps(data, indent=2, ensure_ascii=False)

        if output_path:
            output_path.write_text(json_str, encoding="utf-8")

        return json_str

    @staticmethod
    def to_markdown(result: PanelResult, output_path: Path | None = None) -> str:
        """
        Export discussion result to Markdown format.

        Args:
            result: The panel discussion result
            output_path: Optional file path to save to

        Returns:
            Markdown string representation
        """
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        markdown = f"""# Expert Panel Discussion Report

**Generated:** {timestamp}

## Discussion Overview

- **Topic:** {result.topic}
- **Discussion Pattern:** {result.discussion_pattern.value.replace("_", " ").title()}
- **Participants:** {", ".join(result.agents_participated)}
- **Total Rounds:** {result.total_rounds}
- **Consensus Reached:** {"✅ Yes" if result.consensus_reached else "❌ No"}

## Final Recommendation

{result.final_recommendation}

## Discussion History

"""

        if result.discussion_history:
            for i, entry in enumerate(result.discussion_history, 1):
                speaker = entry.get("speaker", "Unknown")
                content = entry.get("content", "No content")
                markdown += f"### Round {i} - {speaker.title()}\n\n{content}\n\n"
        else:
            markdown += "*No detailed discussion history available.*\n"

        markdown += """
---
*Generated by Agent Expert Panel*
"""

        if output_path:
            output_path.write_text(markdown, encoding="utf-8")

        return markdown

    @staticmethod
    def to_csv(results: list[PanelResult], output_path: Path) -> None:
        """
        Export multiple discussion results to CSV format.

        Args:
            results: List of panel discussion results
            output_path: File path to save CSV to
        """
        with open(output_path, "w", newline="", encoding="utf-8") as csvfile:
            fieldnames = [
                "timestamp",
                "topic",
                "discussion_pattern",
                "participants",
                "total_rounds",
                "consensus_reached",
                "final_recommendation",
            ]
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

            writer.writeheader()
            for result in results:
                writer.writerow(
                    {
                        "timestamp": datetime.now().isoformat(),
                        "topic": result.topic,
                        "discussion_pattern": result.discussion_pattern.value,
                        "participants": ", ".join(result.agents_participated),
                        "total_rounds": result.total_rounds,
                        "consensus_reached": result.consensus_reached,
                        "final_recommendation": result.final_recommendation[:500]
                        + "..."
                        if len(result.final_recommendation) > 500
                        else result.final_recommendation,
                    }
                )

    @staticmethod
    def create_output_filename(topic: str, extension: str = "json") -> str:
        """
        Create a safe filename from the discussion topic.

        Args:
            topic: The discussion topic
            extension: File extension (without dot)

        Returns:
            Safe filename
        """
        # Clean topic for filename
        safe_topic = "".join(
            c for c in topic if c.isalnum() or c in (" ", "-", "_")
        ).rstrip()
        safe_topic = safe_topic.replace(" ", "_").lower()[:50]  # Limit length

        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        return f"discussion_{safe_topic}_{timestamp}.{extension}"


def save_discussion(
    result: PanelResult,
    output_dir: Path = Path("./discussions"),
    formats: list[str] = ["json", "markdown"],
) -> dict[str, Path]:
    """
    Save discussion result in multiple formats.

    Args:
        result: The panel discussion result
        output_dir: Directory to save files to
        formats: List of formats to export ('json', 'markdown', 'csv')

    Returns:
        Dictionary mapping format to saved file path
    """
    output_dir.mkdir(exist_ok=True)
    saved_files = {}

    exporter = DiscussionExporter()
    base_filename = exporter.create_output_filename(result.topic)

    for fmt in formats:
        if fmt == "json":
            filename = base_filename.replace(".json", ".json")
            file_path = output_dir / filename
            exporter.to_json(result, file_path)
            saved_files["json"] = file_path

        elif fmt == "markdown":
            filename = base_filename.replace(".json", ".md")
            file_path = output_dir / filename
            exporter.to_markdown(result, file_path)
            saved_files["markdown"] = file_path

        elif fmt == "csv":
            # For CSV, we need to handle multiple results differently
            # This is a placeholder - would need to be called with multiple results
            filename = base_filename.replace(".json", ".csv")
            file_path = output_dir / filename
            exporter.to_csv([result], file_path)
            saved_files["csv"] = file_path

    return saved_files
