"""Report-Workflow: formatiert ein Lauf-Log (JSONL) als Markdown oder JSON.

Markdown-Output enthält pro Beleg:

- UID, Status, Lieferant, Brutto-Betrag
- Aktions-/Begründungs-Spalte (Note aus dem Lauf-Log)
- Klickbaren ``[PDF](file://...)``-Link, falls ``pdf_path`` im Eintrag steht

Bundle-MVP-Stand v0.10.0: keine Kategorisierung, kein Compliance-Hold,
keine Skonto-Sektion. Diese Erweiterungen folgen in späteren Wellen.
"""
from __future__ import annotations

import argparse
import json
import sys
from collections import Counter
from pathlib import Path
from typing import List


def _summary(log: List[dict]) -> dict:
    c = Counter(e.get("status", "?") for e in log)
    return {
        "processed": len(log),
        "done": c.get("done", 0),
        "review": c.get("review", 0),
        "error": c.get("error", 0),
    }


def _pdf_link(entry: dict) -> str:
    """Erzeugt einen klickbaren file://-Link zum PDF, falls pdf_path vorhanden."""
    path = entry.get("pdf_path", "")
    if not path:
        return "—"
    url_path = str(path).replace("\\", "/")
    if not url_path.startswith("/"):
        url_path = "/" + url_path
    return f"[PDF](file://{url_path})"


def format_markdown(log: List[dict], mandant_label: str) -> str:
    s = _summary(log)
    lines = [
        f"# gmi-accountant Lauf — Mandant: {mandant_label}",
        "",
        "| Beleg | Status | Lieferant | Brutto | Aktion / Begruendung | PDF |",
        "|---|---|---|---|---|---|",
    ]
    for e in log:
        action = e.get("note") or (
            f"{len(e.get('fields_added') or [])} Felder ergaenzt, "
            f"Critic: {e.get('critic', '-')}"
        )
        amount = e.get("grossAmount", 0) or 0
        currency = e.get("currency", "EUR")
        pdf = _pdf_link(e)
        lines.append(
            f"| {e.get('uid', '')} | {e.get('status', '?')} | "
            f"{e.get('supplier', '')} | {amount:.2f} {currency} | "
            f"{action} | {pdf} |"
        )
    lines.append("")
    summary_parts = [
        f"{s['processed']} verarbeitet",
        f"{s['done']} done",
    ]
    if s['review']:
        summary_parts.append(f"{s['review']} review")
    if s['error']:
        summary_parts.append(f"{s['error']} Fehler")
    lines.append(f"**Zusammenfassung:** {', '.join(summary_parts)}.")
    return "\n".join(lines)


def format_json(log: List[dict], mandant_label: str) -> str:
    return json.dumps(
        {
            "mandant": mandant_label,
            "summary": _summary(log),
            "entries": log,
        },
        ensure_ascii=False,
        indent=2,
    )


def format_quiet(log: List[dict]) -> str:
    s = _summary(log)
    return (
        f"{s['processed']} verarbeitet, {s['done']} done, "
        f"{s['review']} review, {s['error']} Fehler."
    )


def run(runfile: str, fmt: str, quiet: bool, mandant_label: str = "default") -> int:
    log: List[dict] = []
    p = Path(runfile)
    if p.exists():
        for line in p.read_text(encoding="utf-8").splitlines():
            line = line.strip()
            if line:
                log.append(json.loads(line))

    if quiet:
        print(format_quiet(log))
    elif fmt == "json":
        print(format_json(log, mandant_label))
    else:
        print(format_markdown(log, mandant_label))
    return 0


def main() -> int:
    p = argparse.ArgumentParser(description="gmi-accountant Report")
    p.add_argument("--runfile", required=True, help="JSONL-Datei mit Lauf-Eintraegen.")
    p.add_argument("--format", choices=["markdown", "json"], default="markdown")
    p.add_argument("--quiet", action="store_true")
    p.add_argument("--mandant-label", default="default")
    args = p.parse_args()
    return run(args.runfile, args.format, args.quiet, args.mandant_label)


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