import logging
from typing import Dict, List, Optional

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


class PreMortemTemplateGenerator:
    """
    A class for generating pre-mortem templates based on PRD content.
    """

    def __init__(self):
        """
        Initializes the PreMortemTemplateGenerator.
        """
        pass

    def generate_template(self, prd_content: Dict) -> str:
        """
        Generates a pre-mortem template string based on the provided PRD content.

        Args:
            prd_content (Dict): A dictionary containing the PRD content.

        Returns:
            str: A string containing the generated pre-mortem template.
        """
        template = f"""
        # Pre-Mortem Analysis

        ## What could fail?

        Based on the PRD content:
        {self._extract_potential_failures(prd_content)}

        ## What assumptions are we making?

        {self._extract_assumptions(prd_content)}

        ## What do we not fully understand?

        {self._extract_unknowns(prd_content)}

        ## Rollback plan

        {self._generate_rollback_plan(prd_content)}
        """
        return template

    def _extract_potential_failures(self, prd_content: Dict) -> str:
        """
        Extracts potential failure points from the PRD content.

        Args:
            prd_content (Dict): A dictionary containing the PRD content.

        Returns:
            str: A string containing a list of potential failure points.
        """
        try:
            # This is a placeholder; in a real implementation, this would involve
            # analyzing the PRD content for keywords and phrases that indicate
            # potential risks or failure points.  For example, look for "risk",
            # "failure", "bottleneck", "error", "unreliable", etc.
            # This would likely involve NLP techniques.  For now, we just return
            # a generic message.
            return "- Insufficient resources allocated to the project.\n- Unexpected dependencies on external systems.\n- Technical challenges in implementing key features.\n- Security vulnerabilities discovered during development.\n- Performance bottlenecks under heavy load."
        except Exception as e:
            logging.error(f"Error extracting potential failures: {e}")
            return "Error extracting potential failures. Please review the PRD manually."

    def _extract_assumptions(self, prd_content: Dict) -> str:
        """
        Extracts assumptions from the PRD content.

        Args:
            prd_content (Dict): A dictionary containing the PRD content.

        Returns:
            str: A string containing a list of assumptions.
        """
        try:
            # Similar to the above, this is a placeholder.  A real implementation
            # would involve identifying statements in the PRD that are presented
            # as facts but could potentially be false or uncertain.  Look for phrases
            # like "we assume", "it is assumed", "we expect", "we anticipate", etc.
            return "- We assume that all external APIs will be available and performant.\n- We assume that the user base will grow at a steady rate.\n- We assume that the infrastructure will be able to handle the expected load.\n- We assume that the data will be accurate and complete.\n- We assume that the team will have the necessary skills and expertise."
        except Exception as e:
            logging.error(f"Error extracting assumptions: {e}")
            return "Error extracting assumptions. Please review the PRD manually."

    def _extract_unknowns(self, prd_content: Dict) -> str:
        """
        Extracts unknowns from the PRD content.

        Args:
            prd_content (Dict): A dictionary containing the PRD content.

        Returns:
            str: A string containing a list of unknowns.
        """
        try:
            # This is another placeholder.  This would involve identifying areas
            # where the PRD is unclear or incomplete, or where there are significant
            # uncertainties about the project's scope, requirements, or implementation.
            # Look for phrases like "we don't know", "it is unclear", "we are unsure", etc.
            return "- The exact performance characteristics of the new database.\n- The impact of the new feature on existing user workflows.\n- The potential for unexpected security vulnerabilities.\n- The scalability limits of the system.\n- The long-term maintenance costs."
        except Exception as e:
            logging.error(f"Error extracting unknowns: {e}")
            return "Error extracting unknowns. Please review the PRD manually."

    def _generate_rollback_plan(self, prd_content: Dict) -> str:
        """
        Generates a basic rollback plan based on the PRD content.

        Args:
            prd_content (Dict): A dictionary containing the PRD content.

        Returns:
            str: A string containing a rollback plan.
        """
        try:
            # This is a placeholder.  A real implementation would involve analyzing
            # the PRD to identify the key steps that need to be taken to revert the
            # system to its previous state in the event of a failure.  This might
            # involve restoring backups, disabling new features, or reverting code changes.
            return "- Create a system backup before deployment.\n- Implement a feature flag to quickly disable the new feature.\n- Develop a script to revert database changes.\n- Prepare a communication plan to notify users of the rollback.\n- Designate a team to monitor the system during the rollback."
        except Exception as e:
            logging.error(f"Error generating rollback plan: {e}")
            return "Error generating rollback plan. Please review the PRD manually."


if __name__ == '__main__':
    # Example usage
    prd_content = {
        "title": "New Feature X",
        "description": "This feature will do something amazing.",
        "risks": ["Potential performance issues", "Security vulnerabilities"],
        "assumptions": ["External API will be available"],
        "unknowns": ["Scalability limits"]
    }

    generator = PreMortemTemplateGenerator()
    template = generator.generate_template(prd_content)
    print(template)