import json
import openpyxl

data = {}
data["databases"] = []

BLZ = 1
BIC = 2
INSTITUTE = 3
CITY = 4
ORGANIZATION = 6
URL = 24


def get_logo(bank: str) -> str:
    if bank in ("dsgv", "bvr", "comdirect", "dkb"):
        return bank

    return "bank"


# Open official list
wb = openpyxl.load_workbook("fints_institute.xlsx", data_only=True)
worksheet = wb["fints_institute_Master"]
for row in worksheet.iter_rows(min_row=2):
    if row[BLZ].value:
        data["databases"].append(
            {
                "blz": row[BLZ].value,
                "bic": str(row[BIC].value).lower(),
                "institute": row[INSTITUTE].value,
                "logo": get_logo(
                    "comdirect"
                    if "comdirect" in row[INSTITUTE].value.lower()
                    else (
                        row[ORGANIZATION].value.lower()
                        if row[ORGANIZATION].value
                        else ""
                    )
                ),
                "url": row[URL].value,
                "city": row[CITY].value,
            }
        )

# Add custom entries
# TODO: Consider automatically checking for missing entries in:
# https://github.com/aqbanking/aqbanking/blob/23ea0303a999e87656f992f2f479dcf75ade8113/
# src/libs/plugins/bankinfo/generic/de.tar.bz2
for i in ("66", "77", "88", "99"):
    data["databases"].append(
        {
            "blz": "200411" + i,
            "bic": "cobadehd0" + i,
            "institute": "comdirect bank AG",
            "logo": "comdirect",
            "url": "https://fints.comdirect.de/fints",
            "city": "Quickborn",
        }
    )

# Demo data for testing purpose
data["databases"].append(
    {
        "blz": "00000000",
        "bic": "",
        "institute": "Demo Bank",
        "logo": "bank",
        "url": "http://0.0.0.0",
        "city": "Virtual",
    }
)

with open("resources/database.json", "w") as outfile:
    json.dump(data, outfile)
