#!/usr/bin/env python3
"""Read archived DSNs and emit exact recipient hard-bounce evidence as JSON."""
import argparse
import json
import os
import re
import sys
from collections import Counter
from email import policy
from email.parser import BytesParser

MAX_HEADER = 65536
MAX_BODY = 4000000
DESTINATION = re.compile(r'^\s*rfc822\s*;\s*<?([^>\s;]+)>?\s*$', re.I)
ALLOWED_STATUS = re.compile(r'^5\.1\.(?:1|2|3|4|6|10)$')
AUTH_TERMS = ('spf', 'dkim', 'dmarc', 'authentication',
              'not permitted to relay', 'relay access denied')


def has_unambiguous_content_type(part):
    headers = part.get_all('Content-Type', [])
    return len(headers) == 1 and not headers[0].defects


def scan(maildir, company_id):
    roots = [os.path.join(maildir, 'new'), os.path.join(maildir, 'cur')]
    reference = re.compile(
        rb'(?<![0-9])([1-9][0-9]*)_([1-9][0-9]*)_([1-9][0-9]*)_bounce@post\.nuhet\.se\b', re.I)
    counts = Counter()
    statuses = Counter()
    evidence = set()

    for root in roots:
        with os.scandir(root) as entries:
            for entry in entries:
                if not entry.is_file(follow_symlinks=False):
                    continue
                counts['all_files'] += 1
                try:
                    with open(entry.path, 'rb') as stream:
                        header = bytearray()
                        while len(header) <= MAX_HEADER:
                            line = stream.readline(8192)
                            if not line:
                                break
                            header.extend(line)
                            if line in (b'\n', b'\r\n'):
                                break
                        else:
                            counts['overlong_header'] += 1
                            continue
                        if len(header) > MAX_HEADER:
                            counts['overlong_header'] += 1
                            continue
                        refs = set(reference.findall(header))
                        if not any(int(ref[0]) == company_id for ref in refs):
                            continue
                        counts['company_header_files'] += 1
                        if len(refs) != 1:
                            counts['ambiguous_reference'] += 1
                            continue
                        body = stream.read(MAX_BODY + 1)
                        if len(body) > MAX_BODY:
                            counts['oversized_message'] += 1
                            continue
                    message = BytesParser(policy=policy.default).parsebytes(
                        bytes(header) + body)
                    if message.defects or not has_unambiguous_content_type(message):
                        counts['malformed_report'] += 1
                        continue
                    if (message.get_content_type() != 'multipart/report'
                            or str(message.get_param('report-type')).lower()
                            != 'delivery-status'):
                        counts['not_delivery_report'] += 1
                        continue
                    direct_parts = message.get_payload()
                    if (not isinstance(direct_parts, list)
                            or any(part.defects for part in direct_parts)):
                        counts['malformed_report'] += 1
                        continue
                    delivery_parts = [part for part in direct_parts
                                      if part.get_content_type() == 'message/delivery-status']
                    if len(delivery_parts) != 1:
                        counts['malformed_report'] += 1
                        continue
                    blocks = delivery_parts[0].get_payload()
                    if (delivery_parts[0].defects
                            or not has_unambiguous_content_type(delivery_parts[0])
                            or not isinstance(blocks, list)
                            or any(block.defects for block in blocks)):
                        counts['malformed_report'] += 1
                        continue
                    counts['structured_report'] += 1
                    _, sendout, stat = next(iter(refs))
                    file_evidence = set()
                    file_valid = True
                    for block in blocks:
                        critical = {name: block.get_all(name, []) for name in (
                            'Final-Recipient', 'Action', 'Status', 'Diagnostic-Code')}
                        if any(len(values) > 1 for values in critical.values()):
                            counts['malformed_report'] += 1
                            file_valid = False
                            break
                        matched = DESTINATION.fullmatch(
                            str(critical['Final-Recipient'][0])
                            if critical['Final-Recipient'] else '')
                        if not matched:
                            continue
                        counts['recipient_blocks'] += 1
                        status = (str(critical['Status'][0]).strip()
                                  if critical['Status'] else '')
                        statuses[status or '(missing)'] += 1
                        action = (str(critical['Action'][0]).strip().lower()
                                  if critical['Action'] else '')
                        if action != 'failed' or not ALLOWED_STATUS.fullmatch(status):
                            continue
                        diagnostic = (str(critical['Diagnostic-Code'][0]).lower()
                                      if critical['Diagnostic-Code'] else '')
                        if any(term in diagnostic for term in AUTH_TERMS):
                            counts['authentication_diagnostic'] += 1
                            continue
                        address = matched.group(1).lower()
                        if len(address) > 255 or not re.fullmatch(
                                r'[^\s<>@]+@[^\s<>@]+', address):
                            counts['invalid_address'] += 1
                            continue
                        file_evidence.add((int(sendout), int(stat), address, status))
                    if file_valid:
                        evidence.update(file_evidence)
                    if file_valid and file_evidence:
                        counts['hard_report_files'] += 1
                except (OSError, ValueError):
                    counts['read_or_parse_errors'] += 1

    return {
        'company_id': company_id,
        'complete': not any(counts[name] for name in (
            'overlong_header', 'ambiguous_reference', 'oversized_message',
            'invalid_address', 'malformed_report', 'read_or_parse_errors')),
        'counts': dict(sorted(counts.items())),
        'statuses': dict(sorted(statuses.items())),
        'evidence': [
            {'sendout_id': sendout, 'stat_id': stat, 'email': email, 'status': status}
            for sendout, stat, email, status in sorted(evidence)
        ],
    }


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--company', type=int, required=True)
    parser.add_argument('--maildir', default='/home/bounce/Maildir')
    args = parser.parse_args()
    if args.company < 1:
        parser.error('--company must be positive')
    json.dump(scan(args.maildir, args.company), sys.stdout,
              ensure_ascii=True, separators=(',', ':'), sort_keys=True)
    sys.stdout.write('\n')


if __name__ == '__main__':
    main()
