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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT_DIR"

export APP_ENV="${APP_ENV:-local}"
export HTTP_ADDR="${HTTP_ADDR:-:8080}"
default_database_url="postgres://nomadcode:nomadcode@code-server-postgres:5432/nomadcode-core-local?sslmode=disable"
legacy_code_server_database_url="postgres://nomadcode:nomadcode@code-server-postgres:5432/nomadcode?sslmode=disable"
default_redis_url="redis://code-server-redis:6379/3"
legacy_code_server_redis_url="redis://code-server-redis:6379/0"
default_redis_key_prefix="nomadcode-core:local"
default_model_base_url="http://192.168.0.91:11434"
default_model_name="qwen3.6:35b-a3b-bf16"
default_model_context_size="262144"
default_model_timeout_sec="300"
default_a2a_timeout_sec="300"
# code-server exports a shared DATABASE_URL; remap that default to this project's local DB.
if [[ "${DATABASE_URL:-}" == "$legacy_code_server_database_url" ]]; then
  export DATABASE_URL="$default_database_url"
else
  export DATABASE_URL="${DATABASE_URL:-$default_database_url}"
fi
# code-server exports a shared REDIS_URL; remap that default to this project's local Redis DB.
if [[ "${REDIS_URL:-}" == "$legacy_code_server_redis_url" ]]; then
  export REDIS_URL="$default_redis_url"
else
  export REDIS_URL="${REDIS_URL:-$default_redis_url}"
fi
export REDIS_KEY_PREFIX="${REDIS_KEY_PREFIX:-$default_redis_key_prefix}"
export AUTH_USERNAME="${AUTH_USERNAME:-nomadcode}"
export MODEL_BASE_URL="${MODEL_BASE_URL:-$default_model_base_url}"
export MODEL_API_KEY="${MODEL_API_KEY:-ollama}"
export MODEL_NAME="${MODEL_NAME:-$default_model_name}"
export MODEL_CONTEXT_SIZE="${MODEL_CONTEXT_SIZE:-$default_model_context_size}"
export MODEL_TIMEOUT_SEC="${MODEL_TIMEOUT_SEC:-$default_model_timeout_sec}"
export A2A_TIMEOUT_SEC="${A2A_TIMEOUT_SEC:-$default_a2a_timeout_sec}"

exec go run ./cmd/server "$@"
