"""
Pure Python Circuit SVG Generator
Convert Verilog AST directly to SVG visualization
No external tools required!
"""

from verilog_framework.core.ast_nodes import (
    Module, Port, WireDeclaration, RegDeclaration, Assign, Always
)
from pathlib import Path
from typing import Optional, List, Tuple


class CircuitSVG:
    """Generate SVG circuit diagram from Verilog AST - Pure Python, No Dependencies"""
    
    def __init__(self, ast: Module, width: int = 800, height: int = 600):
        self.ast = ast
        self.width = width
        self.height = height
        self.elements = []
        self.box_width = 100
        self.box_height = 50
        self.padding = 40
        
    def generate(self) -> str:
        """Generate SVG string from AST"""
        self.elements = []
        
        # SVG header
        svg = f'''<svg width="{self.width}" height="{self.height}" xmlns="http://www.w3.org/2000/svg">
<style>
  .box {{ fill: #f0f0f0; stroke: #333; stroke-width: 2; }}
  .port {{ fill: #fff; stroke: #666; stroke-width: 1; }}
  .wire {{ stroke: #333; stroke-width: 2; fill: none; }}
  .label {{ font-family: Arial, sans-serif; font-size: 12px; }}
  .module-name {{ font-family: Arial, sans-serif; font-size: 14px; font-weight: bold; }}
  .title {{ font-family: Arial, sans-serif; font-size: 16px; font-weight: bold; }}
</style>

<!-- Title -->
<text x="20" y="30" class="title">Module: {self.ast.name}</text>

<!-- Module Box -->
<rect x="100" y="80" width="{self.box_width}" height="{self.box_height}" class="box"/>
<text x="110" y="110" class="module-name">{self.ast.name}</text>

'''
        
        # Draw ports
        input_count = 0
        output_count = 0
        
        for port in self.ast.port_list:
            if port.direction == 'input':
                y_pos = 120 + input_count * 30
                svg += f'<!-- Input: {port.name} -->\n'
                svg += f'<circle cx="100" cy="{y_pos}" r="4" fill="#0066cc"/>\n'
                svg += f'<line x1="90" y1="{y_pos}" x2="100" y2="{y_pos}" class="wire"/>\n'
                svg += f'<text x="10" y="{y_pos + 4}" class="label">{port.name}</text>\n'
                input_count += 1
            else:
                y_pos = 120 + output_count * 30
                svg += f'<!-- Output: {port.name} -->\n'
                svg += f'<circle cx="{100 + self.box_width}" cy="{y_pos}" r="4" fill="#cc0000"/>\n'
                svg += f'<line x1="{100 + self.box_width}" y1="{y_pos}" x2="{100 + self.box_width + 90}" y2="{y_pos}" class="wire"/>\n'
                svg += f'<text x="{100 + self.box_width + 100}" y="{y_pos + 4}" class="label">{port.name}</text>\n'
                output_count += 1
        
        # Draw statements info
        y_offset = 200
        if self.ast.statements:
            svg += f'<!-- Statements ({len(self.ast.statements)}) -->\n'
            for i, stmt in enumerate(self.ast.statements[:5]):  # Limit to 5
                stmt_type = type(stmt).__name__
                svg += f'<text x="20" y="{y_offset + i * 20}" class="label">{i+1}. {stmt_type}</text>\n'
        
        # Legend
        svg += f'''
<!-- Legend -->
<text x="20" y="{self.height - 40}" class="label">Blue: Input   Red: Output</text>
<circle cx="50" cy="{self.height - 45}" r="3" fill="#0066cc"/>
<circle cx="160" cy="{self.height - 45}" r="3" fill="#cc0000"/>

</svg>
'''
        return svg
    
    def save(self, filename: str) -> str:
        """Save SVG to file"""
        svg_content = self.generate()
        path = Path(filename)
        path.write_text(svg_content)
        return str(path.absolute())
    
    def to_string(self) -> str:
        """Return SVG as string"""
        return self.generate()


class DetailedCircuitSVG(CircuitSVG):
    """More detailed circuit visualization with logic blocks"""
    
    def generate(self) -> str:
        """Generate detailed SVG"""
        svg = f'''<svg width="{self.width}" height="{self.height}" xmlns="http://www.w3.org/2000/svg">
<defs>
  <style>
    .box {{ fill: #e8f4f8; stroke: #0066cc; stroke-width: 2; }}
    .input-box {{ fill: #ffe8e8; stroke: #cc0000; stroke-width: 2; }}
    .logic-box {{ fill: #e8ffe8; stroke: #00cc00; stroke-width: 2; }}
    .port {{ fill: #fff; stroke: #666; stroke-width: 1; }}
    .wire {{ stroke: #333; stroke-width: 2; fill: none; }}
    .label {{ font-family: monospace; font-size: 11px; }}
    .title {{ font-family: Arial; font-size: 18px; font-weight: bold; }}
  </style>
</defs>

<text x="20" y="30" class="title">Module: {self.ast.name}</text>

'''
        current_y = 60
        
        # Module Info Box
        svg += f'<rect x="20" y="{current_y}" width="300" height="80" class="box" rx="5"/>\n'
        svg += f'<text x="30" y="{current_y + 20}" class="label"><tspan font-weight="bold">Module: {self.ast.name}</tspan></text>\n'
        svg += f'<text x="30" y="{current_y + 40}" class="label">Ports: {len(self.ast.port_list)}</text>\n'
        svg += f'<text x="30" y="{current_y + 60}" class="label">Statements: {len(self.ast.statements)}</text>\n'
        
        current_y += 100
        
        # Inputs
        if any(p.direction == 'input' for p in self.ast.port_list):
            svg += f'<text x="20" y="{current_y}" class="title" font-size="14">Inputs:</text>\n'
            current_y += 25
            
            for port in self.ast.port_list:
                if port.direction == 'input':
                    svg += f'<rect x="30" y="{current_y - 15}" width="200" height="20" class="input-box" rx="3"/>\n'
                    svg += f'<text x="40" y="{current_y}" class="label">{port.name}</text>\n'
                    current_y += 30
        
        current_y += 10
        
        # Outputs
        if any(p.direction == 'output' for p in self.ast.port_list):
            svg += f'<text x="20" y="{current_y}" class="title" font-size="14">Outputs:</text>\n'
            current_y += 25
            
            for port in self.ast.port_list:
                if port.direction == 'output':
                    svg += f'<rect x="30" y="{current_y - 15}" width="200" height="20" class="input-box" rx="3"/>\n'
                    svg += f'<text x="40" y="{current_y}" class="label">{port.name}</text>\n'
                    current_y += 30
        
        current_y += 10
        
        # Logic statements
        if self.ast.statements:
            svg += f'<text x="20" y="{current_y}" class="title" font-size="14">Logic:</text>\n'
            current_y += 25
            
            for i, stmt in enumerate(self.ast.statements[:10]):
                stmt_type = type(stmt).__name__
                svg += f'<rect x="30" y="{current_y - 15}" width="200" height="20" class="logic-box" rx="3"/>\n'
                svg += f'<text x="40" y="{current_y}" class="label">{i+1}. {stmt_type}</text>\n'
                current_y += 30
        
        svg += '\n</svg>\n'
        return svg
