#!/bin/bash

# Load .env file if it exists
if [ -f .env ]; then
    export $(cat .env | grep -v '^#' | xargs)
fi

# Check if SNOWFLAKE_DB environment variable is set
if [ -z "$SNOWFLAKE_DB" ]; then
    echo "Error: SNOWFLAKE_DB environment variable is not set"
    echo "Please set SNOWFLAKE_DB in your .env file or environment"
    exit 1
fi

# Check if SNOWFLAKE_DB contains "dev" (case-insensitive)
if [[ ! "$SNOWFLAKE_DB" =~ [Dd][Ee][Vv] ]]; then
    echo "Error: SNOWFLAKE_DB must contain 'dev' (case-insensitive)"
    echo "Current value: $SNOWFLAKE_DB"
    exit 1
fi

# Check if DBT_TARGET environment variable is set to "dev"
if [ "$DBT_TARGET" != "dev" ]; then
    echo "Error: DBT_TARGET environment variable must be set to 'dev'"
    echo "Current value: ${DBT_TARGET:-not set}"
    exit 1
fi

echo "SNOWFLAKE_DB is set to: $SNOWFLAKE_DB"
echo "DBT_TARGET is set to: $DBT_TARGET"

cd src/assets/dbt/analytics

# Delete existing database if it exists
echo "Deleting existing $SNOWFLAKE_DB database if it exists..."
uv run dbt run-operation drop_database --args '{"database_name": "'$SNOWFLAKE_DB'"}' 2>/dev/null || true

# Clone the database
echo "Cloning suno_prod to $SNOWFLAKE_DB..."
uv run dbt run-operation clone_database --args '{"source_database": "suno_prod", "destination_database": "'$SNOWFLAKE_DB'"}'

# Disable search optimization on all tables in the cloned database
echo "Disabling search optimization on all tables in $SNOWFLAKE_DB..."
uv run dbt run-operation disable_search_optimization

# Materialize external tables
echo "Materializing external tables in $SNOWFLAKE_DB..."
uv run dbt run --select config.materialized:external
