#!/usr/bin/env python3
"""KAR-Issue-Body-Validator.

Pruet ob ein KAR-Issue-Body die Aria-Mindest-Struktur erfuellt:

- "## Definition of Done" oder "## Akzeptanzkriterien" Sektion vorhanden
- Mindestens 1 Checkbox-Item ([ ] oder [x]) in DoD
- "Closes" oder "Fixes" KAR-Reference (fuer PRs) - skip wenn --kar-only
- Branch-Hint (bei PRs) optional

Usage:
    kar_issue_body.py --input /tmp/issue-body.md
    cat body.md | kar_issue_body.py --input - --kar-only

Exit-Codes: 0 pass, 2 fail.
"""
import argparse
import re
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))
from _lib import emit_report, read_input


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--input", default="-")
    ap.add_argument("--kar-only", action="store_true",
                    help="Skip PR-spezifische Pruefungen (Closes-Syntax)")
    args = ap.parse_args()

    body = read_input(args.input)
    errors: list[str] = []

    has_dod = bool(re.search(r"^##\s+(Definition of Done|Akzeptanzkriterien)\b",
                             body, re.MULTILINE | re.IGNORECASE))
    if not has_dod:
        errors.append("Sektion '## Definition of Done' (oder 'Akzeptanzkriterien') fehlt.")

    if has_dod:
        # Find DoD section content
        match = re.search(r"^##\s+(Definition of Done|Akzeptanzkriterien)\b(.*?)(?=^##\s|\Z)",
                          body, re.MULTILINE | re.IGNORECASE | re.DOTALL)
        dod_content = match.group(2) if match else ""
        if not re.search(r"^[\s-]*\[[ x]\]", dod_content, re.MULTILINE):
            errors.append("DoD-Sektion enthaelt keine Checkbox-Items ([ ] oder [x]).")

    if not args.kar_only:
        if not re.search(r"\b(Closes|Fixes|Resolves)\s+KAR-\d+", body, re.IGNORECASE):
            errors.append("PR-Body braucht 'Closes KAR-XXX' Syntax fuer Linear-Auto-Done.")

    return emit_report("kar_issue_body", not errors, errors,
                       details={"input": args.input, "kar_only": args.kar_only})


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