"""Workflow: Payment Runs lesen.

Aufruf:
  python payment_runs.py list
  python payment_runs.py list --status UPCOMING

Live-Befund 2026-04-07: getPaymentRuns ist [Draft], liefert eine bare Liste,
beim Test-Account leer. Spec garantiert nur primUid + date pro Item, die echte
API kann mehr Felder liefern (status, amount, currency etc.). Workflow bleibt
defensiv und tolerant gegen unbekannte Felder. Kein Banking-Gate nötig.
"""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from typing import Any

try:
    sys.stdout.reconfigure(encoding="utf-8")
except (AttributeError, Exception):
    pass

sys.path.insert(0, str(Path(__file__).parent.parent))

from gmi_client import GmiClient, GmiHttpError  # noqa: E402


# ---------- Fetchers ----------

def fetch_payment_runs(client: GmiClient, status: str | None = None) -> list[dict]:
    """getPaymentRuns liefert eine Liste von Payment Runs.

    Defensiv gegen Wrapper-Varianten: bare Liste oder
    {paymentRuns|records|data|items: [...]}.
    """
    params: dict[str, Any] = {}
    if status:
        params["status"] = status
    r = client.call("paymentRuns", **params)
    if isinstance(r, list):
        return r
    if isinstance(r, dict):
        for key in ("paymentRuns", "records", "data", "items"):
            if key in r and isinstance(r[key], list):
                return r[key]
    return []


# ---------- Formatting ----------

def format_payment_runs_md(items: list[dict]) -> str:
    if not items:
        return "## Payment Runs\n\n(keine Payment Runs vorhanden)"
    lines = [f"## Payment Runs ({len(items)})", ""]
    for it in items:
        prim = it.get("primUid", "")
        date = it.get("date", "")
        status = it.get("status") or ""
        amount = it.get("amount")
        currency = it.get("currency") or ""
        extras = []
        if status:
            extras.append(str(status))
        if amount is not None:
            if currency:
                extras.append(f"{amount} {currency}")
            else:
                extras.append(str(amount))
        suffix = f" — {' | '.join(extras)}" if extras else ""
        lines.append(f"- **{prim}** | {date}{suffix}")
    return "\n".join(lines)


# ---------- CLI ----------

def main() -> int:
    common = argparse.ArgumentParser(add_help=False)
    common.add_argument("--format", choices=["json", "markdown"], default="markdown")

    p = argparse.ArgumentParser(parents=[common])
    sub = p.add_subparsers(dest="cmd", required=True)

    ls = sub.add_parser("list", parents=[common], help="Payment Runs listen")
    ls.add_argument("--status", help="Optional: Filter auf status (z.B. UPCOMING)")

    args = p.parse_args()

    try:
        client = GmiClient()
    except Exception as e:
        print(json.dumps({"error": "config", "detail": str(e)}))
        return 1

    try:
        if args.cmd == "list":
            items = fetch_payment_runs(client, status=args.status)
            data = {"ok": True, "count": len(items), "paymentRuns": items}
            if args.format == "json":
                print(json.dumps(data, indent=2, ensure_ascii=False, default=str))
            else:
                print(format_payment_runs_md(items))
        else:
            print(json.dumps({"error": "unknown_command", "cmd": args.cmd}))
            return 1
    except GmiHttpError as e:
        print(json.dumps({"error": "api", "status": e.status, "detail": str(e)}))
        return 1
    return 0


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