#!/usr/bin/env sh
# Bootstrap legacy SQLite databases once, then apply real migrations on every
# subsequent start. This keeps the old pre-Alembic production database usable
# without stamping away future migrations.

set -eu

DB_PATH="${AGENTEVAL_DB_PATH:-data/agenteval.db}"

if [ ! -f "$DB_PATH" ]; then
    echo "production db not found; creating the initial SQLModel schema"
    python -c "from agenteval.storage.db import init_db; init_db()"
    alembic stamp head
else
    HAS_ALEMBIC_VERSION=$(python -c "import sqlite3, sys; connection = sqlite3.connect(sys.argv[1]); row = connection.execute(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'alembic_version'\").fetchone(); connection.close(); print('yes' if row else 'no')" "$DB_PATH")
    if [ "$HAS_ALEMBIC_VERSION" = "no" ]; then
        echo "legacy production db detected; starting migrations from the pre-Alembic baseline"
        alembic stamp base
    fi
fi

alembic upgrade head
exec agenteval server start --host 0.0.0.0 --port 8000
