# patent_3_risk_assessment.py

import random

class RiskDimension:
    """Represents a single risk dimension."""
    def __init__(self, name, description):
        self.name = name
        self.description = description

    def __str__(self):
        return f"{self.name}: {self.description}"


class RiskAssessmentEngine:
    """Engine for assessing risk across multiple dimensions."""

    def __init__(self, dimensions, weights):
        """
        Initializes the RiskAssessmentEngine.

        Args:
            dimensions (list[RiskDimension]): A list of RiskDimension objects.
            weights (dict): A dictionary mapping dimension names to their weights (0-1).
        """
        self.dimensions = dimensions
        self.weights = weights

        # Validate weights
        total_weight = sum(weights.values())
        if abs(total_weight - 1.0) > 1e-6:  # Allow for minor floating-point inaccuracies
            raise ValueError("Risk dimension weights must sum to 1.0")

    def score_advice(self, advice_text, context):
        """
        Scores AI-generated business advice across all defined dimensions.
        This is a simplified example and would require more sophisticated techniques (e.g., NLP)
        in a real-world implementation.

        Args:
            advice_text (str): The AI-generated business advice.
            context (dict): Contextual information relevant to the advice.

        Returns:
            dict: A dictionary mapping dimension names to risk scores (0-1).
        """
        risk_scores = {}
        for dimension in self.dimensions:
            # Simplified scoring logic based on keywords and context
            score = self._calculate_dimension_score(advice_text, dimension, context)
            risk_scores[dimension.name] = score

        return risk_scores

    def _calculate_dimension_score(self, advice_text, dimension, context):
        """
        Calculates the risk score for a single dimension.  This is a VERY simplified example.
        A real implementation would use NLP techniques, machine learning models, and/or
        expert systems to determine the risk score based on the advice, context, and
        dimension definition.

        Args:
            advice_text (str): The AI-generated business advice.
            dimension (RiskDimension): The risk dimension to score.
            context (dict): Contextual information.

        Returns:
            float: The risk score (0-1).
        """

        advice_text_lower = advice_text.lower()

        if dimension.name == "financial":
            # Financial risk scoring based on keywords
            if "investment" in advice_text_lower or "profit" in advice_text_lower:
                score = random.uniform(0.4, 0.8)  # Higher risk for investment advice
            else:
                score = random.uniform(0.1, 0.3)

        elif dimension.name == "legal":
            # Legal risk scoring based on keywords and context (e.g., industry)
            if "contract" in advice_text_lower or "liability" in advice_text_lower:
                score = random.uniform(0.5, 0.9)
            elif context.get("industry") == "highly_regulated":
                score = random.uniform(0.3, 0.6)
            else:
                score = random.uniform(0.1, 0.4)

        elif dimension.name == "operational":
            # Operational risk scoring based on keywords
            if "efficiency" in advice_text_lower or "process" in advice_text_lower:
                score = random.uniform(0.3, 0.7)
            else:
                score = random.uniform(0.1, 0.3)

        elif dimension.name == "reputational":
            # Reputational risk scoring based on keywords
            if "ethics" in advice_text_lower or "public image" in advice_text_lower:
                score = random.uniform(0.6, 0.9)
            else:
                score = random.uniform(0.1, 0.4)

        else:
            score = 0.0  # Unknown dimension

        # Ensure score is within bounds
        return max(0.0, min(1.0, score))



    def aggregate_risks(self, risk_scores):
        """
        Aggregates risk scores across dimensions using weighted average.

        Args:
            risk_scores (dict): A dictionary mapping dimension names to risk scores.

        Returns:
            float: The overall risk score (0-1).
        """
        overall_risk = 0
        for dimension_name, score in risk_scores.items():
            overall_risk += score * self.weights.get(dimension_name, 0)  # Use get to handle missing weights

        return overall_risk

    def generate_risk_report(self, advice_text, risk_scores, overall_risk, context):
        """
        Generates a human-readable risk report.

        Args:
            advice_text (str): The AI-generated business advice.
            risk_scores (dict): A dictionary mapping dimension names to risk scores.
            overall_risk (float): The overall risk score.
            context (dict): Contextual information.

        Returns:
            str: A human-readable risk report.
        """
        report = f"Risk Assessment Report for AI Advice:\n\n"
        report += f"Advice: {advice_text}\n\n"
        report += f"Context: {context}\n\n"
        report += "Dimension-Specific Risks:\n"
        for dimension in self.dimensions:
            score = risk_scores.get(dimension.name, "N/A")
            report += f"- {dimension.name}: {score:.2f} ({dimension.description})\n"

        report += f"\nOverall Risk Score: {overall_risk:.2f}\n"

        if overall_risk > 0.7:
            report += "\nWARNING: This advice carries a high level of risk. Proceed with caution."
        elif overall_risk > 0.4:
            report += "\nCaution: This advice carries a moderate level of risk. Further review is recommended."
        else:
            report += "\nThis advice appears to have a low level of risk."

        return report



# Example Usage:
if __name__ == "__main__":
    # Define risk dimensions
    financial_risk = RiskDimension("financial", "Potential for financial loss or instability.")
    legal_risk = RiskDimension("legal", "Potential for legal challenges or non-compliance.")
    operational_risk = RiskDimension("operational", "Potential for disruption to business operations.")
    reputational_risk = RiskDimension("reputational", "Potential for damage to the company's reputation.")

    dimensions = [financial_risk, legal_risk, operational_risk, reputational_risk]

    # Define weights for each dimension (must sum to 1.0)
    weights = {
        "financial": 0.3,
        "legal": 0.25,
        "operational": 0.25,
        "reputational": 0.2
    }

    # Create a RiskAssessmentEngine
    engine = RiskAssessmentEngine(dimensions, weights)

    # Example AI-generated business advice
    advice = "Invest heavily in new marketing campaigns to increase brand awareness and boost sales.  Review all supplier contracts for potential liabilities."

    # Example context
    context = {
        "industry": "highly_regulated",
        "market_conditions": "volatile"
    }

    # Score the advice
    risk_scores = engine.score_advice(advice, context)

    # Aggregate the risks
    overall_risk = engine.aggregate_risks(risk_scores)

    # Generate a risk report
    report = engine.generate_risk_report(advice, risk_scores, overall_risk, context)

    # Print the report
    print(report)
