#!/usr/bin/env python3
"""
Simple example of using VerilogToImage library
استفاده ساده از کتابخونه VerilogToImage
"""

import sys
from pathlib import Path

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent))

from verilog_framework.core import parse_verilog
from verilog_framework.visualization import GraphvizVisualizer
from verilog_framework.verilogtoimage import VerilogToImagePipeline


def example_1_basic_parsing():
    """Example 1: Basic parsing - تجزیه و تحلیل ساده"""
    print("\n" + "="*50)
    print("Example 1: Basic Parsing")
    print("="*50)
    
    code = """
    module adder(
        input a,
        input b,
        output sum
    );
        assign sum = a + b;
    endmodule
    """
    
    ast = parse_verilog(code)
    
    print(f"[OK] Module name: {ast.name}")
    print(f"[OK] Number of ports: {len(ast.port_list)}")
    
    inputs = [p.name for p in ast.port_list if p.direction == 'input']
    outputs = [p.name for p in ast.port_list if p.direction == 'output']
    
    print(f"[OK] Input ports: {inputs}")
    print(f"[OK] Output ports: {outputs}")
    print(f"[OK] Statements: {len(ast.statements)}")


def example_2_generate_diagram():
    """Example 2: Generate circuit diagram - تولید نمودار"""
    print("\n" + "="*50)
    print("Example 2: Generate Circuit Diagram")
    print("="*50)
    
    # Simple 2-bit adder
    code = """
    module adder_2bit(
        input a,
        input b,
        output result
    );
        assign result = a + b;
    endmodule
    """
    
    pipeline = VerilogToImagePipeline()
    
    # Generate SVG
    svg_file = "adder_circuit.svg"
    print(f"\n[SVG] Generating: {svg_file}")
    svg_result = pipeline.verilog_to_svg(code, svg_file)
    if svg_result:
        print(f"   [OK] SVG created successfully")
    
    # Generate PNG
    png_file = "adder_circuit.png"
    print(f"\n[PNG] Generating: {png_file}")
    png_result = pipeline.verilog_to_png(code, png_file)
    if png_result:
        print(f"   [OK] PNG created successfully")


def example_3_ast_visualization():
    """Example 3: AST Visualization - نمایش ساختار AST"""
    print("\n" + "="*50)
    print("Example 3: AST Visualization")
    print("="*50)
    
    code = """
    module counter(
        input clk,
        input reset,
        output count
    );
        reg count;

        always @(posedge clk) begin
            if (reset)
                count = 0;
            else
                count = count + 1;
        end
    endmodule
    """
    
    ast = parse_verilog(code)
    visualizer = GraphvizVisualizer()
    
    print(f"\n[GRAPH] Generating AST graph...")
    dot_content = visualizer.generate_dot(ast)
    
    # Save DOT file
    dot_file = "counter_ast.dot"
    Path(dot_file).write_text(dot_content)
    print(f"   [OK] AST saved to: {dot_file}")
    print(f"\n   You can visualize this with:")
    print(f"   $ dot -Tpng {dot_file} -o {dot_file.replace('.dot', '.png')}")


def example_4_analyze_file():
    """Example 4: Analyze a Verilog file - تجزیه فایل Verilog"""
    print("\n" + "="*50)
    print("Example 4: Analyze Verilog File")
    print("="*50)
    
    test_file = Path("test_module.v")
    
    if not test_file.exists():
        print(f"[WARN] File not found: {test_file}")
        return
    
    # Read file
    code = test_file.read_text()
    
    # Parse
    ast = parse_verilog(code)
    
    print(f"\n[FILE] {test_file}")
    print(f"   Module: {ast.name}")
    print(f"   Ports: {len(ast.port_list)}")
    print(f"   Statements: {len(ast.statements)}")
    
    # Generate circuit diagram
    pipeline = VerilogToImagePipeline()
    output_file = f"{test_file.stem}_diagram.png"
    
    print(f"\n   Generating circuit diagram...")
    result = pipeline.verilog_to_png(code, output_file)
    if result:
        print(f"   [OK] Circuit saved to: {output_file}")


def example_5_batch_processing():
    """Example 5: Batch process multiple files - پردازش جمعی فایل‌ها"""
    print("\n" + "="*50)
    print("Example 5: Batch Processing")
    print("="*50)
    
    verilog_files = list(Path(".").glob("*.v"))
    
    if not verilog_files:
        print("[WARN] No .v files found in current directory")
        return
    
    print(f"\n[FILES] Found {len(verilog_files)} Verilog files")
    
    for vfile in verilog_files[:3]:  # Process first 3 files
        print(f"\n   Processing: {vfile.name}")
        try:
            code = vfile.read_text()
            ast = parse_verilog(code)
            
            inputs = len([p for p in ast.port_list if p.direction == 'input'])
            outputs = len([p for p in ast.port_list if p.direction == 'output'])
            
            print(f"   [OK] Module: {ast.name}")
            print(f"   [OK] I/O: {inputs} inputs, {outputs} outputs")
            
        except Exception as e:
            print(f"   [ERR] Error: {str(e)[:60]}")


def main():
    """Run all examples"""
    print("\n" + "="*55)
    print("VerilogToImage - Usage Examples")
    print("="*55)
    
    examples = [
        example_1_basic_parsing,
        example_2_generate_diagram,
        example_3_ast_visualization,
        example_4_analyze_file,
        example_5_batch_processing,
    ]
    
    for example in examples:
        try:
            example()
        except Exception as e:
            print(f"[ERR] Error in {example.__name__}: {str(e)[:100]}")
    
    print("\n" + "="*55)
    print("[OK] Examples completed!")
    print("="*55 + "\n")


if __name__ == "__main__":
    main()
