#!/bin/bash
# JGT Data Refresh Service - Setup Script
# Initial setup and configuration for the JGT service

set -e  # Exit on any error

. $HOME/.jgt/.env||. .env
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Function to print colored output
print_status() {
    echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} ✓ $1"
}

print_error() {
    echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} ✗ $1"
}

print_warning() {
    echo -e "${YELLOW}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} ⚠ $1"
}

# Help function
show_help() {
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "Setup and configure the JGT Data Refresh Service"
    echo ""
    echo "Options:"
    echo "  -h, --help     Show this help message"
    echo "  -f, --full     Install with full web service dependencies"
    echo "  -q, --quick    Quick setup with minimal prompts"
    echo ""
    echo "This script will:"
    echo "  - Install the jgtpy package"
    echo "  - Create configuration directories"
    echo "  - Set up environment variables"
    echo "  - Test basic functionality"
}

# Parse options
INSTALL_FULL=false
QUICK_SETUP=false

while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            show_help
            exit 0
            ;;
        -f|--full)
            INSTALL_FULL=true
            shift
            ;;
        -q|--quick)
            QUICK_SETUP=true
            shift
            ;;
        *)
            print_error "Unknown option: $1"
            show_help
            exit 1
            ;;
    esac
done

# Header
echo "================================================"
echo "JGT Data Refresh Service - Setup & Configuration"
echo "================================================"
print_status "Starting setup process..."
echo ""

# Step 1: Check Python environment
print_status "1. Checking Python environment..."
if command -v python &> /dev/null; then
    PYTHON_VERSION=$(python --version 2>&1)
    print_success "Python found: $PYTHON_VERSION"
else
    print_error "Python not found! Please install Python 3.8 or later"
    exit 1
fi

# Check Python version
PYTHON_VERSION_NUM=$(python -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')")
if python -c "import sys; sys.exit(0 if sys.version_info >= (3, 8) else 1)"; then
    print_success "Python version compatible: $PYTHON_VERSION_NUM"
else
    print_error "Python version too old: $PYTHON_VERSION_NUM (requires 3.8+)"
    exit 1
fi

echo ""

# Step 2: Install package
print_status "2. Installing jgtpy package..."

if [[ "$INSTALL_FULL" == true ]]; then
    print_status "Installing with full web service dependencies..."
    if pip install -e ".[serve]"; then
        print_success "jgtpy[serve] installed successfully"
    else
        print_error "Failed to install jgtpy[serve]"
        exit 1
    fi
else
    print_status "Installing base package..."
    if pip install -e .; then
        print_success "jgtpy installed successfully"
        print_status "For web service features, run: pip install -e .[serve]"
    else
        print_error "Failed to install jgtpy"
        exit 1
    fi
fi

echo ""

# Step 3: Create configuration directories
print_status "3. Setting up configuration directories..."

# Create JGT config directory
JGT_CONFIG_DIR="$HOME/.jgt"
if [[ ! -d "$JGT_CONFIG_DIR" ]]; then
    mkdir -p "$JGT_CONFIG_DIR"
    print_success "Created JGT config directory: $JGT_CONFIG_DIR"
else
    print_status "JGT config directory exists: $JGT_CONFIG_DIR"
fi

# Create data directories (if not quick setup)
if [[ "$QUICK_SETUP" != true ]]; then
    echo ""
    read -p "Enter data directory path (default: $HOME/jgt_data): " DATA_PATH
    DATA_PATH="${DATA_PATH:-$HOME/jgt_data}"
    
    if [[ ! -d "$DATA_PATH" ]]; then
        mkdir -p "$DATA_PATH"/{current,full}/{cds,ids,pds}
        print_success "Created data directories in: $DATA_PATH"
    else
        print_status "Data directory exists: $DATA_PATH"
    fi
else
    DATA_PATH="$HOME/jgt_data"
    mkdir -p "$DATA_PATH"/{current,full}/{cds,ids,pds}
    print_success "Created default data directories: $DATA_PATH"
fi

echo ""

# Step 4: Environment configuration
print_status "4. Setting up environment configuration..."

ENV_FILE="$HOME/.jgt/.env"
print_status "Creating environment file: $ENV_FILE"

cat > "$ENV_FILE" << EOF
# JGT Data Refresh Service Configuration
# Generated by setup script on $(date)

# === Data Storage Paths ===
JGTPY_DATA=$DATA_PATH/current
JGTPY_DATA_FULL=$DATA_PATH/full

# === Timeframe Configuration ===
TRADABLE_TIMEFRAMES=m5,m15,m30,H1,H4,D1
HIGH_TIMEFRAMES=H4,D1,W1
LOW_TIMEFRAMES=m5,m15,m30

# === Service Configuration ===
JGTPY_SERVICE_MAX_WORKERS=4
JGTPY_SERVICE_WEB_PORT=8080
JGTPY_SERVICE_REFRESH_INTERVAL=300

# === Processing Options ===
JGTPY_SERVICE_USE_FRESH=true
JGTPY_SERVICE_CONTINUE_ON_ERROR=true

# === Upload Configuration ===
JGTPY_SERVICE_ENABLE_UPLOAD=false
# JGTPY_DROPBOX_APP_TOKEN=your_dropbox_token_here

# === Security (Optional) ===
# JGTPY_API_KEY=your_api_key_here
EOF

print_success "Environment configuration created"

# Create shell source file
SHELL_SOURCE_FILE="$HOME/.jgt/jgt_env.sh"
cat > "$SHELL_SOURCE_FILE" << EOF
#!/bin/bash
# JGT Environment Variables
# Source this file to load JGT configuration: source ~/.jgt/jgt_env.sh

if [[ -f "$ENV_FILE" ]]; then
    set -a
    source "$ENV_FILE"
    set +a
    echo "JGT environment loaded from $ENV_FILE"
else
    echo "Warning: JGT environment file not found: $ENV_FILE"
fi
EOF

chmod +x "$SHELL_SOURCE_FILE"
print_success "Shell environment script created: $SHELL_SOURCE_FILE"

echo ""

# Step 5: Configure Dropbox (optional)
if [[ "$QUICK_SETUP" != true ]]; then
    print_status "5. Dropbox configuration (optional)..."
    echo ""
    print_status "To enable Dropbox uploads, you need a Dropbox App Token."
    print_status "Visit: https://www.dropbox.com/developers/apps"
    echo ""
    
    read -p "Do you have a Dropbox App Token? (y/N): " HAS_DROPBOX_TOKEN
    if [[ "$HAS_DROPBOX_TOKEN" =~ ^[Yy]$ ]]; then
        read -s -p "Enter your Dropbox App Token: " DROPBOX_TOKEN
        echo ""
        
        if [[ -n "$DROPBOX_TOKEN" ]]; then
            # Add token to environment file
            echo "" >> "$ENV_FILE"
            echo "# Dropbox configuration" >> "$ENV_FILE"
            echo "JGTPY_SERVICE_ENABLE_UPLOAD=true" >> "$ENV_FILE"
            echo "JGTPY_DROPBOX_APP_TOKEN=$DROPBOX_TOKEN" >> "$ENV_FILE"
            
            print_success "Dropbox token configured"
        fi
    else
        print_status "Dropbox configuration skipped"
        print_status "You can configure it later by editing: $ENV_FILE"
    fi
else
    print_status "5. Dropbox configuration skipped (quick setup)"
fi

echo ""

# Step 6: Test installation
print_status "6. Testing installation..."

# Load environment
set -a
source "$ENV_FILE"
set +a

# Test basic functionality
if command -v jgtservice &> /dev/null; then
    print_success "jgtservice command available"
    
    # Test configuration
    if jgtservice --status > /dev/null 2>&1; then
        print_success "Service configuration valid"
    else
        print_warning "Service configuration has issues"
        print_status "Running status check:"
        jgtservice --status
    fi
else
    print_error "jgtservice command not found after installation!"
fi

echo ""

# Step 7: Make scripts executable
print_status "7. Setting up helper scripts..."

SCRIPTS=("refresh-all.sh" "start-api-server.sh" "start-daemon.sh" "check-status.sh")

for script in "${SCRIPTS[@]}"; do
    if [[ -f "$script" ]]; then
        chmod +x "$script"
        print_success "Made $script executable"
    else
        print_warning "$script not found"
    fi
done

echo ""

# Setup complete
print_success "Setup completed successfully!"
echo ""

print_status "Configuration summary:"
print_status "- Data directory: $DATA_PATH"
print_status "- Config directory: $JGT_CONFIG_DIR"
print_status "- Environment file: $ENV_FILE"
print_status "- Shell source file: $SHELL_SOURCE_FILE"
echo ""

print_status "Next steps:"
echo "1. Load environment: source $SHELL_SOURCE_FILE"
echo "2. Test status: ./check-status.sh"
echo "3. Refresh data: ./refresh-all.sh"
echo "4. Start API server: ./start-api-server.sh"
echo "5. Start daemon: ./start-daemon.sh"
echo ""

print_status "Optional configuration:"
echo "- Edit environment: nano $ENV_FILE"
echo "- Configure Dropbox token for uploads"
echo "- Set up systemd service for production"
echo ""

if [[ "$INSTALL_FULL" != true ]]; then
    print_warning "For web API features, install full dependencies:"
    print_warning "  pip install -e .[serve]"
    echo ""
fi

print_success "JGT Data Refresh Service is ready to use!" 