"""Parse mystery style generated by MTA at caiwireless.net."""

import re

from email.iterators import body_line_iterator
from email.message import Message
from enum import Enum

from public import public

from flufl.bounce.interfaces import NoFailures, NoTemporaryFailures, Recipients


tcre = re.compile(r'the following recipients did not receive this message:', re.IGNORECASE)
acre = re.compile(r'<(?P<addr>[^>]*)>')


class ParseState(Enum):
    start = 0
    tag_seen = 1


@public
class Caiwireless:
    """Parse mystery style generated by MTA at caiwireless.net."""

    def process(self, msg: Message) -> tuple[Recipients, Recipients]:
        if msg.get_content_type() == 'multipart/mixed':
            state = ParseState.start
            # This format thinks it's a MIME, but it really isn't.
            for line in body_line_iterator(msg):
                line = line.strip()
                if state is ParseState.start and tcre.match(line):
                    state = ParseState.tag_seen
                elif state is ParseState.tag_seen and line:
                    if mo := acre.match(line):
                        return NoTemporaryFailures, frozenset([mo.group('addr').encode('us-ascii')])
                    break
        return NoFailures
