from pathlib import Path
from typing import Optional
from verilog_framework.verilogtoimage.logger import get_logger
from verilog_framework.verilogtoimage.converters import (
    YosysConverter, NetlistSVGConverter, CairoSVGConverter
)


class VerilogToImagePipeline:
    def __init__(self):
        self.logger = get_logger()
        self.yosys = YosysConverter()
        self.netlist_svg = NetlistSVGConverter()
        self.cairo_svg = CairoSVGConverter()
    
    def verilog_to_png(self, verilog_code: str, output_png: str = "circuit.png", 
                       intermediate_cleanup: bool = True) -> Optional[str]:
        
        self.logger.info("=" * 60)
        self.logger.info("Starting complete Verilog to PNG pipeline")
        self.logger.info("=" * 60)
        
        json_file = "circuit.json"
        svg_file = "circuit.svg"
        
        try:
            self.logger.info("Step 1: Converting Verilog to JSON using Yosys")
            json_result = self.yosys.verilog_to_json(verilog_code, json_file)
            if not json_result:
                self.logger.error("Failed at step 1: Yosys conversion")
                return None
            self.logger.info(f"[OK] JSON file created: {json_result}")
            
            self.logger.info("Step 2: Converting JSON to SVG using netlistsvg")
            svg_result = self.netlist_svg.json_to_svg(json_file, svg_file)
            if not svg_result:
                self.logger.error("Failed at step 2: netlistsvg conversion")
                return None
            self.logger.info(f"[OK] SVG file created: {svg_result}")
            
            self.logger.info("Step 3: Converting SVG to PNG using CairoSVG")
            png_result = self.cairo_svg.svg_to_png(svg_file, output_png)
            if not png_result:
                self.logger.error("Failed at step 3: CairoSVG conversion")
                return None
            self.logger.info(f"[OK] PNG file created: {png_result}")
            
            if intermediate_cleanup:
                self.logger.info("Cleaning up intermediate files")
                Path(json_file).unlink(missing_ok=True)
                Path(svg_file).unlink(missing_ok=True)
                self.logger.info("Intermediate files cleaned up")
            
            self.logger.info("=" * 60)
            self.logger.info(f"[OK] Pipeline completed successfully!")
            self.logger.info(f"Output PNG: {output_png}")
            self.logger.info("=" * 60)
            
            return str(output_png)
            
        except Exception as e:
            self.logger.error(f"Pipeline error: {str(e)}")
            return None
    
    def verilog_to_svg(self, verilog_code: str, output_svg: str = "circuit.svg") -> Optional[str]:
        
        self.logger.info("Starting Verilog to SVG pipeline")
        
        json_file = "circuit.json"
        
        try:
            self.logger.info("Step 1: Converting Verilog to JSON using Yosys")
            json_result = self.yosys.verilog_to_json(verilog_code, json_file)
            if not json_result:
                return None
            self.logger.info(f"[OK] JSON file created: {json_result}")
            
            self.logger.info("Step 2: Converting JSON to SVG using netlistsvg")
            svg_result = self.netlist_svg.json_to_svg(json_file, output_svg)
            if not svg_result:
                return None
            self.logger.info(f"[OK] SVG file created: {svg_result}")
            
            Path(json_file).unlink(missing_ok=True)
            self.logger.info(f"[OK] Pipeline completed! Output: {svg_result}")
            
            return str(svg_result)
            
        except Exception as e:
            self.logger.error(f"Pipeline error: {str(e)}")
            return None
