"""
Export utilities for consultations and session summaries.

Provides markdown, JSON, and text export formats for sharing with teams.
v0.4.0 Feature #3: Team Collaboration
"""

from typing import List, Dict, Any
from datetime import datetime
import json
from dataclasses import asdict

from sensei_mcp.models import Consultation, SessionState, Decision


class ConsultationExporter:
    """Export individual consultations in various formats."""

    @staticmethod
    def export_consultation(
        consultation: Consultation,
        format: str = "markdown",
        include_metadata: bool = True
    ) -> str:
        """
        Export a single consultation as shareable report.

        Args:
            consultation: Consultation to export
            format: Output format ("markdown", "json", "text")
            include_metadata: Include timestamps and IDs

        Returns:
            Formatted consultation report
        """
        if format == "json":
            return ConsultationExporter._export_json(consultation)
        elif format == "text":
            return ConsultationExporter._export_text(consultation, include_metadata)
        else:  # markdown (default)
            return ConsultationExporter._export_markdown(consultation, include_metadata)

    @staticmethod
    def _export_markdown(consultation: Consultation, include_metadata: bool) -> str:
        """Export as markdown report."""
        lines = ["# Consultation Report", ""]

        if include_metadata:
            lines.extend([
                f"**ID:** `{consultation.id}`",
                f"**Date:** {consultation.timestamp}",
                f"**Mode:** {consultation.mode}",
                f"**Context:** {consultation.context}",
                ""
            ])

        lines.extend([
            "## Query",
            f"> {consultation.query}",
            "",
            "## Personas Consulted"
        ])

        for persona in consultation.personas_consulted:
            lines.append(f"- {persona.replace('-', ' ').title()}")

        lines.extend([
            "",
            "## Synthesis & Recommendation",
            consultation.synthesis,
            ""
        ])

        if consultation.decision_id:
            lines.extend([
                "## Linked Decision",
                f"This consultation led to decision: `{consultation.decision_id}`",
                ""
            ])

        lines.extend([
            "---",
            f"*Generated by Sensei MCP v0.4.0 on {datetime.now().strftime('%Y-%m-%d')}*"
        ])

        return "\n".join(lines)

    @staticmethod
    def _export_text(consultation: Consultation, include_metadata: bool) -> str:
        """Export as plain text."""
        lines = ["CONSULTATION REPORT", "=" * 60]

        if include_metadata:
            lines.extend([
                f"ID: {consultation.id}",
                f"Date: {consultation.timestamp}",
                f"Mode: {consultation.mode}",
                f"Context: {consultation.context}",
                ""
            ])

        lines.extend([
            "QUERY:",
            consultation.query,
            "",
            "PERSONAS CONSULTED:",
            ", ".join(consultation.personas_consulted),
            "",
            "SYNTHESIS:",
            consultation.synthesis
        ])

        if consultation.decision_id:
            lines.extend([
                "",
                f"Linked Decision: {consultation.decision_id}"
            ])

        return "\n".join(lines)

    @staticmethod
    def _export_json(consultation: Consultation) -> str:
        """Export as JSON."""
        data = {
            'id': consultation.id,
            'timestamp': consultation.timestamp,
            'query': consultation.query,
            'mode': consultation.mode,
            'personas_consulted': consultation.personas_consulted,
            'context': consultation.context,
            'synthesis': consultation.synthesis,
            'decision_id': consultation.decision_id
        }
        return json.dumps(data, indent=2)


class SessionExporter:
    """Export session summaries and ADRs for team sharing."""

    @staticmethod
    def export_session_summary(
        session: SessionState,
        format: str = "markdown",
        include: List[str] = None,
        max_consultations: int = 10
    ) -> str:
        """
        Export comprehensive session summary.

        Args:
            session: SessionState to export
            format: Output format ("markdown", "json", "text")
            include: Components to include (decisions, consultations, constraints, patterns)
            max_consultations: Maximum recent consultations to include

        Returns:
            Formatted session summary
        """
        if include is None:
            include = ["decisions", "consultations", "constraints", "patterns"]

        if format == "json":
            return SessionExporter._export_json(session, include)
        elif format == "text":
            return SessionExporter._export_text(session, include, max_consultations)
        else:  # markdown
            return SessionExporter._export_markdown(session, include, max_consultations)

    @staticmethod
    def _export_markdown(
        session: SessionState,
        include: List[str],
        max_consultations: int
    ) -> str:
        """Export as markdown with ADR-style formatting."""
        lines = [
            f"# Session Summary: {session.session_id}",
            "",
            f"**Generated:** {datetime.now().isoformat()}",
            f"**Session Started:** {session.started_at}",
            f"**Last Updated:** {session.last_updated}",
            ""
        ]

        # Architecture Decision Records
        if "decisions" in include and session.decisions:
            lines.extend([
                "## Architecture Decision Records (ADRs)",
                "",
                f"Total decisions: {len(session.decisions)}",
                ""
            ])

            for i, decision in enumerate(session.decisions, 1):
                lines.extend([
                    f"### ADR {i}: {decision.description}",
                    "",
                    f"**Category:** {decision.category}",
                    f"**Date:** {decision.timestamp}",
                    "",
                    "**Rationale:**",
                    decision.rationale,
                    ""
                ])

                # Check context for constraint/pattern (stored in context dict)
                if decision.context:
                    if decision.context.get('constraint'):
                        lines.append(f"**Adds Constraint:** {decision.context['constraint']}")
                        lines.append("")
                    if decision.context.get('pattern'):
                        lines.append(f"**Establishes Pattern:** {decision.context['pattern']}")
                        lines.append("")

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

        # Consultation History
        if "consultations" in include and session.consultations:
            recent = session.consultations[-max_consultations:]
            lines.extend([
                "## Recent Consultation History",
                "",
                f"Showing {len(recent)} most recent (total: {len(session.consultations)})",
                ""
            ])

            for cons in recent:
                lines.extend([
                    f"### {cons.query}",
                    "",
                    f"**Date:** {cons.timestamp}",
                    f"**Mode:** {cons.mode} | **Context:** {cons.context}",
                    f"**Personas:** {', '.join(cons.personas_consulted)}",
                    "",
                    "**Outcome:**",
                    cons.synthesis[:200] + "..." if len(cons.synthesis) > 200 else cons.synthesis,
                    ""
                ])

                if cons.decision_id:
                    lines.append(f"*→ Led to decision: {cons.decision_id}*")
                    lines.append("")

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

        # Active Constraints
        if "constraints" in include and session.active_constraints:
            lines.extend([
                "## Active Constraints",
                "",
                "Current project constraints and requirements:",
                ""
            ])

            for constraint in session.active_constraints:
                lines.append(f"- {constraint}")

            lines.append("")

        # Agreed Patterns
        if "patterns" in include and session.patterns_agreed:
            lines.extend([
                "## Agreed Patterns",
                "",
                "Architectural patterns and approaches we've agreed to follow:",
                ""
            ])

            for pattern in session.patterns_agreed:
                lines.append(f"- {pattern}")

            lines.append("")

        # Footer
        lines.extend([
            "---",
            "",
            "## How to Use This Summary",
            "",
            "This document captures our architectural decision-making context.",
            "Share with team members to:",
            "- Onboard new engineers",
            "- Align on architectural direction",
            "- Document decision rationale",
            "- Track constraint evolution",
            "",
            f"*Generated by Sensei MCP v0.4.0*"
        ])

        return "\n".join(lines)

    @staticmethod
    def _export_text(
        session: SessionState,
        include: List[str],
        max_consultations: int
    ) -> str:
        """Export as plain text."""
        lines = [
            f"SESSION SUMMARY: {session.session_id}",
            "=" * 70,
            f"Generated: {datetime.now().isoformat()}",
            f"Started: {session.started_at}",
            ""
        ]

        if "decisions" in include:
            lines.extend([
                "DECISIONS:",
                "-" * 70
            ])
            for decision in session.decisions:
                lines.extend([
                    f"• {decision.description} ({decision.category})",
                    f"  {decision.rationale}",
                    ""
                ])

        if "consultations" in include:
            recent = session.consultations[-max_consultations:]
            lines.extend([
                f"RECENT CONSULTATIONS ({len(recent)} of {len(session.consultations)}):",
                "-" * 70
            ])
            for cons in recent:
                lines.extend([
                    f"• {cons.query}",
                    f"  Personas: {', '.join(cons.personas_consulted)}",
                    ""
                ])

        if "constraints" in include:
            lines.extend([
                "CONSTRAINTS:",
                "-" * 70
            ])
            for constraint in session.active_constraints:
                lines.append(f"• {constraint}")
            lines.append("")

        return "\n".join(lines)

    @staticmethod
    def _export_json(session: SessionState, include: List[str]) -> str:
        """Export as JSON."""
        data = {
            'session_id': session.session_id,
            'started_at': session.started_at,
            'last_updated': session.last_updated,
            'generated_at': datetime.now().isoformat()
        }

        if "decisions" in include:
            data['decisions'] = [
                {
                    'id': d.id,
                    'category': d.category,
                    'description': d.description,
                    'rationale': d.rationale,
                    'timestamp': d.timestamp,
                    'context': d.context
                }
                for d in session.decisions
            ]

        if "consultations" in include:
            data['consultations'] = [
                {
                    'id': c.id,
                    'query': c.query,
                    'mode': c.mode,
                    'personas': c.personas_consulted,
                    'context': c.context,
                    'timestamp': c.timestamp,
                    'decision_id': c.decision_id
                }
                for c in session.consultations
            ]

        if "constraints" in include:
            data['active_constraints'] = session.active_constraints

        if "patterns" in include:
            data['patterns_agreed'] = session.patterns_agreed

        return json.dumps(data, indent=2)
