#!/usr/bin/env bash
# Verify HA recorder/history/logbook status via REST API
# Usage: ./verify-ha-recorder.sh
# Requires: HA_URL and HA_TOKEN in ~/.hermes/.env or environment

set -euo pipefail

# Load env
if [ -f ~/.hermes/.env ]; then
  source ~/.hermes/.env
fi

: "${HA_URL:?Set HA_URL in ~/.hermes/.env}"
: "${HA_TOKEN:?Set HA_TOKEN in ~/.hermes/.env}"

echo "=== HA State ==="
STATE=$(curl -sf "$HA_URL/api/config" -H "Authorization: Bearer $HA_TOKEN" | python3 -c "import sys,json; d=json.load(sys.stdin); print(f'State: {d[\"state\"]}, Version: {d[\"version\"]}')")
echo "$STATE"

echo ""
echo "=== Service Domains ==="
curl -sf "$HA_URL/api/services" -H "Authorization: Bearer $HA_TOKEN" | python3 -c "
import sys,json
data=json.load(sys.stdin)
services=set(s['domain'] for s in data)
checks=['recorder','history','logbook']
allok=True
for d in checks:
    ok = d in services
    if not ok: allok=False
    print(f'  {d}: {\"✓\" if ok else \"✗\"}')
print(f'\nAll critical services: {\"PASS ✓\" if allok else \"FAIL ✗\"}')
"

echo ""
echo "=== History API Test ==="
RESULT=$(curl -sf -w "\n%{http_code}" "$HA_URL/api/history/period?filter_entity_id=sun.sun" -H "Authorization: Bearer $HA_TOKEN" 2>&1)
HTTP_CODE=$(echo "$RESULT" | tail -1)
BODY=$(echo "$RESULT" | head -n -1)
echo "  HTTP: $HTTP_CODE"
echo "$BODY" | python3 -c "
import sys,json
try:
    data=json.load(sys.stdin)
    if isinstance(data, list):
        total=sum(len(g) for g in data)
        print(f'  History entries returned: {total}')
        print('  Result: PASS ✓' if total > 0 else '  Result: EMPTY (may be normal)')
except Exception as e:
    print(f'  Parse error: {e}')
" 2>&1

echo ""
echo "=== Logbook API Test ==="
RESULT2=$(curl -sf -w "\n%{http_code}" "$HA_URL/api/logbook/2026-06-27T00:00:00?entity=sun.sun" -H "Authorization: Bearer $HA_TOKEN" 2>&1)
HTTP_CODE2=$(echo "$RESULT2" | tail -1)
echo "  HTTP: $HTTP_CODE2"
echo "  Result: $([ "$HTTP_CODE2" = "200" ] && echo 'PASS ✓' || echo 'FAIL ✗')"
