"""Workflow: Notifications lesen und als gelesen markieren.

Aufruf:
  python notifications.py list
  python notifications.py list --type invoice
  python notifications.py mark-all-read

Gilt als 'Posteingang' für Claude. Kein Permission-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_notifications(client: GmiClient, notification_type: str | None = None) -> list[dict]:
    """getNotificationsList liefert eine Liste.

    Je nach API-Version könnte auch ein Wrapper {notifications: [...]} oder
    {data: [...]} kommen — der Code bleibt defensiv.
    """
    params: dict[str, Any] = {}
    if notification_type:
        params["notificationType"] = notification_type
    r = client.call("getNotificationsList", **params)
    if isinstance(r, list):
        return r
    if isinstance(r, dict):
        for key in ("notifications", "records", "data", "items"):
            if key in r and isinstance(r[key], list):
                return r[key]
    return []


def mark_all_read(client: GmiClient) -> dict:
    """notificationsMarkAllRead -> {success: bool}."""
    r = client.call("notificationsMarkAllRead")
    if isinstance(r, dict):
        return r
    return {"success": True, "raw": r}


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

def format_list_md(items: list[dict]) -> str:
    if not items:
        return "## Notifications\n\n(keine)"
    lines = [f"## Notifications ({len(items)})", ""]
    for n in items:
        # Robust gegen unterschiedliche Feldnamen
        title = n.get("title") or n.get("subject") or n.get("message") or n.get("text") or "(ohne Titel)"
        created = n.get("createdAt") or n.get("date") or n.get("timestamp") or ""
        ntype = n.get("type") or n.get("notificationType") or ""
        nid = n.get("id") or n.get("uid") or n.get("notificationUid") or ""
        read = n.get("read") or n.get("isRead") or False
        marker = "o" if not read else "x"
        lines.append(f"- [{marker}] **{title}** — {ntype} | {created} | id={nid}")
    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="Notifications listen")
    ls.add_argument("--type", dest="ntype", help="Optional: Filter auf notificationType")

    sub.add_parser("mark-all-read", parents=[common], help="Alle Notifications als gelesen markieren")

    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_notifications(client, notification_type=args.ntype)
            data = {"ok": True, "count": len(items), "notifications": items}
            if args.format == "json":
                print(json.dumps(data, indent=2, ensure_ascii=False, default=str))
            else:
                print(format_list_md(items))
        elif args.cmd == "mark-all-read":
            res = mark_all_read(client)
            data = {"ok": bool(res.get("success")), "response": res}
            if args.format == "json":
                print(json.dumps(data, indent=2, ensure_ascii=False, default=str))
            else:
                status = "OK" if data["ok"] else "FEHLGESCHLAGEN"
                print(f"## Mark-all-read: {status}")
        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())
