#!/bin/bash

# Colors for better readability
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Print section header
print_header() {
    echo -e "\n${GREEN}=== $1 ===${NC}\n"
}

# Check if a command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Check for required system dependencies
check_dependencies() {
    print_header "Checking Dependencies"
    
    # Check for Git
    if command_exists git; then
        echo -e "${GREEN}✓${NC} Git installed: $(git --version)"
    else
        echo -e "${RED}✗${NC} Git is not installed. Please install Git."
        exit 1
    fi
    
    # Check for Python
    if command_exists python3; then
        PYTHON_VERSION=$(python3 --version 2>&1 | awk '{print $2}')
        REQUIRED_VERSION="3.11"
        if python3 -c "import sys; exit(0 if sys.version_info >= (3, 11) else 1)" 2>/dev/null; then
            echo -e "${GREEN}✓${NC} Python installed: $(python3 --version)"
        else
            echo -e "${YELLOW}!${NC} Python $PYTHON_VERSION installed, but 3.11+ is recommended for development"
        fi
    else
        echo -e "${RED}✗${NC} Python 3 is not installed. Please install Python 3.11 or higher."
        exit 1
    fi
}

# Check if this is a Git repository with submodules
check_git_setup() {
    print_header "Checking Git Repository Setup"
    
    # Check if this is a git repository
    if [ ! -d ".git" ]; then
        echo -e "${YELLOW}!${NC} This directory is not a Git repository."
        echo "If you're working with the open source version, this is normal."
        echo "Skipping Git submodule setup."
        return 0
    fi
    
    # Check if there are submodules defined
    if [ ! -f ".gitmodules" ]; then
        echo -e "${YELLOW}!${NC} No Git submodules found."
        echo "This is normal for the current repository structure."
        return 0
    fi
    
    echo "Initializing and updating Git submodules..."
    git submodule init
    if [ $? -eq 0 ]; then
        git submodule update --recursive
        if [ $? -eq 0 ]; then
            echo -e "${GREEN}✓${NC} Git submodules initialized and updated successfully"
        else
            echo -e "${RED}✗${NC} Failed to update Git submodules"
            exit 1
        fi
    else
        echo -e "${RED}✗${NC} Failed to initialize Git submodules"
        exit 1
    fi
}

# Verify trains service has required files
setup_trains_service() {
    print_header "Verifying Trains Service"
    
    # Check if trains directory exists
    if [ ! -d "trains" ]; then
        echo -e "${RED}✗${NC} Trains directory not found. This should exist in the repository."
        exit 1
    else
        echo -e "${GREEN}✓${NC} Trains directory exists"
    fi
    
    # Check if required train modules exist
    if [ ! -f "trains/train_types.py" ]; then
        echo -e "${RED}✗${NC} trains/train_types.py not found. This file should exist in the repository."
        exit 1
    else
        echo -e "${GREEN}✓${NC} Train types module exists"
    fi
    
    # Don't create main.py if it doesn't exist - it should already be there
    if [ ! -f "trains/main.py" ]; then
        echo -e "${RED}✗${NC} trains/main.py not found. This file should exist in the repository."
        echo "Please ensure the trains directory is properly set up."
        exit 1
    else
        echo -e "${GREEN}✓${NC} Trains main.py exists"
    fi
}

# Set up application environment
setup_environment() {
    print_header "Setting Up Application Environment"
    
    # Create .env file if it doesn't exist
    if [ ! -f ".env" ]; then
        echo "Creating .env file with default values..."
        cat > .env << EOL
# NYC Train Status Server Configuration
# Generated by setup.sh

# Environment variables for the main service
PORT=4599
PYTHONPATH=/app

# Environment variables for the trains service
TRAINS_PORT=4600

# Add any additional environment variables here
HOST=server.local

# Server URL Configuration - REQUIRED
# Example: localhost, server.local, myserver.com
SERVER_URL=localhost

# MTA API Configuration
# Note: MTA GTFS feeds are public and don't require API keys
# The application uses these public endpoints for all NYC subway lines
EOL
        echo -e "${GREEN}✓${NC} Created .env file with default settings"
    else
        echo -e "${YELLOW}!${NC} .env file already exists, keeping existing configuration"
    fi
    
    echo -e "${GREEN}✓${NC} Application environment setup complete"
}

# Start the application
start_application() {
    print_header "Starting Application"
    
    echo "Starting the NYC Train Status API..."
    python3 start.py
}

# Main function
main() {
    print_header "NYC Train Status Server - Setup"
    echo "Welcome to the NYC Train Status Server setup!"
    echo "This script will help you get the application running on your system."
    echo ""
    echo "This project is open source under the MIT License."
    echo "Repository: https://github.com/dvd-rsnw/server"
    echo ""
    echo "The setup will:"
    echo "  - Check for required dependencies"
    echo "  - Check Git repository setup"
    echo "  - Verify the trains service configuration"
    echo "  - Set up the application environment"
    echo "  - Optionally start the application"
    echo ""
    read -p "Press Enter to continue..."
    
    # Check dependencies
    check_dependencies
    
    # Check Git setup
    check_git_setup
    
    # Verify trains service
    setup_trains_service
    
    # Set up application environment
    setup_environment
    
    # Ask whether to start the application
    echo -e "\nDo you want to start the application now?"
    read -p "Enter your choice (y/n): " start_choice
    
    if [ "$start_choice" == "y" ] || [ "$start_choice" == "Y" ]; then
        start_application
    else
        echo -e "\n${GREEN}Setup completed successfully!${NC}"
        echo ""
        echo "Next steps:"
        echo "  1. To start the application: python3 start.py"
        echo "  2. Access the API at: http://localhost:4600"
        echo "  3. View API docs at: http://localhost:4600/docs"
        echo ""
        echo "For more information:"
        echo "  - README: https://github.com/dvd-rsnw/server#readme"
        echo "  - Issues: https://github.com/dvd-rsnw/server/issues"
        echo ""
        echo "Thank you for using NYC Train Status Server!"
    fi
}

# Run main function
main