import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent))

from verilog_framework.core import VerilogLexer, VerilogParser
from verilog_framework.visualization import GraphvizVisualizer
from verilog_framework.verilogtoimage import VerilogToImagePipeline, get_logger


class VerilogProcessor:
    def __init__(self, file_path: str):
        self.file_path = Path(file_path)
        self.ast = None
        self.logger = get_logger()

    def load_file(self) -> str:
        if not self.file_path.exists():
            raise FileNotFoundError(f"File not found: {self.file_path}")
        return self.file_path.read_text()

    def process(self):
        verilog_code = self.load_file()
        lexer = VerilogLexer(verilog_code)
        tokens = lexer.tokenize()
        parser = VerilogParser(tokens)
        self.ast = parser.parse()
        return self.ast

    def visualize(self, output_file: str = None) -> str:
        if not self.ast:
            raise RuntimeError("AST not generated. Call process() first.")
        
        if output_file is None:
            output_file = self.file_path.stem + "_graph"
        
        visualizer = GraphvizVisualizer()
        dot = visualizer.generate_dot(self.ast)
        
        try:
            import graphviz
            graph = graphviz.Source(dot)
            graph.render(output_file, format='svg', cleanup=True)
            return f"{output_file}.svg"
        except (ImportError, Exception):
            dot_file = Path(output_file + ".dot")
            dot_file.write_text(dot)
            return str(dot_file)

    def generate_circuit_image(self, output_file: str = None, format: str = "svg") -> str:
        if format not in ["svg", "png"]:
            raise ValueError("Format must be 'svg' or 'png'")
        
        if output_file is None:
            if format == "svg":
                output_file = self.file_path.stem + "_circuit.svg"
            else:
                output_file = self.file_path.stem + "_circuit.png"
        
        verilog_code = self.load_file()
        pipeline = VerilogToImagePipeline()
        
        if format == "svg":
            return pipeline.verilog_to_svg(verilog_code, output_file)
        else:
            return pipeline.verilog_to_png(verilog_code, output_file)


def main():
    if len(sys.argv) < 2:
        print("Usage: python cli.py <verilog_file> [options]")
        print("\nOptions:")
        print("  --png              Generate circuit PNG image")
        print("  --svg              Generate circuit SVG image")
        print("  --ast              Generate AST visualization")
        print("  --all              Generate all outputs")
        return
    
    verilog_file = sys.argv[1]
    options = sys.argv[2:] if len(sys.argv) > 2 else ["--ast"]
    
    try:
        processor = VerilogProcessor(verilog_file)
        ast = processor.process()
        
        print(f"Module: {ast.name}")
        print(f"Ports: {len(ast.port_list)}")
        print(f"Declarations: {len(ast.declarations)}")
        print(f"Statements: {len(ast.statements)}")
        print()
        
        if "--all" in options or "--ast" in options:
            output = processor.visualize()
            print(f"✓ AST visualization saved to: {output}")
        
        if "--all" in options or "--svg" in options:
            output = processor.generate_circuit_image(format="svg")
            if output:
                print(f"✓ Circuit SVG saved to: {output}")
        
        if "--all" in options or "--png" in options:
            output = processor.generate_circuit_image(format="png")
            if output:
                print(f"✓ Circuit PNG saved to: {output}")
    
    except FileNotFoundError as e:
        print(f"Error: {e}")
    except SyntaxError as e:
        print(f"Parse Error: {e}")


if __name__ == "__main__":
    main()
