"""
Export functionality for Umbra.
Generates standalone HTML files with interactive diagrams.
"""

from datetime import datetime
from pathlib import Path

HTML_TEMPLATE = '''<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{project_name} - Architecture</title>
    <script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
    <style>
        * {{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }}
        
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
            color: #e4e4e4;
            min-height: 100vh;
            padding: 2rem;
        }}
        
        .container {{
            max-width: 1400px;
            margin: 0 auto;
        }}
        
        header {{
            text-align: center;
            margin-bottom: 2rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #0f3460;
        }}
        
        h1 {{
            font-size: 2.5rem;
            background: linear-gradient(90deg, #e94560, #0f3460);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 0.5rem;
        }}
        
        .subtitle {{
            color: #888;
            font-size: 0.9rem;
        }}
        
        .grid {{
            display: grid;
            grid-template-columns: 1fr 350px;
            gap: 2rem;
        }}
        
        @media (max-width: 1000px) {{
            .grid {{
                grid-template-columns: 1fr;
            }}
        }}
        
        .card {{
            background: rgba(15, 52, 96, 0.5);
            border-radius: 12px;
            padding: 1.5rem;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(233, 69, 96, 0.2);
        }}
        
        .card h2 {{
            color: #e94560;
            font-size: 1.1rem;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }}
        
        .diagram-container {{
            background: #0a0a1a;
            border-radius: 8px;
            padding: 2rem;
            overflow-x: auto;
        }}
        
        .mermaid {{
            display: flex;
            justify-content: center;
        }}
        
        .summary {{
            line-height: 1.8;
        }}
        
        .summary strong {{
            color: #e94560;
        }}
        
        .summary h3 {{
            color: #fff;
            font-size: 1rem;
            margin: 1.5rem 0 0.5rem 0;
        }}
        
        .summary ul {{
            list-style: none;
            padding-left: 0;
        }}
        
        .summary li {{
            padding: 0.3rem 0;
            padding-left: 1.2rem;
            position: relative;
        }}
        
        .summary li::before {{
            content: "→";
            position: absolute;
            left: 0;
            color: #e94560;
        }}
        
        .summary code {{
            background: rgba(233, 69, 96, 0.2);
            padding: 0.1rem 0.4rem;
            border-radius: 4px;
            font-size: 0.85rem;
        }}
        
        .changes {{
            margin-top: 1.5rem;
        }}
        
        .changes table {{
            width: 100%;
            border-collapse: collapse;
            font-size: 0.85rem;
        }}
        
        .changes th {{
            text-align: left;
            color: #888;
            padding: 0.5rem;
            border-bottom: 1px solid #0f3460;
        }}
        
        .changes td {{
            padding: 0.5rem;
            border-bottom: 1px solid rgba(15, 52, 96, 0.5);
        }}
        
        .changes code {{
            background: rgba(233, 69, 96, 0.2);
            padding: 0.1rem 0.4rem;
            border-radius: 4px;
        }}
        
        footer {{
            text-align: center;
            margin-top: 2rem;
            padding-top: 1rem;
            border-top: 1px solid #0f3460;
            color: #666;
            font-size: 0.8rem;
        }}
        
        footer a {{
            color: #e94560;
            text-decoration: none;
        }}
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>🏗️ {project_name}</h1>
            <p class="subtitle">Generated by Umbra • {timestamp}</p>
        </header>
        
        <div class="grid">
            <main>
                <div class="card">
                    <h2>📊 Architecture Diagram</h2>
                    <div class="diagram-container">
                        <pre class="mermaid">
{mermaid_diagram}
                        </pre>
                    </div>
                </div>
            </main>
            
            <aside>
                <div class="card">
                    <h2>📋 Project Summary</h2>
                    <div class="summary">
                        {summary_html}
                    </div>
                </div>
                
                <div class="card changes">
                    <h2>🕐 Recent Changes</h2>
                    {changes_html}
                </div>
            </aside>
        </div>
        
        <footer>
            Generated by <a href="https://github.com/username/umbra">Umbra</a> - The Shadow Architect
        </footer>
    </div>
    
    <script>
        mermaid.initialize({{
            startOnLoad: true,
            theme: 'dark',
            themeVariables: {{
                primaryColor: '#e94560',
                primaryTextColor: '#fff',
                primaryBorderColor: '#0f3460',
                lineColor: '#e94560',
                secondaryColor: '#16213e',
                tertiaryColor: '#0f3460'
            }}
        }});
    </script>
</body>
</html>
'''


def markdown_to_html(md: str) -> str:
    """Convert simple markdown to HTML."""
    import re
    
    html = md
    
    # Bold
    html = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', html)
    
    # Code
    html = re.sub(r'`(.+?)`', r'<code>\1</code>', html)
    
    # Headers
    html = re.sub(r'^### (.+)$', r'<h3>\1</h3>', html, flags=re.MULTILINE)
    
    # Lists
    lines = html.split('\n')
    in_list = False
    result = []
    for line in lines:
        if line.strip().startswith('- '):
            if not in_list:
                result.append('<ul>')
                in_list = True
            result.append(f'<li>{line.strip()[2:]}</li>')
        else:
            if in_list:
                result.append('</ul>')
                in_list = False
            result.append(line)
    if in_list:
        result.append('</ul>')
    
    html = '\n'.join(result)
    
    # Paragraphs (lines that aren't tags)
    lines = html.split('\n')
    result = []
    for line in lines:
        stripped = line.strip()
        if stripped and not stripped.startswith('<'):
            result.append(f'<p>{line}</p>')
        else:
            result.append(line)
    
    return '\n'.join(result)


def export_html(
    input_file: str,
    output_file: str,
    project_name: str | None = None,
) -> None:
    """
    Export architecture to standalone HTML file.
    
    Args:
        input_file: Path to LIVE_ARCHITECTURE.md
        output_file: Output HTML path
        project_name: Optional project name (derived from path if not provided)
    """
    input_path = Path(input_file)
    
    if not input_path.exists():
        raise FileNotFoundError(f"Input file not found: {input_file}")
    
    content = input_path.read_text(encoding="utf-8")
    
    # Extract mermaid diagram
    mermaid = ""
    if "```mermaid" in content:
        start = content.index("```mermaid") + len("```mermaid")
        end = content.index("```", start)
        mermaid = content[start:end].strip()
    
    # Extract summary (between "## Project Summary" and "## System Overview")
    summary = ""
    if "## Project Summary" in content:
        start = content.index("## Project Summary") + len("## Project Summary")
        end = content.index("## System Overview") if "## System Overview" in content else len(content)
        summary = content[start:end].strip()
    
    # Extract changes table
    changes_html = "<p>No changes recorded yet.</p>"
    if "## Recent Changes" in content:
        start = content.index("## Recent Changes") + len("## Recent Changes")
        changes_section = content[start:].strip()
        
        # Parse markdown table
        lines = [l.strip() for l in changes_section.split('\n') if l.strip() and '|' in l]
        if len(lines) >= 2:
            changes_html = '<table><thead><tr><th>Time</th><th>File</th><th>Change</th></tr></thead><tbody>'
            for line in lines[2:]:  # Skip header and separator
                cells = [c.strip() for c in line.split('|')[1:-1]]
                if len(cells) >= 3:
                    changes_html += f'<tr><td>{cells[0]}</td><td><code>{cells[1]}</code></td><td>{cells[2]}</td></tr>'
            changes_html += '</tbody></table>'
    
    # Generate HTML
    html = HTML_TEMPLATE.format(
        project_name=project_name or "Project",
        timestamp=datetime.now().strftime("%Y-%m-%d %H:%M"),
        mermaid_diagram=mermaid,
        summary_html=markdown_to_html(summary),
        changes_html=changes_html,
    )
    
    # Write output
    output_path = Path(output_file)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_text(html, encoding="utf-8")

