import matplotlib.pyplot as plt
import io
import base64

class ReportGenerator:
    def __init__(self, execution_data, graphs=None):
        self.execution_data = execution_data
        self.graphs = graphs or {}

    def generate_markdown_report(self):
        report = "# Execution Report\n\n"
        report += "## Metrics\n\n"
        if self.execution_data:
            for key, value in self.execution_data.items():
                report += f"- **{key}:** {value}\n"
        else:
            report += "No execution data available.\n"

        report += "\n## Graphs\n\n"
        if self.graphs:
            for graph_name, graph_data in self.graphs.items():
                report += f"### {graph_name}\n\n"
                # Assuming graph_data is a matplotlib figure
                try:
                    img_data = io.BytesIO()
                    graph_data.savefig(img_data, format='png')
                    img_data.seek(0)
                    img_base64 = base64.b64encode(img_data.read()).decode('utf-8')
                    report += f"![{graph_name}](data:image/png;base64,{img_base64})\n\n"
                except Exception as e:
                    report += f"Error displaying graph: {e}\n\n"

        else:
            report += "No graphs available.\n\n"

        report += "## Recommendations\n\n"
        report += self.generate_recommendations()  # Call the recommendation generator

        return report

    def generate_recommendations(self):
        """Placeholder for recommendation generation logic."""
        # This is where you would add logic to analyze the execution data
        # and graphs to generate meaningful recommendations.
        # For now, it returns a default message.
        return "Based on the execution data, consider optimizing the Ralph Wiggum Loop for improved efficiency. Further analysis of the graphs is recommended to identify specific bottlenecks. Consider adjusting parameters based on the observed trends."


if __name__ == '__main__':
    # Example Usage
    execution_data = {
        "Total Loops": 1000,
        "Average Loop Time": 0.05,
        "Success Rate": 0.95
    }

    # Create dummy graphs (replace with actual graph generation)
    graphs = {}
    try:
        fig, ax = plt.subplots()
        ax.plot([1, 2, 3, 4], [5, 6, 7, 8])
        ax.set_title("Sample Graph")
        graphs['Sample Graph'] = fig
    except Exception as e:
        print(f"Error creating sample graph: {e}")


    report_generator = ReportGenerator(execution_data, graphs)
    report = report_generator.generate_markdown_report()
    print(report)

    # Optionally, save the report to a file:
    with open("execution_report.md", "w") as f:
        f.write(report)
    print("Report saved to execution_report.md")