"""Conversation export and sharing — Markdown, HTML, JSON."""

from __future__ import annotations

import html
import json
import time
from dataclasses import dataclass, field
from typing import Any


@dataclass
class ExportEntry:
    """A single entry in an export (thought, action, observation, etc.)."""

    entry_type: str  # thought, action, observation, result, error
    content: str
    timestamp: float = field(default_factory=time.time)
    metadata: dict[str, Any] = field(default_factory=dict)


@dataclass
class ExportData:
    """Full export data for a task conversation."""

    task_description: str
    entries: list[ExportEntry] = field(default_factory=list)
    result: dict[str, Any] | None = None
    cost: float = 0.0
    duration_seconds: float = 0.0
    model: str = ""
    created_at: float = field(default_factory=time.time)


class Exporter:
    """Export task conversations to various formats."""

    def to_markdown(self, data: ExportData) -> str:
        """Export to Markdown format."""
        lines: list[str] = []

        lines.append("# AgentScout Task Report")
        lines.append("")
        lines.append(f"**Task:** {data.task_description}")
        ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(data.created_at))
        lines.append(f"**Date:** {ts}")
        if data.model:
            lines.append(f"**Model:** {data.model}")
        if data.cost > 0:
            lines.append(f"**Cost:** ${data.cost:.4f}")
        if data.duration_seconds > 0:
            lines.append(f"**Duration:** {data.duration_seconds:.1f}s")
        lines.append("")
        lines.append("---")
        lines.append("")

        for entry in data.entries:
            if entry.entry_type == "thought":
                lines.append("### Thinking")
                lines.append(f"> {entry.content}")
            elif entry.entry_type == "action":
                tool = entry.metadata.get("tool_name", "unknown")
                lines.append(f"### Action: `{tool}`")
                lines.append("```json")
                lines.append(json.dumps(entry.metadata.get("tool_input", {}), indent=2))
                lines.append("```")
            elif entry.entry_type == "observation":
                lines.append("### Observation")
                lines.append(entry.content)
            elif entry.entry_type == "result":
                lines.append("### Result")
                lines.append(entry.content)
            elif entry.entry_type == "error":
                lines.append("### Error")
                lines.append(f"**{entry.content}**")
            lines.append("")

        if data.result:
            lines.append("---")
            lines.append("")
            lines.append("## Final Result")
            lines.append("")
            lines.append("```json")
            lines.append(json.dumps(data.result, indent=2))
            lines.append("```")

        lines.append("")
        lines.append("---")
        lines.append("*Generated by AgentScout*")

        return "\n".join(lines)

    def to_html(self, data: ExportData) -> str:
        """Export to shareable HTML report."""
        ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(data.created_at))

        entries_html: list[str] = []
        for entry in data.entries:
            escaped = html.escape(entry.content)
            if entry.entry_type == "thought":
                entries_html.append(
                    f'<div class="entry thought"><h3>Thinking</h3>'
                    f"<blockquote>{escaped}</blockquote></div>"
                )
            elif entry.entry_type == "action":
                tool = html.escape(entry.metadata.get("tool_name", "unknown"))
                tool_input = html.escape(json.dumps(entry.metadata.get("tool_input", {}), indent=2))
                entries_html.append(
                    f'<div class="entry action"><h3>Action: <code>{tool}</code></h3>'
                    f"<pre>{tool_input}</pre></div>"
                )
            elif entry.entry_type == "observation":
                entries_html.append(
                    f'<div class="entry observation"><h3>Observation</h3><p>{escaped}</p></div>'
                )
            elif entry.entry_type == "result":
                entries_html.append(
                    f'<div class="entry result"><h3>Result</h3><p>{escaped}</p></div>'
                )
            elif entry.entry_type == "error":
                entries_html.append(
                    f'<div class="entry error"><h3>Error</h3>'
                    f"<p><strong>{escaped}</strong></p></div>"
                )

        result_html = ""
        if data.result:
            result_json = html.escape(json.dumps(data.result, indent=2))
            result_html = (
                f'<div class="final-result"><h2>Final Result</h2><pre>{result_json}</pre></div>'
            )

        cost_line = f"<p><strong>Cost:</strong> ${data.cost:.4f}</p>" if data.cost > 0 else ""
        duration_line = (
            f"<p><strong>Duration:</strong> {data.duration_seconds:.1f}s</p>"
            if data.duration_seconds > 0
            else ""
        )
        model_line = (
            f"<p><strong>Model:</strong> {html.escape(data.model)}</p>" if data.model else ""
        )

        task_escaped = html.escape(data.task_description)

        return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AgentScout Report</title>
<style>
body {{ font-family: system-ui, sans-serif; max-width: 800px; margin: 2rem auto;
       padding: 0 1rem; color: #1a1a2e; background: #fafafa; }}
h1 {{ color: #16213e; }}
.meta {{ color: #666; margin-bottom: 2rem; }}
.entry {{ margin: 1.5rem 0; padding: 1rem; border-radius: 8px; }}
.thought {{ background: #e8f4f8; border-left: 4px solid #4ea8de; }}
.action {{ background: #f0f0ff; border-left: 4px solid #7b68ee; }}
.observation {{ background: #f0fff0; border-left: 4px solid #66bb6a; }}
.result {{ background: #fff8e1; border-left: 4px solid #ffa726; }}
.error {{ background: #fce4ec; border-left: 4px solid #ef5350; }}
.final-result {{ margin-top: 2rem; padding: 1.5rem; background: #e8f5e9;
                 border-radius: 8px; }}
pre {{ background: #1a1a2e; color: #e0e0e0; padding: 1rem; border-radius: 4px;
       overflow-x: auto; }}
code {{ background: #e0e0e0; padding: 2px 6px; border-radius: 3px; }}
blockquote {{ margin: 0.5rem 0; padding: 0.5rem 1rem; border-left: 3px solid #ccc;
              color: #555; }}
footer {{ margin-top: 3rem; color: #999; font-size: 0.85rem; text-align: center; }}
</style>
</head>
<body>
<h1>AgentScout Task Report</h1>
<div class="meta">
<p><strong>Task:</strong> {task_escaped}</p>
<p><strong>Date:</strong> {ts}</p>
{model_line}
{cost_line}
{duration_line}
</div>
<hr>
{"".join(entries_html)}
{result_html}
<hr>
<footer>Generated by AgentScout</footer>
</body>
</html>"""

    def to_json(self, data: ExportData) -> str:
        """Export to JSON format."""
        return json.dumps(
            {
                "task_description": data.task_description,
                "created_at": data.created_at,
                "model": data.model,
                "cost": data.cost,
                "duration_seconds": data.duration_seconds,
                "entries": [
                    {
                        "type": e.entry_type,
                        "content": e.content,
                        "timestamp": e.timestamp,
                        "metadata": e.metadata,
                    }
                    for e in data.entries
                ],
                "result": data.result,
            },
            indent=2,
        )
