#!/usr/bin/env python3

import os
import subprocess
import json

class RegressionSuite:
    def __init__(self, attack_reports_dir, report_template_path):
        self.attack_reports_dir = attack_reports_dir
        self.report_template_path = report_template_path
        self.vulnerabilities_found = []

    def load_attack_reports(self):
        attack_reports = []
        for filename in os.listdir(self.attack_reports_dir):
            if filename.endswith(".json"):
                filepath = os.path.join(self.attack_reports_dir, filename)
                try:
                    with open(filepath, 'r') as f:
                        report = json.load(f)
                        attack_reports.append(report)
                except Exception as e:
                    print(f"Error loading report {filename}: {e}")
        return attack_reports

    def run_regression_test(self, attack_report):
        """Simulates running the attack described in the report and checks if it still works."""
        # This is a placeholder.  In a real system, this would execute the attack.
        # The specifics of the attack would be defined in the attack_report.
        # For now, we just check if the report has the key 'exploit_command'.
        # If it does, we assume the vulnerability *should* be fixed.  If it doesn't,
        # then the regression test passes.

        if 'exploit_command' in attack_report:
            # Simulate running the exploit command
            command = attack_report['exploit_command']
            try:
               # This is a placeholder - replace with actual exploit execution
               result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=5)
               # Check for successful exploit (e.g., non-zero exit code)
               if result.returncode == 0:
                   # Exploit still works!  Vulnerability NOT fixed.
                   self.vulnerabilities_found.append(attack_report['vulnerability_id'])
                   print(f"Vulnerability {attack_report['vulnerability_id']} still present! Command: {command}")

            except subprocess.TimeoutExpired:
                print(f"Attack {attack_report['vulnerability_id']} timed out - assuming fixed.")
                return True  # Assume timeout means fixed
            except Exception as e:
                print(f"Error running command {command}: {e}")
                return False # Assume failure to run means fixed

            return False # Vulnerability found, regression test failed.

        else:
            # No exploit command, assuming vulnerability doesn't exist or is mitigated.
            return True # Regression test passes.

    def generate_report(self):
        """Generates a report based on the template."""
        with open(self.report_template_path, 'r') as f:
            template = f.read()

        report = template.format(num_reports=len(self.attack_reports),
                                  num_vulnerabilities_found=len(self.vulnerabilities_found),
                                  vulnerabilities_found=self.vulnerabilities_found)
        return report

    def run_suite(self):
        self.attack_reports = self.load_attack_reports()
        all_tests_passed = True

        for report in self.attack_reports:
            if not self.run_regression_test(report):
                all_tests_passed = False

        report = self.generate_report()
        print(report)

        return all_tests_passed

if __name__ == "__main__":
    # Example usage (replace with actual paths)
    attack_reports_dir = "/mnt/e/genesis-system/core/rwl/hardening/attack_reports"
    report_template_path = "/mnt/e/genesis-system/core/rwl/hardening/regression_report_template.md"

    # Create dummy attack reports directory and files if they don't exist
    if not os.path.exists(attack_reports_dir):
        os.makedirs(attack_reports_dir)
        # Create some dummy attack reports
        dummy_report1 = {"vulnerability_id": "CVE-2023-1234", "exploit_command": "echo 'Exploit successful!' > /tmp/evil.txt"}
        dummy_report2 = {"vulnerability_id": "CVE-2023-5678"}
        dummy_report3 = {"vulnerability_id": "CVE-2023-9012", "exploit_command": "rm -rf /"} #Simulate a critical vulnerability

        with open(os.path.join(attack_reports_dir, "report1.json"), "w") as f:
            json.dump(dummy_report1, f)
        with open(os.path.join(attack_reports_dir, "report2.json"), "w") as f:
            json.dump(dummy_report2, f)
        with open(os.path.join(attack_reports_dir, "report3.json"), "w") as f:
            json.dump(dummy_report3, f)

    suite = RegressionSuite(attack_reports_dir, report_template_path)
    if suite.run_suite():
        print("All regression tests passed!")
    else:
        print("Some regression tests failed.")