"""Verify-Only Workflow: prüft komplett befüllte Belege gegen ein PDF.

Anders als write.py schreibt verify.py KEINE inhaltlichen Felder. Es setzt
nur einen Tag (``agent-done`` bei Critic-Pass, ``agent-review`` bei
Critic-Fail) und einen Audit-Stempel im Notizfeld. Das ist der Pfad für
Belege, bei denen GMI-OCR alle Pflichtfelder bereits korrekt gesetzt hat
und der Agent nur bestätigen soll, dass das PDF zu den Feldern passt.

Audit-Stempel-Format (Bundle-Format-Version v1):

    [Agent v1, YYYY-MM-DD HH:MM] Verify pass.
    [Agent v1, YYYY-MM-DD HH:MM] Verify fail: <fail-reasons>.
"""
from __future__ import annotations

import argparse
import json
import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional


_SKILL_DIR = Path(__file__).resolve().parent.parent
_SKILLS_ROOT = _SKILL_DIR.parent
if str(_SKILLS_ROOT) not in sys.path:
    sys.path.insert(0, str(_SKILLS_ROOT))
if str(_SKILL_DIR) not in sys.path:
    sys.path.insert(0, str(_SKILL_DIR))


AGENT_VERSION = "v1"


def make_verify_stamp(passed: bool, fail_reasons: list) -> str:
    ts = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M")
    if passed:
        return f"[Agent {AGENT_VERSION}, {ts}] Verify pass."
    detail = ", ".join(fail_reasons) if fail_reasons else "(keine Detail)"
    return f"[Agent {AGENT_VERSION}, {ts}] Verify fail: {detail}."


def run(uid: int, critic_file: str, dry_run: bool) -> int:
    try:
        from gmi_bridge import (  # noqa: WPS433
            build_client,
            fetch_one_document_meta_via_list,
            set_status_tag,
            update_document,
        )
        from workflows.write import merge_audit_stamp  # noqa: WPS433
    except (FileNotFoundError, ImportError) as e:
        print(json.dumps({"error": f"depends_on-Vertrag verletzt: {e}"}, ensure_ascii=False))
        return 3

    try:
        critic = json.loads(Path(critic_file).read_text(encoding="utf-8"))
    except (FileNotFoundError, OSError) as e:
        print(json.dumps({"error": f"Critic-Datei nicht lesbar: {type(e).__name__}"}, ensure_ascii=False))
        return 2
    except json.JSONDecodeError:
        print(json.dumps({"error": "Critic-Datei ist kein valides JSON."}, ensure_ascii=False))
        return 2

    passed = bool(critic.get("passed"))
    results = critic.get("results") or []
    fail_reasons = [r.get("id", "?") for r in results if r.get("passed") is False]

    new_tag = "agent-done" if passed else "agent-review"
    stamp = make_verify_stamp(passed, fail_reasons)

    if dry_run:
        print(json.dumps({
            "uid": uid,
            "dry_run": True,
            "would_tag": new_tag,
            "would_stamp": stamp,
        }, ensure_ascii=False, indent=2))
        return 0

    try:
        client = build_client()
    except Exception:
        print(json.dumps({"error": "Bridge fehlgeschlagen."}, ensure_ascii=False))
        return 2

    try:
        re_read = fetch_one_document_meta_via_list(client, uid)
        if re_read is None:
            print(json.dumps({
                "error": f"UID {uid} wurde in getDocumentList nicht gefunden.",
                "uid": uid,
            }, ensure_ascii=False))
            return 1
        meta = re_read.get("meta_data", re_read) if isinstance(re_read, dict) else {}
        if not isinstance(meta, dict):
            meta = {}

        existing_tags = set_status_tag(list(meta.get("tags") or []), new_tag)
        old_note = meta.get("note") or ""
        new_note = merge_audit_stamp(old_note, stamp)

        # Verify-Workflow schreibt nur Tag und Notiz, keine inhaltlichen Felder.
        update_document(client, uid, {"tags": existing_tags, "note": new_note})

    except Exception as e:
        print(json.dumps({"error": f"Verify fehlgeschlagen: {type(e).__name__}"}, ensure_ascii=False))
        return 1

    print(json.dumps({
        "uid": uid,
        "success": True,
        "final_tag": new_tag,
        "audit_stamp": stamp,
    }, ensure_ascii=False, indent=2))
    return 0


def main() -> int:
    p = argparse.ArgumentParser(description="gmi-accountant Verify")
    p.add_argument("--uid", type=int, required=True)
    p.add_argument("--critic-file", required=True,
                   help="JSON-Datei mit Critic-Ergebnis (passed, results).")
    p.add_argument("--dry-run", action="store_true")
    args = p.parse_args()
    return run(args.uid, args.critic_file, args.dry_run)


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