"""Parse bounce messages generated by qmail.

Qmail actually has a standard, called QSBMF (qmail-send bounce message
format), as described in

    http://cr.yp.to/proto/qsbmf.txt

This module should be conformant.

"""

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 NoTemporaryFailures, Recipients


# Other (non-standard?) intros have been observed in the wild.
introtags = [
    "We're sorry. There's a problem",
    'Check your send e-mail address.',
    'Hi. The MTA program at',
    'Hi. This is the',
    'This is the mail delivery agent at',
    'Unfortunately, your mail was not delivered',
    'Your mail message to the following',
]
acre = re.compile(r'<(?P<addr>[^>]*)>:')


class ParseState(Enum):
    start = 0
    intro_paragraph_seen = 1
    recip_paragraph_seen = 2


@public
class Qmail:
    """Parse QSBMF format bounces."""

    def process(self, msg: Message) -> tuple[Recipients, Recipients]:
        """See `BounceDetector`."""
        addresses: set[bytes] = set()
        state = ParseState.start
        for line in body_line_iterator(msg):
            line = line.strip()
            if state is ParseState.start:
                for introtag in introtags:
                    if line.startswith(introtag):
                        state = ParseState.intro_paragraph_seen
                        break
            elif state is ParseState.intro_paragraph_seen and not line:
                # Looking for the end of the intro paragraph.
                state = ParseState.recip_paragraph_seen
            elif state is ParseState.recip_paragraph_seen:
                if line.startswith('-'):
                    # We're looking at the break paragraph, so we're done.
                    break
                # At this point we know we must be looking at a recipient
                # paragraph.
                if mo := acre.match(line):
                    addresses.add(mo.group('addr').encode('us-ascii'))
                # Otherwise, it must be a continuation line, so just ignore it.
            else:
                # We're not looking at anything in particular.
                pass
        return NoTemporaryFailures, frozenset(addresses)
