#!/usr/bin/env bash
set -euo pipefail

COMPANY_ID="${COMPANY_ID:-40193f7a-ff14-4616-8cc5-5c4378073592}"
PAPERCLIP_BASE="${PAPERCLIP_BASE:-http://127.0.0.1:3100/api}"
GATEWAY_HEALTH_URL="${GATEWAY_HEALTH_URL:-http://127.0.0.1:3200/health}"
LOG_DIR="${LOG_DIR:-/home/jinkidi/.hermes/workrooms/dalgeumi/integrated-dashboard/operations/cron-run-logs}"
ISSUE="${ISSUE:-NEX-8}"
JOB_NAME="${JOB_NAME:-manual-preflight}"

mkdir -p "$LOG_DIR"
LOG_FILE="$LOG_DIR/$(date +%Y-%m).jsonl"
TS="$(date -Iseconds)"

z_state="failed"
if [ -d /mnt/z ]; then
  if [ -w /mnt/z ]; then z_state="pass"; else z_state="degraded"; fi
fi

paperclip_state="failed"
if curl -fsS "$PAPERCLIP_BASE/health" >/tmp/paperclip_health.$$ 2>/dev/null; then
  if curl -fsS "$PAPERCLIP_BASE/companies/$COMPANY_ID" >/tmp/paperclip_company.$$ 2>/dev/null; then
    paperclip_state="pass"
  else
    paperclip_state="degraded"
  fi
fi
rm -f /tmp/paperclip_health.$$ /tmp/paperclip_company.$$

gateway_state="not_required"
if [ "${GATEWAY_REQUIRED:-0}" = "1" ]; then
  if curl -fsS "$GATEWAY_HEALTH_URL" >/tmp/gateway_health.$$ 2>/dev/null; then
    gateway_state="pass"
  else
    gateway_state="failed"
  fi
  rm -f /tmp/gateway_health.$$
fi

state="done"
recovery_next="none"
if [ "$z_state" = "failed" ] || [ "$paperclip_state" = "failed" ] || [ "$gateway_state" = "failed" ]; then
  state="failed"
  recovery_next="restore failed dependency before running job"
elif [ "$z_state" = "degraded" ] || [ "$paperclip_state" = "degraded" ]; then
  state="degraded"
  recovery_next="run with fallback path and create/sync pending Paperclip record"
fi

python3 - <<PY >> "$LOG_FILE"
import json
record={
  "timestamp":"$TS",
  "issue":"$ISSUE",
  "job_name":"$JOB_NAME",
  "state":"$state",
  "preflight":{
    "z_drive":"$z_state",
    "paperclip":"$paperclip_state",
    "gateway":"$gateway_state"
  },
  "artifacts":[],
  "verification":["z drive checked","paperclip health/company checked"],
  "recovery_next":"$recovery_next"
}
print(json.dumps(record, ensure_ascii=False))
PY

printf 'state=%s z_drive=%s paperclip=%s gateway=%s log=%s\n' "$state" "$z_state" "$paperclip_state" "$gateway_state" "$LOG_FILE"
[ "$state" != "failed" ]
