#!/usr/bin/env bash
# Heuristic: try? JSON decode / data(for:) in ViewModels without nearby statusMessage or logger.error
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
cd "$ROOT"

echo "# swift_optional_decode_audit (heuristic)"
echo ""

rg -n 'try\?' MugiApp/Mugi --glob '*ViewModel.swift' | while IFS= read -r line; do
  file="${line%%:*}"
  rest="${line#*:}"
  lineno="${rest%%:*}"
  content="${rest#*:}"
  if [[ "$content" =~ JSONDecoder|data\(for:|decode\( ]] || [[ "$content" =~ \.data\(for: ]]; then
  start=$((lineno - 8))
  [[ $start -lt 1 ]] && start=1
  end=$((lineno + 8))
  window=$(sed -n "${start},${end}p" "$file" 2>/dev/null || true)
  if ! echo "$window" | grep -qE 'statusMessage|logger\.(error|warning)|BackendAPIError'; then
    echo "FLAG $file:$lineno $content"
  fi
  fi
done

echo ""
echo "# done"
