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

usage() {
  cat <<'EOF'
Usage: run_digest.sh [YYYY-MM-DD]

Environment overrides:
  DIGEST_AI_BIN           Digest agent command (default: claude)
  DIGEST_AI_PROMPT_PREFIX Optional prompt prefix
  DIGEST_PROCESS_SCRIPT   Process wrapper path (default: PHASES/PHASE-01-INGEST/process_day.sh)
  DIGEST_CAPTION_SCRIPT   Caption wrapper path (default: PHASES/PHASE-02-CAPTIONS/caption_until_complete.sh)
  DIGEST_MERGE_BIN        CSV merge binary (default: ./bin/tweet-csv-merge)
  DIGEST_NOTIFY_SCRIPT    Notify script path (default: PHASES/PHASE-06-NOTIFICATIONS/notify_telegram.sh)
EOF
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  usage
  exit 0
fi

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
DATE_ISO="${1:-$(date +%F)}"
DAY_TWEETS="${ROOT}/PHASES/PHASE-01-INGEST/tweets/archive/${DATE_ISO}"
DAY_DIGEST="${ROOT}/PHASES/PHASE-05-ORCHESTRATOR/digests/archive/${DATE_ISO}"
LOCK="/tmp/twitter-digest-${DATE_ISO}.lock"
LOG_DIR="${ROOT}/PHASES/PHASE-05-ORCHESTRATOR/logs/digest"
INDEX_TEMPLATE="${ROOT}/PHASES/PHASE-04-RENDER/index.php.template"
LEDGER="${ROOT}/PHASES/PHASE-05-ORCHESTRATOR/COMPLETED-DAYS.md"

DIGEST_AI_BIN="${DIGEST_AI_BIN:-claude}"
DIGEST_AI_PROMPT_PREFIX="${DIGEST_AI_PROMPT_PREFIX:-}"
DIGEST_PROCESS_SCRIPT="${DIGEST_PROCESS_SCRIPT:-${ROOT}/PHASES/PHASE-01-INGEST/process_day.sh}"
DIGEST_CAPTION_SCRIPT="${DIGEST_CAPTION_SCRIPT:-${ROOT}/PHASES/PHASE-02-CAPTIONS/caption_until_complete.sh}"
DIGEST_MERGE_BIN="${DIGEST_MERGE_BIN:-./bin/tweet-csv-merge}"
DIGEST_NOTIFY_SCRIPT="${DIGEST_NOTIFY_SCRIPT:-${ROOT}/PHASES/PHASE-06-NOTIFICATIONS/notify_telegram.sh}"

mkdir -p "${LOG_DIR}" "${DAY_DIGEST}" "${DAY_TWEETS}"

exec 9>"${LOCK}"
flock -n 9 || { echo "[digest] already running date=${DATE_ISO}"; exit 0; }

cd "${ROOT}"
if [[ -f "${ROOT}/venv/bin/activate" ]]; then
  # shellcheck source=/dev/null
  source "${ROOT}/venv/bin/activate"
fi

echo "[digest] start date=${DATE_ISO} time=$(date -Is)"

RAW_FEED="${DAY_TWEETS}/raw_feed.csv"
RUN_DIR="${DAY_TWEETS}/raw_feed_runs"

if [[ ! -f "${RAW_FEED}" ]]; then
  echo "[digest] raw_feed.csv missing; attempting merge from ${RUN_DIR}"
  if [[ ! -d "${RUN_DIR}" ]]; then
    echo "[digest] ERROR: missing ${RUN_DIR} and no raw_feed.csv"
    exit 2
  fi

  shopt -s nullglob
  run_files=("${RUN_DIR}"/*.csv)
  shopt -u nullglob
  if [[ "${#run_files[@]}" -eq 0 ]]; then
    echo "[digest] ERROR: no run files in ${RUN_DIR} and no raw_feed.csv"
    exit 2
  fi

  if [[ ! -x "${DIGEST_MERGE_BIN}" ]]; then
    echo "[digest] ERROR: merge binary not executable: ${DIGEST_MERGE_BIN}"
    exit 2
  fi

  "${DIGEST_MERGE_BIN}" "${run_files[@]}" -o "${RAW_FEED}" --keep first
fi

if [[ ! -x "${DIGEST_PROCESS_SCRIPT}" ]]; then
  echo "[digest] ERROR: process script not executable: ${DIGEST_PROCESS_SCRIPT}"
  exit 2
fi
"${DIGEST_PROCESS_SCRIPT}" "${DATE_ISO}"

if [[ ! -x "${DIGEST_CAPTION_SCRIPT}" ]]; then
  echo "[digest] ERROR: caption script not executable: ${DIGEST_CAPTION_SCRIPT}"
  exit 2
fi
"${DIGEST_CAPTION_SCRIPT}" "${DATE_ISO}"

if [[ ! -f "${DAY_TWEETS}/images_done.ok" ]]; then
  echo "[digest] ERROR: caption step finished but images_done.ok is missing"
  exit 2
fi

if ! command -v "${DIGEST_AI_BIN}" >/dev/null 2>&1 && [[ ! -x "${DIGEST_AI_BIN}" ]]; then
  echo "[digest] ERROR: digest AI binary not found/executable: ${DIGEST_AI_BIN}"
  exit 2
fi

PROMPT="${DIGEST_AI_PROMPT_PREFIX} Read ${ROOT}/PHASES/PHASE-03-DIGEST-CONTRACT/CLAUDE.md and generate PHASES/PHASE-05-ORCHESTRATOR/digests/archive/${DATE_ISO}/digest.json and PHASES/PHASE-05-ORCHESTRATOR/digests/archive/${DATE_ISO}/digest_checkpoint.md for date ${DATE_ISO}. Use PHASES/PHASE-01-INGEST/tweets/archive/${DATE_ISO}/*.csv and previous 7 days digests."

if command -v "${DIGEST_AI_BIN}" >/dev/null 2>&1; then
  "${DIGEST_AI_BIN}" -p "${PROMPT}"
else
  "${DIGEST_AI_BIN}" -p "${PROMPT}"
fi

DIGEST_JSON="${DAY_DIGEST}/digest.json"
DIGEST_CHECKPOINT="${DAY_DIGEST}/digest_checkpoint.md"
if [[ ! -f "${DIGEST_JSON}" ]]; then
  echo "[digest] ERROR: digest agent did not produce ${DIGEST_JSON}"
  exit 2
fi
if [[ ! -f "${DIGEST_CHECKPOINT}" ]]; then
  echo "[digest] ERROR: digest agent did not produce ${DIGEST_CHECKPOINT}"
  exit 2
fi
python3 - <<PY
import json
from pathlib import Path
p = Path(${DIGEST_JSON@Q})
json.loads(p.read_text(encoding="utf-8"))
PY

if [[ ! -f "${INDEX_TEMPLATE}" ]]; then
  echo "[digest] ERROR: missing ${INDEX_TEMPLATE}"
  exit 2
fi
cp -f "${INDEX_TEMPLATE}" "${DAY_DIGEST}/index.php"

find "${ROOT}/PHASES/PHASE-05-ORCHESTRATOR/digests/archive" -type d -exec chmod 755 {} \;
find "${ROOT}/PHASES/PHASE-05-ORCHESTRATOR/digests/archive" -type f -name "*.php" -exec chmod 644 {} \;
find "${ROOT}/PHASES/PHASE-05-ORCHESTRATOR/digests/archive" -type f -name "*.json" -exec chmod 644 {} \;
find "${ROOT}/PHASES/PHASE-05-ORCHESTRATOR/digests/archive" -type f -name "*.md" -exec chmod 644 {} \;
find "${ROOT}/PHASES/PHASE-05-ORCHESTRATOR/digests/archive" -type f -name "*.ok" -exec chmod 644 {} \;

if [[ ! -x "${DIGEST_NOTIFY_SCRIPT}" ]]; then
  echo "[digest] ERROR: notify script not executable: ${DIGEST_NOTIFY_SCRIPT}"
  exit 2
fi
"${DIGEST_NOTIFY_SCRIPT}" "${DATE_ISO}"

if [[ ! -f "${LEDGER}" ]]; then
  cat > "${LEDGER}" <<'EOF'
# Completed Digest Days

# One YYYY-MM-DD per line
EOF
fi
if ! rg -n --smart-case -S "^${DATE_ISO}$" "${LEDGER}" >/dev/null 2>&1; then
  echo "${DATE_ISO}" >> "${LEDGER}"
fi

touch "${DAY_DIGEST}/published.ok"

echo "[digest] complete date=${DATE_ISO} time=$(date -Is)"
