#!/usr/bin/env python3

from pathlib import Path
from urllib.request import urlopen
from datetime import datetime
from fints.client import FinTS3PinTanClient

# Konfiguration laden
# Konfiguration laden
config = {}

# Zuerst Home-Verzeichnis prüfen
config_file = Path.home() / ".ing.conf"

# Falls nicht vorhanden, Datei neben dem Skript verwenden
if not config_file.exists():
    config_file = Path(__file__).parent / ".ing.conf"

with open(config_file, encoding="utf-8") as f:
    for line in f:
        line = line.strip()

        # Leere Zeilen und Kommentare ignorieren
        if not line or line.startswith("#"):
            continue

        if "=" not in line:
            continue

        key, value = line.split("=", 1)
        config[key] = value
# ING
USER = config["ING_USER"]
PIN = config["ING_PIN"]
TARGET_IBAN = config["ING_IBAN"]

# ioBroker
IOBROKER_HOST = config["IOBROKER_HOST"]
IOBROKER_PORT = config["IOBROKER_PORT"]
IOBROKER_DP = config["IOBROKER_DP"]

# ING Deutschland
BLZ = "50010517"

LOGFILE = Path.home() / "logs" / "balance.log"

try:
    client = FinTS3PinTanClient(
        BLZ,
        USER,
        PIN,
        "https://fints.ing.de/fints/",
        product_id="PythonFinTS"
    )

    with client:
        for account in client.get_sepa_accounts():

            if account.iban != TARGET_IBAN:
                continue

            balance = client.get_balance(account)

            # Zahlenwert extrahieren
            value = float(balance.amount.amount)

            # An ioBroker senden
            url = (
                f"http://{IOBROKER_HOST}:{IOBROKER_PORT}"
                f"/set/{IOBROKER_DP}?value={value}"
            )

            urlopen(url).read()

            break

        else:
            with open(LOGFILE, "a") as log:
                log.write(
                    f"{datetime.now():%Y-%m-%d %H:%M:%S} "
                    f"IBAN nicht gefunden: {TARGET_IBAN}\n"
                )

except Exception as e:
    with open(LOGFILE, "a") as log:
        log.write(
            f"{datetime.now():%Y-%m-%d %H:%M:%S} "
            f"FEHLER: {e}\n"
        )