class TemplateService:
    """
    Service to fetch and format email templates from blob storage or JSON config.
    Designed to be a reusable package component.
    """

    def __init__(self, blob_config_service, config_blob_name="subject.json"):
        """
        :param blob_config_service: Service used to fetch JSON from blob storage.
        :param config_blob_name: Name of the JSON blob containing templates.
        """
        self.blob_config_service = blob_config_service
        self.config_blob_name = config_blob_name

        try:
            self.config = self.blob_config_service.get_json(config_blob_name)
            if not self.config:
                raise ValueError(f"Template config '{config_blob_name}' is empty or invalid")
        except Exception as e:
            raise ValueError(f"Failed to load template configuration: {e}")

    async def get_email_template(self, key: str, **kwargs):
        """
        Fetch and format an email template by key.
        :param key: Template key (e.g. 'welcome_email')
        :param kwargs: Placeholder values for formatting
        :return: Tuple[str, str] -> (subject, body)
        """
        if key not in self.config:
            raise ValueError(f"Email template '{key}' not found in configuration")

        template = self.config[key]

        try:
            subject = template.get("subject", "No Subject Defined").format(**kwargs)
        except KeyError as e:
            subject = f"[Missing placeholder: {e.args[0]}]"

        try:
            body = template.get("body", "No Body Defined").format(**kwargs)
        except KeyError as e:
            body = f"[Missing placeholder: {e.args[0]}]"

        return subject, body

    def _create_failure_details_html(self, failures: list[dict]):
        """
        Create a simple HTML table summarizing failure details.
        """
        if not failures:
            return ""

        rows = "".join(
            f"<tr><td>{f.get('name', 'Unknown')}</td><td>{f.get('reason', 'No reason provided')}</td></tr>"
            for f in failures
        )
        return f"<table border='1'>{rows}</table>"
