# constitutional_guard.py
import re
import logging
from datetime import datetime

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class Directive:
    def __init__(self, name, principle, description):
        self.name = name
        self.principle = principle
        self.description = description

class ConstitutionalGuard:
    def __init__(self, constitution_file="E__genesis-system_CONSTITUTION_PRIME_DIRECTIVES_CORRECTED.md"):
        self.constitution_file = constitution_file
        self.directives = self.parse_directives()
        self.audit_trail = []

    def parse_directives(self):
        """Parses the constitution file and extracts the prime directives."""
        try:
            with open(self.constitution_file, 'r') as f:
                constitution_text = f.read()

            directives = []

            # Regex to find directives
            directive_matches = re.findall(r"## PRIME DIRECTIVE (\d+): ([A-Z]+)\n\n### The Principle\n\"(.*?)\"\n\n(.*?)(?=## PRIME DIRECTIVE|$)",
                                            constitution_text, re.DOTALL)

            for match in directive_matches:
                directive_name = match[1].strip()
                directive_principle = match[2].strip()
                directive_description = match[3].strip()
                directives.append(Directive(directive_name, directive_principle, directive_description))

            return directives

        except FileNotFoundError:
            logging.error(f"Constitution file not found: {self.constitution_file}")
            return []
        except Exception as e:
            logging.error(f"Error parsing constitution: {e}")
            return []

    def validate_action(self, action, context):
        """Validates an action against the constitutional rules."""
        scores = self.score_compliance(action, context)
        is_compliant = all(score > 0.5 for score in scores.values())  # Adjust threshold as needed

        if not is_compliant:
            violation_details = self.handle_violation(action, context, scores)
            return False, violation_details
        else:
            self.log_compliance(action, context, scores, compliant=True)
            return True, "Action is compliant."

    def score_compliance(self, action, context):
        """Scores the compliance of an action against each prime directive."""
        scores = {}
        for directive in self.directives:
            scores[directive.name] = self.calculate_directive_score(action, context, directive)
        return scores

    def calculate_directive_score(self, action, context, directive):
        """Calculates a compliance score for a specific directive.
           This is a placeholder and should be replaced with more sophisticated logic."""

        # Placeholder logic: Check if the action description mentions the directive.
        if directive.name.lower() in str(action).lower(): # check if directive name is mentioned
            score = 0.8  # High score if the directive is mentioned
        else:
            score = 0.3  # Lower score if not mentioned

        # Adjust score based on context (example)
        if "revenue" in str(context).lower() and directive.name == "REVENUE":
            score += 0.2  # Boost score if revenue context aligns with revenue directive
            score = min(1.0, score) # cap at 1.0

        return score

    def handle_violation(self, action, context, scores):
        """Handles a constitutional violation."""
        violation_details = {
            "action": action,
            "context": context,
            "compliance_scores": scores,
            "timestamp": datetime.now().isoformat()
        }

        logging.warning(f"Constitutional Violation Detected: {violation_details}")
        self.log_compliance(action, context, scores, compliant=False)

        # Implement escalation logic here (e.g., send an alert to a human supervisor)
        # For now, just return the details
        return violation_details

    def log_compliance(self, action, context, scores, compliant):
        """Logs the compliance decision to the audit trail."""
        log_entry = {
            "action": action,
            "context": context,
            "compliance_scores": scores,
            "compliant": compliant,
            "timestamp": datetime.now().isoformat()
        }
        self.audit_trail.append(log_entry)
        logging.info(f"Compliance Log: {log_entry}")

    def generate_compliance_report(self):
        """Generates a compliance report from the audit trail."""
        report = {
            "total_actions": len(self.audit_trail),
            "compliant_actions": sum(1 for log in self.audit_trail if log["compliant"]),
            "non_compliant_actions": sum(1 for log in self.audit_trail if not log["compliant"]),
            "audit_trail": self.audit_trail
        }
        return report

    def get_directive_by_name(self, name):
        """Retrieves a directive object by its name."""
        for directive in self.directives:
            if directive.name == name:
                return directive
        return None

# Example Usage
if __name__ == '__main__':
    guard = ConstitutionalGuard()

    # Example Action and Context
    action1 = "Implement a new memory storage system."
    context1 = "Improving data retention and recall."

    action2 = "Initiate a marketing campaign without considering budget."
    context2 = "Increase brand awareness."

    action3 = "Develop a new AI model to optimize revenue generation."
    context3 = "Maximize profits for the company."


    # Validate Actions
    is_compliant1, details1 = guard.validate_action(action1, context1)
    print(f"Action 1 Compliance: {is_compliant1}, Details: {details1}")

    is_compliant2, details2 = guard.validate_action(action2, context2)
    print(f"Action 2 Compliance: {is_compliant2}, Details: {details2}")

    is_compliant3, details3 = guard.validate_action(action3, context3)
    print(f"Action 3 Compliance: {is_compliant3}, Details: {details3}")


    # Generate Compliance Report
    report = guard.generate_compliance_report()
    print("\nCompliance Report:")
    print(report)

    # Access a specific directive
    revenue_directive = guard.get_directive_by_name("REVENUE")
    if revenue_directive:
        print(f"\nRevenue Directive Principle: {revenue_directive.principle}")