"""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 enum import Enum
from flufl.bounce.interfaces import IBounceDetector, NoTemporaryFailures
from public import public
from zope.interface import implementer


# 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',
    ]
introtags_encoded = [tag.encode('ascii') for tag in introtags]
acre = re.compile(r'<(?P<addr>[^>]*)>:')


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


@public
@implementer(IBounceDetector)
class Qmail:
    """Parse QSBMF format bounces."""

    def process(self, msg):
        """See `IBounceDetector`."""
        addresses = set()
        state = ParseState.start
        for line in body_line_iterator(msg):
            line = line.strip()
            if state is ParseState.start:
                for introtag in (introtags_encoded
                                 if isinstance(line, bytes) else 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.
                mo = acre.match(line)
                if mo:
                    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, addresses
