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

read_env_var() {
  local key="$1"
  local file="$2"
  [[ -f "${file}" ]] || return 1
  sed -n "s/^${key}=//p" "${file}" | head -n1
}

SOC_ENV_FILE="${SOC_ENV_FILE:-soc-integrator/.env}"
ROOT_ENV_FILE="${ROOT_ENV_FILE:-.env}"

iris_api_key_from_env="${IRIS_API_KEY:-}"
if [[ -z "${iris_api_key_from_env}" ]]; then
  iris_api_key_from_env="$(read_env_var "IRIS_API_KEY" "${SOC_ENV_FILE}" || true)"
fi
if [[ -z "${iris_api_key_from_env}" ]]; then
  iris_api_key_from_env="$(read_env_var "IRIS_API_KEY" "${ROOT_ENV_FILE}" || true)"
fi

integrator_url_from_env="${INTEGRATOR_URL:-}"
if [[ -z "${integrator_url_from_env}" ]]; then
  integrator_url_from_env="$(read_env_var "INTEGRATOR_URL" "${SOC_ENV_FILE}" || true)"
fi
if [[ -z "${integrator_url_from_env}" ]]; then
  integrator_url_from_env="http://localhost:8088"
fi

iris_base_url_from_env="${IRIS_BASE_URL:-}"
if [[ -z "${iris_base_url_from_env}" ]]; then
  iris_base_url_from_env="$(read_env_var "IRIS_BASE_URL" "${SOC_ENV_FILE}" || true)"
fi
if [[ -z "${iris_base_url_from_env}" ]]; then
  iris_base_url_from_env="https://localhost:8443"
fi

MODE="${MODE:-integrator}"                  # integrator | direct
COUNT="${COUNT:-5}"
PREFIX="${PREFIX:-SOC Demo Incident}"
INTEGRATOR_URL="${integrator_url_from_env}"
IRIS_BASE_URL="${iris_base_url_from_env}"
IRIS_API_KEY="${iris_api_key_from_env}"
IRIS_VERIFY_SSL="${IRIS_VERIFY_SSL:-false}" # false -> use -k
CASE_CUSTOMER="${CASE_CUSTOMER:-1}"
CASE_SOC_ID="${CASE_SOC_ID:-}"

if [[ ! "${COUNT}" =~ ^[0-9]+$ ]] || [[ "${COUNT}" -lt 1 ]]; then
  echo "error: COUNT must be a positive integer"
  exit 1
fi

timestamp="$(date +%Y%m%d-%H%M%S)"

for i in $(seq 1 "${COUNT}"); do
  severity="medium"
  if (( i % 4 == 0 )); then
    severity="critical"
  elif (( i % 3 == 0 )); then
    severity="high"
  elif (( i % 2 == 0 )); then
    severity="low"
  fi

  title="${PREFIX} #${i} (${timestamp})"
  description="Generated demo IRIS case ${i}/${COUNT} at ${timestamp}"

  if [[ "${MODE}" == "integrator" ]]; then
    response="$(
      curl -sS -X POST "${INTEGRATOR_URL}/iris/tickets" \
        -H "Content-Type: application/json" \
        -d "{
          \"title\": \"${title}\",
          \"description\": \"${description}\",
          \"case_customer\": ${CASE_CUSTOMER},
          \"case_soc_id\": \"${CASE_SOC_ID}\",
          \"payload\": {}
        }"
    )"
  elif [[ "${MODE}" == "direct" ]]; then
    curl_args=(-sS -X POST "${IRIS_BASE_URL}/api/v2/cases" -H "Content-Type: application/json")
    if [[ "${IRIS_VERIFY_SSL}" == "false" ]]; then
      curl_args+=(-k)
    fi
    if [[ -n "${IRIS_API_KEY}" ]]; then
      curl_args+=(-H "Authorization: Bearer ${IRIS_API_KEY}")
    fi
    response="$(
      curl "${curl_args[@]}" \
        -d "{
          \"case_name\": \"${title}\",
          \"case_description\": \"${description}\",
          \"case_customer\": ${CASE_CUSTOMER},
          \"case_soc_id\": \"${CASE_SOC_ID}\"
        }"
    )"
  else
    echo "error: MODE must be 'integrator' or 'direct'"
    exit 1
  fi

  RESPONSE="${response}" python3 - <<'PY'
import json
import os

raw = os.environ.get("RESPONSE", "")
try:
    data = json.loads(raw)
except Exception:
    print(f"raw_response: {raw[:400]}")
    raise SystemExit(0)

# integrator shape: {"ok": true, "data": {"iris": {...}}}
if isinstance(data, dict) and "data" in data and isinstance(data["data"], dict):
    iris = data["data"].get("iris", {})
    case = iris.get("data", {}) if isinstance(iris, dict) else {}
    if case:
        print(
            f"created case_id={case.get('case_id')} case_uuid={case.get('case_uuid')} "
            f"title={case.get('case_name')}"
        )
    else:
        print(json.dumps(data))
    raise SystemExit(0)

# direct IRIS shape: {"status":"success","data":{...}}
case = data.get("data", {}) if isinstance(data, dict) else {}
if isinstance(case, dict) and case:
    print(
        f"created case_id={case.get('case_id')} case_uuid={case.get('case_uuid')} "
        f"title={case.get('case_name')}"
    )
else:
    print(json.dumps(data))
PY
done

echo "done: created ${COUNT} demo cases (mode=${MODE})"
