#!/usr/bin/env python3

from beangulp import Ingest
from beangulp.testing import main
from beancount.core.data import Transaction, Posting

import rabobank
import pdf


def classify_contra(guess_contra, primary_account):
    def _inner(extracted_entries_list, ledger_entries):
        def _classify(entry):
            if not isinstance(entry, Transaction):
                return entry
            posting = entry.postings[0]
            if posting.account != primary_account:
                return entry
            contra = guess_contra(entry)
            entry.postings.append(
                Posting(
                    contra or "Inkomsten:TODO",
                    -posting.units,
                    posting.cost,
                    posting.price,
                    None if contra else "!",
                    None,
                )
            )
            return entry

        return [
            (filename, [_classify(entry) for entry in entries], account, importer)
            for filename, entries, account, importer in extracted_entries_list
        ]

    return _inner


if __name__ == "__main__":
    importers = [
        rabobank.Importer("Activa:Betaalrekening", "EUR"),
        pdf.MollieInvoiceImporter(),
        pdf.StatiegeldImporter(),
    ]
    hooks = [classify_contra(rabobank.guess_contra, "Activa:Betaalrekening")]
    main = Ingest(importers, hooks)
    main()
