#!/bin/zsh
set -euo pipefail

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

export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$PATH"
export UFORIA_DATA_ROOT="${UFORIA_DATA_ROOT:-$REPO_ROOT/data}"
export UFORIA_MICROSTRUCTURE_IMPORT_ROOT="${UFORIA_MICROSTRUCTURE_IMPORT_ROOT:-/Users/mubaris/dev/crypto-microstructure}"
export UFORIA_MICROSTRUCTURE_START="${UFORIA_MICROSTRUCTURE_START:-2026-01-01T00:00:00Z}"
export UFORIA_MICROSTRUCTURE_END="${UFORIA_MICROSTRUCTURE_END:-$(date -u +%Y-%m-%dT%H:00:00Z)}"
export PYTHONUNBUFFERED=1
export UFORIA_DB_ENABLED="${UFORIA_DB_ENABLED:-true}"
export UFORIA_DB_DSN="${UFORIA_DB_DSN:-postgresql:///uforia?user=$USER}"
export UFORIA_DB_READ_MODE="${UFORIA_DB_READ_MODE:-db}"
export UFORIA_DB_WRITE_MODE="${UFORIA_DB_WRITE_MODE:-db}"

for ASSET in BTC ETH; do
  echo "=== BUILDING INPUTS FOR $ASSET ==="
  uv run uforia-admin microstructure build-features --asset "$ASSET" --start "$UFORIA_MICROSTRUCTURE_START" --end "$UFORIA_MICROSTRUCTURE_END"
  uv run uforia-admin microstructure build-labels --asset "$ASSET" --start "$UFORIA_MICROSTRUCTURE_START" --end "$UFORIA_MICROSTRUCTURE_END" --horizons 30s,1m,2m,5m
  uv run uforia-admin microstructure build-regime --asset "$ASSET" --start "$UFORIA_MICROSTRUCTURE_START" --end "$UFORIA_MICROSTRUCTURE_END"
  for HORIZON in 1m 2m 5m 30s; do
    echo "--- TRAIN CHECK $ASSET $HORIZON ---"
    if /opt/homebrew/bin/uv run python - <<PY
from uforia.config import get_config
from uforia.storage.store import DatasetStore
from uforia.storage.datasets import DatasetName

store = DatasetStore(get_config().storage.root)
frame = store.read(
    DatasetName.MICROSTRUCTURE_TRAINING_RUN,
    filters={"asset": "${ASSET}", "horizon": "${HORIZON}", "source": "tcn_boost_fusion", "model_version": "tcn_boost_fusion_v2"},
).sort("ts").tail(1)
artifact_ok = (not frame.is_empty()) and bool(frame.item(0, "artifact_payload"))
raise SystemExit(0 if artifact_ok else 1)
PY
    then
      echo "Skipping $ASSET $HORIZON: repaired v2 artifact already exists"
      continue
    fi
    if uv run uforia-admin microstructure train --asset "$ASSET" --horizon "$HORIZON"; then
      uv run uforia-admin microstructure evaluate --asset "$ASSET" --horizon "$HORIZON" || echo "Evaluate failed for $ASSET $HORIZON"
      uv run uforia-admin microstructure generate-signals --asset "$ASSET" --horizon "$HORIZON" || echo "Generate-signals failed for $ASSET $HORIZON"
    else
      echo "Skipping $ASSET $HORIZON: no trainable rows yet"
    fi
  done
done
