#!/bin/sh
# POSIX shell + jq - NINA Warnmeldungen fuer eine Stadt pruefen
# Stadt wird per IP ermittelt oder per -c uebergeben.
# JSON-Parsing uebernimmt jq (statt awk/sed-Handarbeit).

API="https://warnung.bund.de/api31"
RS_URL="https://www.xrepository.de/api/xrepository/urn:de:bund:destatis:bevoelkerungsstatistik:schluessel:rs_2021-07-31/download/Regionalschl_ssel_2021-07-31.json"

command -v jq >/dev/null 2>&1 || { echo "error: jq ist nicht installiert" >&2; exit 1; }

echo_err() { echo "$@" >&2; }

usage() {
    echo_err "usage: $0 [-c CITY] [-t curl|wget]"
    exit 1
}

# HTTP-Abruf, Werkzeug per -t oder HTTP_TOOL umschaltbar
TOOL="${HTTP_TOOL:-}"
if [ -z "$TOOL" ]; then
    if command -v curl >/dev/null 2>&1; then TOOL=curl; else TOOL=wget; fi
fi
case "$TOOL" in
    curl|wget) ;;
    *) echo_err "error: unbekanntes HTTP-Tool '$TOOL' (erwartet: curl|wget)"; exit 1 ;;
esac
command -v "$TOOL" >/dev/null 2>&1 || { echo_err "error: '$TOOL' ist nicht installiert"; exit 1; }

fetch() {
    case "$TOOL" in
        wget) wget -qO- "$1" ;;
        *)    curl -sS "$1" ;;
    esac
}

download() {
    case "$TOOL" in
        wget) wget -qO "$2" "$1" ;;
        *)    curl -sS "$1" -o "$2" ;;
    esac
}

CITY=""
while getopts "c:t:h" opt; do
    case "$opt" in
        c) CITY="$OPTARG" ;;
        t) TOOL="$OPTARG" ;;
        *) usage ;;
    esac
done
shift $((OPTIND - 1))

case "$TOOL" in
    curl|wget) ;;
    *) echo_err "error: unbekanntes HTTP-Tool '$TOOL' (erwartet: curl|wget)"; exit 1 ;;
esac
command -v "$TOOL" >/dev/null 2>&1 || { echo_err "error: '$TOOL' ist nicht installiert"; exit 1; }

# ---- Stadt aus IP ermitteln, falls nicht angegeben -----------------------
if [ -z "$CITY" ]; then
    GEO=$(fetch "http://ip-api.com/json/?lang=de") || {
        echo_err "error: Geolokalisierung fehlgeschlagen"
        exit 1
    }
    [ -z "$GEO" ] && { echo_err "error: Geolokalisierung fehlgeschlagen"; exit 1; }
    STATUS=$(printf '%s' "$GEO" | jq -r '.status')
    COUNTRY=$(printf '%s' "$GEO" | jq -r '.countryCode')
    CITY=$(printf '%s' "$GEO" | jq -r '.city')
    if [ "$STATUS" != "success" ] || [ "$COUNTRY" != "DE" ] || [ -z "$CITY" ]; then
        echo_err "error: Standort konnte nicht nach Deutschland aufgeloest werden. Bitte -c CITY angeben."
        exit 1
    fi
    echo "Standort per IP ermittelt: $CITY"
fi

# ---- ARS fuer die Stadt ermitteln ----------------------------------------
RS_FILE="${TMPDIR:-/tmp}/opencode-regionalschluessel.json"
if [ ! -s "$RS_FILE" ]; then
    download "$RS_URL" "$RS_FILE" || { echo_err "error: Regionalschluessel-Download fehlgeschlagen"; exit 1; }
fi

ROW=$(jq -r --arg city "$CITY" '.daten[] | select((.[1] // "") | ascii_downcase | contains($city | ascii_downcase)) | [.[0], .[1]] | @tsv' "$RS_FILE" | head -n 1)
if [ -z "$ROW" ]; then
    echo_err "error: Stadt '$CITY' nicht im Regionalschluessel-Verzeichnis gefunden"
    exit 1
fi

ARS=$(printf '%s' "$ROW" | cut -f1)
NAME=$(printf '%s' "$ROW" | cut -f2)
DISTRICT=$(printf '%s' "$ARS" | cut -c1-5)0000000

echo ""
echo "Stadt : $NAME ($ARS)"
echo "Kreis : $DISTRICT"
echo ""

# ---- 1) Dashboard (aktuelle Warnungen fuer den Kreis) ---------------------
echo "=== Dashboard Kreis ($DISTRICT) ==="
DASH=$(fetch "$API/dashboard/$DISTRICT.json")
DASH_N=$(printf '%s' "$DASH" | jq 'length')
if [ "$DASH_N" -eq 0 ]; then
    echo "  keine aktuellen Meldungen"
else
    printf '%s' "$DASH" | jq -r '.[] | "  \(.id)  |  \(.i18nTitle.de // "")  |  sent: \(.sent // "")"'
fi

# ---- 2) RSS-Feed (MoWaS, XML - weiterhin mit awk) -------------------------
echo ""
echo "=== RSS-Feed ($DISTRICT.rss) ==="
RSS=$(fetch "$API/mowas/rss/$DISTRICT.rss")
RSS_N=$(printf '%s' "$RSS" | awk 'BEGIN{RS="<item>"} {n++} END{print n-1}')
if [ "$RSS_N" -eq 0 ]; then
    echo "  keine aktuellen Meldungen"
else
    printf '%s' "$RSS" | awk 'BEGIN{RS="</item>"} /<item>/{t=$0; sub(/^.*<title>/,"",t); sub(/<\/title>.*/,"",t); d=$0; sub(/^.*<pubDate>/,"",d); sub(/<\/pubDate>.*/,"",d); print "  " t "  |  " d}'
fi

# ---- 3) Alle Warnquellen nach Stadtname filtern ----------------------------
echo ""
echo "=== Alle Warnquellen (mowas/katwarn/biwapp/dwd/lhp/police) ==="
FOUND=0
for s in mowas katwarn biwapp dwd lhp police; do
    LIST=$(fetch "$API/$s/mapData.json")
    [ -z "$LIST" ] && continue
    IDS=$(printf '%s' "$LIST" | jq -r '.[].id')
    for id in $IDS; do
        WARN=$(fetch "$API/warnings/$id.json")
        printf '%s' "$WARN" | grep -qi "$CITY" || continue
        FOUND=$((FOUND + 1))
        echo ""
        echo "  [$s] $id"
        echo "  Headline : $(printf '%s' "$WARN" | jq -r '.info[0].headline // empty')"
        echo "  Event    : $(printf '%s' "$WARN" | jq -r '.info[0].event // empty')"
        echo "  Severity : $(printf '%s' "$WARN" | jq -r '.info[0].severity // empty')"
        echo "  Sender   : $(printf '%s' "$WARN" | jq -r '.info[0].parameter[]? | select(.valueName == "sender_langname") | .value' | head -n 1)"
        echo "  Sent     : $(printf '%s' "$WARN" | jq -r '.sent // empty')"
    done
done

echo ""
echo "=== Ergebnis ==="
TOTAL=$((FOUND + DASH_N))
if [ "$TOTAL" -eq 0 ]; then
    echo "  Keine aktuellen Warnmeldungen fuer '$CITY' gefunden."
else
    echo "  $TOTAL Warnmeldung(en) fuer '$CITY' gefunden."
fi
