#!/usr/bin/env bash
# Seed the dev database with the minimum reference data needed to run the
# ingest-binance service: the binance_spot exchange, the BTCUSDC instrument,
# and an ingest_config row that activates historical ingestion for it.
#
# Safe to run repeatedly — all inserts use ON CONFLICT DO NOTHING.
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"

# Build connection string from dev api config (same logic as the deploy drop block)
api_cfg="$REPO_ROOT/config/dev/api.json"
config_db_url=$(jq -r '.database.url' "$api_cfg")
db_user="$(echo ${config_db_url} | cut -d '/' -f 3 | cut -d '@' -f 1)"
db_host="$(echo ${config_db_url} | cut -d '@' -f 2 | cut -d ':' -f 1)"
db_port="$(echo ${config_db_url} | cut -d ':' -f 3 | cut -d '/' -f 1)"
db_name="$(echo ${config_db_url} | cut -d '/' -f 4 | cut -d '?' -f 1)"
db_ssl_mode=verify-full
db_ssl_root_cert=/etc/pki/ca-trust/source/anchors/ca.internal-rsa.pem
db_ssl_cert=/etc/pki/tls/misc/$(hostnamectl hostname)-rsa.pem
db_ssl_key=/etc/pki/tls/private/$(hostnamectl hostname)-rsa.pem
db_url="postgres://${db_user}@${db_host}:${db_port}/${db_name}?sslmode=${db_ssl_mode}&sslrootcert=${db_ssl_root_cert}&sslcert=${db_ssl_cert}&sslkey=${db_ssl_key}"

echo "==> Seeding dev database ($db_url)..."

psql "$db_url" <<'SQL'

-- Exchange
INSERT INTO exchanges (name)
VALUES ('binance_spot')
ON CONFLICT (name) DO NOTHING;

-- Instrument: BTCUSDC on binance_spot
INSERT INTO instruments (exchange_id, name_exchange, base_asset, quote_asset, kind)
SELECT e.id, 'BTCUSDC', 'BTC', 'USDC', 'spot'
FROM exchanges e
WHERE e.name = 'binance_spot'
ON CONFLICT (exchange_id, name_exchange) DO NOTHING;

-- Ingest config: 365-day retention for BTCUSDC, sync all standard candle intervals from S3
INSERT INTO ingest_configs (instrument_id, source, retention_days, candle_intervals)
SELECT i.id, 'binance_s3', 365, ARRAY['1m', '5m', '15m', '1h', '4h', '1d']
FROM instruments i
JOIN exchanges e ON e.id = i.exchange_id
WHERE e.name = 'binance_spot'
  AND i.name_exchange = 'BTCUSDC'
ON CONFLICT (instrument_id, source)
DO UPDATE SET candle_intervals = ARRAY['1m', '5m', '15m', '1h', '4h', '1d'], updated_at = now();

SQL

echo "==> Done."
