from smartcard.System import readers
import requests

API_BASE = "https://DEINE-DOMAIN.DE/gutschein-api"
API_KEY = "HIER_DEIN_API_KEY"


def get_uid():
    r = readers()
    if not r:
        raise RuntimeError("Kein Reader gefunden")

    reader = r[0]
    connection = reader.createConnection()
    connection.connect()

    get_uid_cmd = [0xFF, 0xCA, 0x00, 0x00, 0x00]
    data, sw1, sw2 = connection.transmit(get_uid_cmd)

    if sw1 != 0x90 or sw2 != 0x00:
        raise RuntimeError(f"UID konnte nicht gelesen werden: {sw1:02X} {sw2:02X}")

    return ''.join(format(x, '02X') for x in data)


def api_get(path):
    headers = {"X-API-Key": API_KEY}
    return requests.get(f"{API_BASE}{path}", headers=headers, timeout=10)


def api_post(path, payload):
    headers = {
        "X-API-Key": API_KEY,
        "Content-Type": "application/json"
    }
    return requests.post(f"{API_BASE}{path}", json=payload, headers=headers, timeout=10)


while True:
    print("\n--- Gutschein-System ---")
    print("1 = Karte registrieren")
    print("2 = Guthaben prüfen")
    print("3 = Aufladen")
    print("4 = Abbuchen")
    print("5 = Letzte Transaktionen")
    print("6 = Beenden")

    choice = input("Auswahl: ").strip()

    if choice == "6":
        break

    try:
        uid = get_uid()
        print("Karte erkannt:", uid)

        if choice == "1":
            r = api_post("/register_card.php", {"uid": uid})
            print(r.text)

        elif choice == "2":
            r = api_get(f"/get_balance.php?uid={uid}")
            print(r.text)

        elif choice == "3":
            amount = input("Betrag in Euro (z.B. 10.00): ").strip()
            cents = int(round(float(amount.replace(",", ".")) * 100))
            r = api_post("/topup.php", {"uid": uid, "amount_cents": cents})
            print(r.text)

        elif choice == "4":
            amount = input("Betrag in Euro (z.B. 2.50): ").strip()
            cents = int(round(float(amount.replace(",", ".")) * 100))
            r = api_post("/debit.php", {"uid": uid, "amount_cents": cents})
            print(r.text)

        elif choice == "5":
            r = api_get(f"/history.php?uid={uid}")
            print(r.text)

        else:
            print("Ungültige Auswahl")

    except Exception as e:
        print("Fehler:", e)
