#!/bin/bash

# Local Jira Sync Script
# This script loads environment variables from .env file and runs the sync pipeline.

set -e  # Exit on any error

# Get the script directory (where this script is located)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# Check if .env file exists
ENV_FILE="$PROJECT_ROOT/.env"
if [ ! -f "$ENV_FILE" ]; then
    echo "ERROR: .env file not found at $ENV_FILE"
    echo ""
    echo "Please create a .env file with the following variables:"
    echo "JIRA_HOST=your-domain.atlassian.net"
    echo "JIRA_USER_EMAIL=your-email@company.com"
    echo "JIRA_API_TOKEN=your-jira-api-token"
    echo "GOOGLE_GENERATIVE_AI_API_KEY=your-gemini-api-key"
    echo ""
    echo "Optional variables:"
    echo "PROJECT_ID=gcp-cp-bigquery-dev"
    echo "DATASET=jira"
    echo "TABLE=ticket"
    echo "JIRA_PROJECTS=TCOC,APID,FRM,ST,TCID"
    echo "WINDOW_HOURS=8"
    echo "TARGET_END_AT=2026-04-21 16:00"
    exit 1
fi

echo "Loading environment variables from $ENV_FILE"

# Load environment variables from .env file
# This handles comments, empty lines, and proper variable export
while IFS= read -r line || [[ -n "$line" ]]; do
    # Skip empty lines and comments
    if [[ -z "$line" || "$line" =~ ^[[:space:]]*# ]]; then
        continue
    fi

    # Extract variable name and value
    if [[ "$line" =~ ^[[:space:]]*([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
        var_name="${BASH_REMATCH[1]}"
        var_value="${BASH_REMATCH[2]}"

        # Remove quotes if present
        var_value=$(echo "$var_value" | sed 's/^["'\'']\(.*\)["'\'']$/\1/')

        # Export the variable
        export "$var_name"="$var_value"
        echo "  ✓ $var_name"
    fi
done < "$ENV_FILE"

echo ""
echo "Environment variables loaded successfully!"

# Change to project root directory
cd "$PROJECT_ROOT"

# Check if the project is built
if [ ! -d "dist" ]; then
    echo "Building project..."
    pnpm run build || {
        echo "ERROR: Failed to build project"
        exit 1
    }
fi

echo ""
echo "Starting Jira sync..."
echo "============================================"

# Run the sync script
exec "$SCRIPT_DIR/daily-sync.sh" "$@"
