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

REPORTS_DIR="/var/lib/saikyo-av/reports"
ART_DIR="${REPORTS_DIR}/artifacts"

mkdir -p "${REPORTS_DIR}" "${ART_DIR}" || true
chmod 0755 /var/lib/saikyo-av "${REPORTS_DIR}" 2>/dev/null || true

TS="$(date -u +%Y%m%dT%H%M%SZ)"
REPORT_ID="agent-${TS}"
OUT_JSON="${REPORTS_DIR}/${REPORT_ID}.json"

FAILED_UNITS_FILE="${ART_DIR}/systemctl-failed-${TS}.txt"
JOURNAL_FILE="${ART_DIR}/journal-warn-${TS}.txt"

(systemctl --failed 2>&1 || true) > "${FAILED_UNITS_FILE}"
(journalctl -b -p warning..alert --no-pager 2>&1 | tail -n 400 || true) > "${JOURNAL_FILE}"

FAILED_COUNT="$(grep -cE '^[^\s].*\.service' "${FAILED_UNITS_FILE}" 2>/dev/null || echo 0)"

SEVERITY="info"
SUMMARY="Saikyo AV: periodic health report"
if [[ "${FAILED_COUNT}" -gt 0 ]]; then
  SEVERITY="warn"
  SUMMARY="Saikyo AV: detected failed systemd units (${FAILED_COUNT})"
fi

cat > "${OUT_JSON}" <<EOF
{
  "created_utc": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "severity": "${SEVERITY}",
  "summary": "${SUMMARY}",
  "details": {
    "failed_units_count": ${FAILED_COUNT}
  },
  "artifacts": {
    "systemctl_failed": "${FAILED_UNITS_FILE}",
    "journal_warn": "${JOURNAL_FILE}"
  },
  "suggested_fixes": [
    {
      "id": "run_evidence",
      "title": "Run evidence collection",
      "description": "Generate /var/log/saikyo-evidence/latest.log using saikyo-evidence.",
      "requires_consent": true
    }
  ]
}
EOF

exit 0
