"""Session export functionality (HTML, Markdown, etc.)."""

from pathlib import Path
from typing import Optional
from datetime import datetime

from .session import Session, SessionEntry


class SessionExporter:
    """Export sessions to various formats."""

    HTML_TEMPLATE = """<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{title}</title>
    <style>
        * {{ margin: 0; padding: 0; box-sizing: border-box; }}
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f5f5f5;
            padding: 2rem;
            line-height: 1.6;
        }}
        .container {{
            max-width: 900px;
            margin: 0 auto;
            background: white;
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }}
        .header {{
            border-bottom: 2px solid #007bff;
            padding-bottom: 1rem;
            margin-bottom: 2rem;
        }}
        h1 {{ color: #007bff; }}
        .meta {{ color: #6c757d; font-size: 0.9rem; margin-top: 0.5rem; }}
        .message {{
            margin: 1.5rem 0;
            padding: 1rem;
            border-radius: 8px;
        }}
        .message.user {{
            background: #e3f2fd;
            border-left: 4px solid #2196f3;
        }}
        .message.assistant {{
            background: #f1f8e9;
            border-left: 4px solid #4caf50;
        }}
        .message.system {{
            background: #fff3e0;
            border-left: 4px solid #ff9800;
            font-style: italic;
        }}
        .message.tool {{
            background: #f3e5f5;
            border-left: 4px solid #9c27b0;
            font-family: monospace;
            font-size: 0.9rem;
        }}
        .role {{
            font-weight: bold;
            text-transform: uppercase;
            font-size: 0.85rem;
            margin-bottom: 0.5rem;
        }}
        .role.user {{ color: #2196f3; }}
        .role.assistant {{ color: #4caf50; }}
        .role.system {{ color: #ff9800; }}
        .role.tool {{ color: #9c27b0; }}
        .content {{
            white-space: pre-wrap;
            word-wrap: break-word;
        }}
        .timestamp {{
            font-size: 0.75rem;
            color: #999;
            margin-top: 0.5rem;
        }}
        code {{
            background: #f4f4f4;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: 'Courier New', monospace;
        }}
        pre {{
            background: #2d2d2d;
            color: #f8f8f2;
            padding: 1rem;
            border-radius: 4px;
            overflow-x: auto;
            margin: 1rem 0;
        }}
        pre code {{
            background: none;
            padding: 0;
            color: inherit;
        }}
        .footer {{
            margin-top: 3rem;
            padding-top: 1rem;
            border-top: 1px solid #dee2e6;
            text-align: center;
            color: #6c757d;
            font-size: 0.85rem;
        }}
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>{title}</h1>
            <div class="meta">
                <div>Session ID: {session_id}</div>
                <div>Exported: {export_time}</div>
                <div>{entry_count} messages</div>
            </div>
        </div>
        
        <div class="messages">
{messages_html}
        </div>
        
        <div class="footer">
            Generated by pig-mono | <a href="https://github.com/kangkona/pig-mono">GitHub</a>
        </div>
    </div>
</body>
</html>
"""

    @staticmethod
    def export_to_html(
        session: Session, output_path: Optional[Path] = None, title: Optional[str] = None
    ) -> Path:
        """Export session to HTML file.

        Args:
            session: Session to export
            output_path: Output file path (auto-generated if None)
            title: Page title (uses session name if None)

        Returns:
            Path to exported file
        """
        if output_path is None:
            # Auto-generate filename
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            output_path = Path(f"{session.name}_{timestamp}.html")

        # Get conversation
        conversation = session.get_current_conversation()

        # Build messages HTML
        messages_html = []
        for entry in conversation:
            timestamp_str = entry.timestamp if hasattr(entry, "timestamp") else ""

            content_html = SessionExporter._format_content(entry.content)

            msg_html = f"""
            <div class="message {entry.role}">
                <div class="role {entry.role}">{entry.role}</div>
                <div class="content">{content_html}</div>
                {f'<div class="timestamp">{timestamp_str}</div>' if timestamp_str else ''}
            </div>"""

            messages_html.append(msg_html)

        # Fill template
        html = SessionExporter.HTML_TEMPLATE.format(
            title=title or session.name,
            session_id=session.id[:8],
            export_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            entry_count=len(conversation),
            messages_html="\n".join(messages_html),
        )

        # Write file
        output_path.write_text(html)

        return output_path

    @staticmethod
    def _format_content(content: str) -> str:
        """Format content for HTML display.

        Args:
            content: Message content

        Returns:
            HTML-formatted content
        """
        import html
        import re

        # Escape HTML
        content = html.escape(content)

        # Detect code blocks ```
        def replace_code_block(match):
            code = match.group(1)
            return f'<pre><code>{code}</code></pre>'

        content = re.sub(r'```(.*?)```', replace_code_block, content, flags=re.DOTALL)

        # Detect inline code `
        content = re.sub(r'`([^`]+)`', r'<code>\1</code>', content)

        # Convert newlines to <br> (outside code blocks)
        # This is simplified - a real implementation would be smarter
        content = content.replace('\n', '<br>\n')

        return content

    @staticmethod
    def export_to_markdown(session: Session, output_path: Optional[Path] = None) -> Path:
        """Export session to Markdown file.

        Args:
            session: Session to export
            output_path: Output file path

        Returns:
            Path to exported file
        """
        if output_path is None:
            output_path = Path(f"{session.name}.md")

        conversation = session.get_current_conversation()

        lines = [
            f"# {session.name}",
            "",
            f"Session ID: {session.id}",
            f"Exported: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
            f"Messages: {len(conversation)}",
            "",
            "---",
            "",
        ]

        for entry in conversation:
            lines.append(f"## {entry.role.upper()}")
            lines.append("")
            lines.append(entry.content)
            lines.append("")
            if hasattr(entry, "timestamp") and entry.timestamp:
                lines.append(f"*{entry.timestamp}*")
                lines.append("")

        output_path.write_text("\n".join(lines))

        return output_path
