#!/usr/bin/env bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
STATE_FILE="$SCRIPT_DIR/codex_context.yaml"
DEFAULT_OLLAMA_API_BASE="http://100.100.231.104:11434"
AIDER_BIN="${AIDER_BIN:-$HOME/.local/bin/aider}"

usage() {
  cat <<'EOF'
Usage: ./start-aider.sh [aider-args...]

Starts Aider from this repository with shared project context.
EOF
}

if (($# > 0)); then
  case "$1" in
    -h|--help)
      usage
      exit 0
      ;;
  esac
fi

export OLLAMA_API_BASE="${OLLAMA_API_BASE:-$DEFAULT_OLLAMA_API_BASE}"

cd "$SCRIPT_DIR"
printf 'Loading %s\n' "$STATE_FILE"

if [[ ! -x "$AIDER_BIN" ]]; then
  echo "Aider executable not found at $AIDER_BIN" >&2
  exit 1
fi

if "$AIDER_BIN" --help 2>/dev/null | grep -q -- '--read FILE'; then
  printf '%s\n' 'Starting Aider with codex_context.yaml attached as read-only shared context.'
  exec "$AIDER_BIN" \
    --model ollama/deepseek-coder:latest \
    --read "$STATE_FILE" \
    "$@"
fi

printf '%s\n' 'Aider does not support read-only context files in this environment.'
printf '%s\n' 'Ask Aider to read codex_context.yaml first, then continue with your task.'
exec "$AIDER_BIN" --model qwen2.5-coder:14b"$@"
