"""Verbindungstest für GetMyInvoices API.

Gibt strukturierten Status auf stdout aus, KEINE Auth-Infos.
Exit-Code: 0=OK, 1=Fehler.
"""
import json
import os
import sys

from gmi_client import GmiClient, GmiConfigError, GmiHttpError


def main() -> int:
    if not os.environ.get("GETMYINVOICES_API_KEY"):
        print(json.dumps({"status": "MISSING_KEY"}))
        return 1

    try:
        client = GmiClient()
    except GmiConfigError:
        print(json.dumps({"status": "MISSING_KEY"}))
        return 1

    try:
        api_status = client.call("APIStatus")
    except GmiHttpError as e:
        if e.status in (401, 403):
            print(json.dumps({"status": "UNAUTHORIZED"}))
            return 1
        print(json.dumps({"status": "API_ERROR", "http": e.status}))
        return 1
    except Exception:
        print(json.dumps({"status": "NETWORK_ERROR"}))
        return 1

    try:
        account = client.call("getAccountDetails")
    except GmiHttpError as e:
        print(json.dumps({"status": "API_ERROR", "http": e.status}))
        return 1

    # Sichere Ausgabe: nur unkritische Account-Felder
    safe_fields = {}
    if isinstance(account, dict):
        for key in ("companyName", "email", "plan", "status"):
            if key in account:
                safe_fields[key] = account[key]

    print(json.dumps({
        "status": "OK",
        "api_status": api_status if isinstance(api_status, dict) else None,
        "account": safe_fields,
    }, indent=2, ensure_ascii=False))
    return 0


if __name__ == "__main__":
    sys.exit(main())
