#!/bin/bash

echo "🚀 Starting AI Land Pipeline..."

# Activate virtualenv (if you use one)
# source /path/to/venv/bin/activate

# Step 1: Fetch fresh data
echo "📥 Fetching data..."
python fetch_land_data.py

# Check if file exists
if [ ! -f "formatted_output.json" ]; then
    echo "❌ formatted_output.json not found. Exiting."
    exit 1
fi

# Step 2: Run matching (your existing script)
echo "🧠 Running matching..."
python match_pipeline.py

# Find latest grouped result file
LATEST_FILE=$(ls -t grouped_result_*.json | head -n 1)

if [ -z "$LATEST_FILE" ]; then
    echo "❌ No grouped result file found. Exiting."
    exit 1
fi

echo "📄 Found result file: $LATEST_FILE"

# Step 3: Push to API
echo "📤 Sending data to server..."
python push_ai_status.py "$LATEST_FILE"

# Step 4: Cleanup
echo "🧹 Cleaning up..."
rm -f formatted_output.json
rm -f "$LATEST_FILE"

echo "✅ Pipeline completed successfully!"
