#!/usr/bin/env bash
# kaizen-retro.sh — Automated retrospective after every burn cycle.
#
# Runs daily after the morning report.
# Analyzes success rates by agent, repo, and issue type.
# Identifies max-attempts issues, generates ONE concrete improvement,
# and posts the retro to Telegram + the master morning-report issue.
#
# Usage:
#   ./bin/kaizen-retro.sh [--dry-run]

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="${SCRIPT_DIR%/bin}"
PYTHON="${PYTHON3:-python3}"

# Source local env if available so TELEGRAM_BOT_TOKEN is picked up
HOME_DIR="${HOME:-$(eval echo ~$(whoami))}"
for env_file in "$HOME_DIR/.hermes/.env" "$HOME_DIR/.timmy/.env" "$REPO_ROOT/.env"; do
  if [ -f "$env_file" ]; then
    # shellcheck source=/dev/null
    set -a
    # shellcheck source=/dev/null
    source "$env_file"
    set +a
  fi
done

# If the configured Gitea URL is unreachable but localhost works, prefer localhost
if ! curl -sf "${GITEA_URL:-http://localhost:3000}/api/v1/version" >/dev/null 2>&1; then
  if curl -sf http://localhost:3000/api/v1/version >/dev/null 2>&1; then
    export GITEA_URL="http://localhost:3000"
  fi
fi

# Ensure the Python script exists
RETRO_PY="$REPO_ROOT/scripts/kaizen_retro.py"
if [ ! -f "$RETRO_PY" ]; then
  echo "ERROR: kaizen_retro.py not found at $RETRO_PY" >&2
  exit 1
fi

# Run
exec "$PYTHON" "$RETRO_PY" "$@"
