import re
from dataclasses import dataclass
from pathlib import Path

from db import get_session
from imap_tools import MailBox
from sqlalchemy import text


@dataclass
class ImapCredentials:
    server: str
    username: str
    password: str


creds = ImapCredentials("mail.global-cube.com", "forderung", "Navision2013!")
fileserver = Path("C:\\Projekte\\Reisacher-Fileserver")


def main():
    db = next(get_session())
    q = db.execute(text("SELECT Client_DB, Document_No FROM dbo.Forderungen")).fetchall()
    lookup = {row[1]: row[0] for row in q}

    with MailBox(creds.server).login(creds.username, creds.password) as mb:
        messages = mb.fetch(
            mark_seen=True,
            bulk=True,
            limit=100,
            headers_only=False,
            reverse=True,
        )

        for msg in messages:
            match = re.findall(r"([WV]\w+\d+)", msg.subject)
            if not match:
                print(msg.subject)
                continue
            print(match)
            invoice_no = match[0]
            if invoice_no not in lookup:
                continue
            client_db = lookup[invoice_no]
            print(invoice_no, client_db)
            attachments = {att.filename: att.payload for att in msg.attachments if att.size > 0}
            for file, content in attachments.items():
                filename: Path = fileserver / client_db / invoice_no / file
                filename.parent.mkdir(exist_ok=True, parents=True)
                filename.write_bytes(content)
                print(filename)


if __name__ == "__main__":
    main()
