#!/usr/bin/env bash
# scripts/qa/hook-audit - Verify v11.1.0 property hook conversion completeness
# Exit 0 = all checks pass, exit 1 = violations found
set -uo pipefail
cd "$(git rev-parse --show-toplevel)"

violations=0
report() { echo "$1"; violations=$((violations + 1)); }

# 1. No-op getter methods (return $this->prop;) - excluding interface-mandated
echo "--- Check 1: No-op getters (excluding interface-mandated) ---"
noops=$(rg -n 'public function get(\w+)\(\)\s*\n\s*\{\s*\n\s*return \$this->\w+;\s*\n\s*\}' -U -t php src/Entity/ 2>/dev/null \
    | rg -v 'getPassword|getUserIdentifier|passworthash' \
    | wc -l)
[ "$noops" -gt 0 ] && report "Found $noops no-op getter methods" || echo "OK: 0 no-op getters"

# 2. DateTime setter methods still using method form (excluding cross-property logic)
echo "--- Check 2: Remaining DateTime setter methods ---"
dt_setters=$(rg -n 'function set\w*.*\\DateTime' -t php src/Entity/ 2>/dev/null \
    | rg -v 'setFaelligAm' \
    | wc -l)
[ "$dt_setters" -gt 0 ] && report "Found $dt_setters DateTime setter methods" || echo "OK: 0 DateTime setters"

# 3. private(set) without justification (PK, business key, collection, relationship OK)
echo "--- Check 3: Unjustified private(set) ---"
unjustified=$(rg -n 'private\(set\)' -t php src/Entity/ 2>/dev/null \
    | rg -v 'lfdnr|landeskuerzel|Collection|art\b' \
    | rg -v 'auftragsposition|bestellposition|artikel|adresse|dokument|vater|retoure' \
    | wc -l)
[ "$unjustified" -gt 0 ] && report "Found $unjustified potentially unjustified private(set)" || echo "OK: 0 unjustified private(set)"

# 4. @todo / FIXME markers
echo "--- Check 4: Stale @todo markers ---"
todos=$(rg -n '@todo|@TODO|FIXME' -t php src/ 2>/dev/null | wc -l)
[ "$todos" -gt 0 ] && report "Found $todos @todo/FIXME markers" || echo "OK: 0 @todo markers"

# 5. Private scalar properties without companion methods or jane: comment
echo "--- Check 5: Private scalars without justification ---"
# Filter.$oeffentlich has isOeffentlich()/setOeffentlich() companions
# Artikel.$vk2-4 has jane: intent comment documenting the reason
unjustified_privates=$(rg -n '^\s*private\s+\??(int|string|float|bool)\s+\$' -t php src/Entity/ 2>/dev/null \
    | rg -v 'oeffentlich' \
    | wc -l)
# Verify jane: comment exists for remaining private scalars
jane_count=$(rg -c 'jane:' src/Entity/Artikel.php 2>/dev/null || echo 0)
if [ "$unjustified_privates" -gt 0 ] && [ "$jane_count" -eq 0 ]; then
    report "Found $unjustified_privates private scalar properties without jane: comment"
else
    echo "OK: $unjustified_privates private scalars, all documented with jane: comments or companion methods"
fi

echo ""
if [ "$violations" -eq 0 ]; then
    echo "=== ALL CHECKS PASSED: 0 violations ==="
    exit 0
else
    echo "=== $violations VIOLATION(S) FOUND ==="
    exit 1
fi
