"""HTML Output Renderer for NLP3

Generates rich HTML reports from tree structures.
"""

from typing import List, Optional
from datetime import datetime
import json

from ..core import TreeNode


class HTMLRenderer:
    """Render tree structures as HTML"""
    
    @staticmethod
    def render_tree(nodes: List[TreeNode], title: str = "Tree Report") -> str:
        """Render tree structure as HTML"""
        html = f"""<!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>
        body {{
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }}
        .container {{
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }}
        .header {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }}
        .header h1 {{
            margin: 0;
            font-size: 2.5em;
            font-weight: 300;
        }}
        .header p {{
            margin: 10px 0 0 0;
            opacity: 0.9;
        }}
        .content {{
            padding: 30px;
        }}
        .tree {{
            font-family: 'Courier New', monospace;
            line-height: 1.6;
        }}
        .tree-node {{
            margin: 2px 0;
        }}
        .tree-node.branch {{
            font-weight: bold;
            color: #2563eb;
        }}
        .tree-node.leaf {{
            color: #059669;
        }}
        .tree-indent {{
            display: inline-block;
            width: 20px;
        }}
        .metadata {{
            font-size: 0.9em;
            color: #6b7280;
            margin-left: 10px;
        }}
        .size {{
            background: #f3f4f6;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 0.8em;
        }}
        .extra {{
            background: #fef3c7;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 0.8em;
            margin-left: 5px;
        }}
        .footer {{
            background: #f9fafb;
            padding: 20px;
            text-align: center;
            color: #6b7280;
            border-top: 1px solid #e5e7eb;
        }}
        .stats {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }}
        .stat-card {{
            background: #f9fafb;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
        }}
        .stat-number {{
            font-size: 2em;
            font-weight: bold;
            color: #2563eb;
        }}
        .stat-label {{
            color: #6b7280;
            margin-top: 5px;
        }}
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🌳 NLP3 Report</h1>
            <p>{title}</p>
            <p>Generated on {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
        </div>
        
        <div class="content">
            <div class="stats">
                <div class="stat-card">
                    <div class="stat-number">{len(nodes)}</div>
                    <div class="stat-label">Root Nodes</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number">{HTMLRenderer._count_all_nodes(nodes)}</div>
                    <div class="stat-label">Total Nodes</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number">{HTMLRenderer._count_branch_nodes(nodes)}</div>
                    <div class="stat-label">Branch Nodes</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number">{HTMLRenderer._count_leaf_nodes(nodes)}</div>
                    <div class="stat-label">Leaf Nodes</div>
                </div>
            </div>
            
            <div class="tree">
"""
        
        for node in nodes:
            html += HTMLRenderer._render_node_html(node, 0)
        
        html += """
            </div>
        </div>
        
        <div class="footer">
            <p>Generated by NLP3 - Universal Context Navigator</p>
        </div>
    </div>
</body>
</html>"""
        
        return html
    
    @staticmethod
    def _render_node_html(node: TreeNode, depth: int) -> str:
        """Render single node as HTML"""
        indent = "  " * depth
        node_class = node.node_type.value
        
        # Node name and type
        html = f'{indent}<div class="tree-node {node_class}">'
        html += f'{"&nbsp;" * (depth * 4)}📁 {node.name} ({node_class})'
        
        # Size
        if node.metadata and node.metadata.size:
            size = node.metadata.size
            if size < 1024:
                size_str = f"{size}B"
            elif size < 1024**2:
                size_str = f"{size/1024:.1f}KB"
            else:
                size_str = f"{size/1024**2:.1f}MB"
            html += f' <span class="size">{size_str}</span>'
        
        # Extra metadata
        if node.metadata.extra:
            extra_items = []
            for key, value in node.metadata.extra.items():
                if key in ['tag', 'type', 'class', 'id'] and value:
                    if isinstance(value, list):
                        value = ', '.join(str(v) for v in value)
                    extra_items.append(f"{key}: {value}")
            
            if extra_items:
                html += f' <span class="extra">{", ".join(extra_items)}</span>'
        
        html += '</div>\n'
        
        # Children
        children = list(node.children())
        if children:
            for child in children:
                html += HTMLRenderer._render_node_html(child, depth + 1)
        
        return html
    
    @staticmethod
    def _count_all_nodes(nodes: List[TreeNode]) -> int:
        """Count all nodes recursively"""
        count = 0
        for node in nodes:
            count += 1
            children = list(node.children())
            if children:
                count += HTMLRenderer._count_all_nodes(children)
        return count
    
    @staticmethod
    def _count_branch_nodes(nodes: List[TreeNode]) -> int:
        """Count branch nodes recursively"""
        count = 0
        for node in nodes:
            if node.node_type.value == 'branch':
                count += 1
            children = list(node.children())
            if children:
                count += HTMLRenderer._count_branch_nodes(children)
        return count
    
    @staticmethod
    def _count_leaf_nodes(nodes: List[TreeNode]) -> int:
        """Count leaf nodes recursively"""
        count = 0
        for node in nodes:
            if node.node_type.value == 'leaf':
                count += 1
            children = list(node.children())
            if children:
                count += HTMLRenderer._count_leaf_nodes(children)
        return count
