"""
Module: outreach_gen.py
Description: Generates personalized outreach sequences.
"""

import logging
import random
from typing import List, Dict, Optional

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


class OutreachSequenceGenerator:
    """
    Generates personalized outreach sequences based on provided data and templates.
    """

    def __init__(self, templates: Dict[str, List[str]]):
        """
        Initializes the OutreachSequenceGenerator with templates for different outreach stages.

        Args:
            templates (Dict[str, List[str]]): A dictionary where keys are stage names (e.g., "initial", "followup1")
                                                and values are lists of string templates for that stage.
        """
        self.templates = templates
        self.logger = logging.getLogger(__name__)

    def generate_sequence(self, prospect_data: Dict[str, str], sequence_stages: List[str]) -> List[str]:
        """
        Generates a personalized outreach sequence.

        Args:
            prospect_data (Dict[str, str]): A dictionary containing prospect-specific data for personalization.
                                                Example: {"first_name": "Alice", "company_name": "Acme Corp"}
            sequence_stages (List[str]): A list of stage names defining the sequence (e.g., ["initial", "followup1", "followup2"]).

        Returns:
            List[str]: A list of personalized outreach messages, one for each stage in the sequence. Returns an empty list on error.
        """
        sequence = []
        for stage in sequence_stages:
            try:
                message = self._generate_message(stage, prospect_data)
                if message:
                    sequence.append(message)
                else:
                    self.logger.warning(f"No template found for stage: {stage}. Skipping this stage.")
            except KeyError as e:
                self.logger.error(f"KeyError during message generation: {e}. Ensure data keys match template placeholders.")
                return [] # Stop generation if there is an error

            except Exception as e:
                self.logger.exception(f"An unexpected error occurred during message generation for stage {stage}: {e}")
                return [] # Stop generation if there is an error
        return sequence

    def _generate_message(self, stage: str, prospect_data: Dict[str, str]) -> Optional[str]:
        """
        Generates a single personalized message for a given stage.

        Args:
            stage (str): The name of the stage (e.g., "initial", "followup1").
            prospect_data (Dict[str, str]): A dictionary containing prospect-specific data for personalization.

        Returns:
            Optional[str]: A personalized outreach message, or None if no template is found for the stage.
        """
        if stage not in self.templates:
            self.logger.warning(f"No templates found for stage: {stage}")
            return None

        template = random.choice(self.templates[stage])  # Select a random template for the stage
        try:
            message = template.format(**prospect_data)  # Personalize the template
            return message
        except KeyError as e:
             self.logger.error(f"KeyError during template formatting: {e}.  Check template placeholders and data keys.")
             raise  # Re-raise the exception to be caught in the outer method

        except ValueError as e:
            self.logger.error(f"ValueError during template formatting: {e}. Check template formatting (e.g., mismatched braces).")
            raise # Re-raise the exception to be caught in the outer method


def load_templates_from_file(file_path: str) -> Dict[str, List[str]]:
    """
    Loads outreach templates from a file.

    Args:
        file_path (str): The path to the file containing the templates.  The file should contain a JSON-like dictionary.
                         Example: {"initial": ["Hello {first_name}, ..."], "followup1": ["Just checking in, {first_name}"]}

    Returns:
        Dict[str, List[str]]: A dictionary containing the loaded templates.  Returns an empty dictionary if the file cannot be loaded.
    """
    import json
    try:
        with open(file_path, 'r') as f:
            templates = json.load(f)
        return templates
    except FileNotFoundError:
        logging.error(f"Template file not found: {file_path}")
        return {}
    except json.JSONDecodeError:
        logging.error(f"Error decoding JSON from template file: {file_path}")
        return {}
    except Exception as e:
        logging.exception(f"An unexpected error occurred while loading templates from file {file_path}: {e}")
        return {}


if __name__ == '__main__':
    # Example Usage
    template_file = "/mnt/e/genesis-system/core/revenue/templates.json" # Create a dummy templates.json file

    # Create a dummy file at /mnt/e/genesis-system/core/revenue/templates.json
    with open(template_file, "w") as f:
        f.write("""
        {
            "initial": [
                "Hello {first_name}, I saw you at {company_name}.",
                "Hi {first_name}, I am reaching out from {my_company}."
            ],
            "followup1": [
                "Just checking in, {first_name}.",
                "Any thoughts on this {first_name}?"
            ],
            "followup2": [
               "Last try {first_name}, is it a no?"
            ]
        }
        """)

    templates = load_templates_from_file(template_file)
    if templates:
      generator = OutreachSequenceGenerator(templates)

      prospect_data = {
          "first_name": "Alice",
          "company_name": "Acme Corp",
          "my_company": "Genesis Systems"
      }

      sequence_stages = ["initial", "followup1", "followup2"]

      outreach_sequence = generator.generate_sequence(prospect_data, sequence_stages)

      if outreach_sequence:
          for i, message in enumerate(outreach_sequence):
              print(f"Stage {i+1}: {message}")
      else:
          print("Failed to generate outreach sequence.")
    else:
      print("Could not load templates")