#!/bin/bash
# scripts/setup-module.sh - Set up environment for Module 13

set -e

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

# Functions
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Detect OS
detect_os() {
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        OS="linux"
        if [ -f /etc/os-release ]; then
            . /etc/os-release
            DISTRO=$ID
        fi
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        OS="macos"
    elif [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]]; then
        OS="windows"
    else
        log_error "Unsupported operating system: $OSTYPE"
        exit 1
    fi
    
    log_info "Detected OS: $OS"
}

# Install Azure CLI
install_azure_cli() {
    if command -v az &> /dev/null; then
        log_info "Azure CLI already installed: $(az version --query '"azure-cli"' -o tsv)"
        return
    fi
    
    log_info "Installing Azure CLI..."
    
    case $OS in
        "linux")
            if [[ "$DISTRO" == "ubuntu" ]] || [[ "$DISTRO" == "debian" ]]; then
                curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash
            elif [[ "$DISTRO" == "rhel" ]] || [[ "$DISTRO" == "centos" ]]; then
                sudo rpm --import https://packages.microsoft.com/keys/microsoft.asc
                echo -e "[azure-cli]
name=Azure CLI
baseurl=https://packages.microsoft.com/yumrepos/azure-cli
enabled=1
gpgcheck=1
gpgkey=https://packages.microsoft.com/keys/microsoft.asc" | sudo tee /etc/yum.repos.d/azure-cli.repo
                sudo yum install azure-cli -y
            else
                log_error "Unsupported Linux distribution: $DISTRO"
                log_info "Please install Azure CLI manually: https://docs.microsoft.com/cli/azure/install-azure-cli"
                exit 1
            fi
            ;;
        "macos")
            if command -v brew &> /dev/null; then
                brew update && brew install azure-cli
            else
                log_error "Homebrew not installed. Please install Homebrew first: https://brew.sh"
                exit 1
            fi
            ;;
        "windows")
            log_info "Please download and install Azure CLI from:"
            echo "https://aka.ms/installazurecliwindows"
            exit 1
            ;;
    esac
}

# Install Terraform
install_terraform() {
    if command -v terraform &> /dev/null; then
        CURRENT_VERSION=$(terraform version -json | jq -r .terraform_version)
        log_info "Terraform already installed: $CURRENT_VERSION"
        
        # Check if version is >= 1.6.0
        if [[ "$(printf '%s\n' "1.6.0" "$CURRENT_VERSION" | sort -V | head -n1)" != "1.6.0" ]]; then
            log_warn "Terraform version is older than 1.6.0. Consider upgrading."
        fi
        return
    fi
    
    log_info "Installing Terraform..."
    
    TERRAFORM_VERSION="1.6.5"
    
    case $OS in
        "linux")
            wget -O- https://apt.releases.hashicorp.com/gpg | \
                gpg --dearmor | \
                sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg > /dev/null
            
            echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] \
                https://apt.releases.hashicorp.com $(lsb_release -cs) main" | \
                sudo tee /etc/apt/sources.list.d/hashicorp.list
            
            sudo apt update && sudo apt install terraform
            ;;
        "macos")
            if command -v brew &> /dev/null; then
                brew tap hashicorp/tap
                brew install hashicorp/tap/terraform
            else
                log_error "Homebrew not installed"
                exit 1
            fi
            ;;
        "windows")
            log_info "Please download Terraform from:"
            echo "https://www.terraform.io/downloads"
            exit 1
            ;;
    esac
}

# Install GitHub CLI
install_github_cli() {
    if command -v gh &> /dev/null; then
        log_info "GitHub CLI already installed: $(gh version | head -n1)"
        return
    fi
    
    log_info "Installing GitHub CLI..."
    
    case $OS in
        "linux")
            type -p curl >/dev/null || sudo apt install curl -y
            curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | \
                sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg
            
            echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] \
                https://cli.github.com/packages stable main" | \
                sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null
            
            sudo apt update && sudo apt install gh
            ;;
        "macos")
            brew install gh
            ;;
        "windows")
            log_info "Please download GitHub CLI from:"
            echo "https://cli.github.com"
            exit 1
            ;;
    esac
}

# Install Python dependencies
install_python_deps() {
    if ! command -v python3 &> /dev/null; then
        log_warn "Python 3 not installed. Some features may not work."
        return
    fi
    
    log_info "Installing Python dependencies..."
    
    # Create virtual environment
    python3 -m venv .venv
    
    # Activate and install
    if [[ "$OS" == "windows" ]]; then
        .venv/Scripts/activate
    else
        source .venv/bin/activate
    fi
    
    pip install --upgrade pip
    pip install azure-identity azure-mgmt-resource azure-mgmt-web azure-mgmt-storage requests pytest
    
    log_info "Python dependencies installed in .venv"
}

# Install VS Code extensions
install_vscode_extensions() {
    if ! command -v code &> /dev/null; then
        log_warn "VS Code CLI not found. Please install VS Code extensions manually:"
        echo "  - ms-azuretools.vscode-bicep"
        echo "  - hashicorp.terraform"
        echo "  - ms-vscode.azurecli"
        echo "  - github.copilot"
        echo "  - github.vscode-github-actions"
        return
    fi
    
    log_info "Installing VS Code extensions..."
    
    extensions=(
        "ms-azuretools.vscode-bicep"
        "hashicorp.terraform"
        "ms-vscode.azurecli"
        "github.copilot"
        "github.vscode-github-actions"
        "ms-azuretools.vscode-azureresourcegroups"
    )
    
    for ext in "${extensions[@]}"; do
        code --install-extension "$ext" || log_warn "Failed to install $ext"
    done
}

# Configure Bicep
configure_bicep() {
    log_info "Configuring Bicep..."
    
    # Install/upgrade Bicep
    az bicep install
    
    # Verify installation
    BICEP_VERSION=$(az bicep version)
    log_info "Bicep version: $BICEP_VERSION"
}

# Create module structure
create_module_structure() {
    log_info "Creating module directory structure..."
    
    directories=(
        "exercises/exercise1-bicep-basics/starter"
        "exercises/exercise1-bicep-basics/solution"
        "exercises/exercise1-bicep-basics/tests"
        "exercises/exercise2-terraform-environments/starter"
        "exercises/exercise2-terraform-environments/solution"
        "exercises/exercise2-terraform-environments/tests"
        "exercises/exercise2-terraform-environments/modules/network"
        "exercises/exercise2-terraform-environments/modules/webapp"
        "exercises/exercise2-terraform-environments/environments"
        "exercises/exercise3-gitops-pipeline/starter"
        "exercises/exercise3-gitops-pipeline/solution"
        "exercises/exercise3-gitops-pipeline/tests"
        "exercises/exercise3-gitops-pipeline/.github/workflows"
        "exercises/exercise3-gitops-pipeline/policies"
        "infrastructure/bicep"
        "infrastructure/terraform"
        "infrastructure/github-actions"
        "scripts"
        "docs"
    )
    
    for dir in "${directories[@]}"; do
        mkdir -p "$dir"
    done
    
    log_info "Directory structure created"
}

# Setup Git hooks
setup_git_hooks() {
    if [ ! -d .git ]; then
        log_warn "Not in a git repository. Skipping git hooks setup."
        return
    fi
    
    log_info "Setting up git hooks..."
    
    # Pre-commit hook for formatting
    cat > .git/hooks/pre-commit << 'EOF'
#!/bin/bash
# Format Terraform files
if command -v terraform &> /dev/null; then
    terraform fmt -recursive infrastructure/
fi

# Format Bicep files
if command -v az &> /dev/null; then
    find . -name "*.bicep" -type f -exec az bicep format --file {} \;
fi
EOF
    
    chmod +x .git/hooks/pre-commit
    log_info "Git hooks configured"
}

# Main setup function
main() {
    echo "🚀 Module 13: Infrastructure as Code - Environment Setup"
    echo "======================================================"
    echo ""
    
    detect_os
    
    # Core installations
    install_azure_cli
    install_terraform
    install_github_cli
    install_python_deps
    install_vscode_extensions
    
    # Configuration
    configure_bicep
    create_module_structure
    setup_git_hooks
    
    # Azure login check
    if ! az account show &> /dev/null; then
        log_warn "Not logged into Azure. Please run: az login"
    else
        ACCOUNT=$(az account show --query name -o tsv)
        log_info "Azure account: $ACCOUNT"
    fi
    
    # Final verification
    echo ""
    log_info "Setup complete! Verifying installations:"
    echo ""
    
    # Run prerequisite check
    if [ -f "scripts/check-prerequisites.sh" ]; then
        bash scripts/check-prerequisites.sh
    fi
    
    echo ""
    log_info "🎉 Environment ready for Module 13!"
    log_info "Next steps:"
    echo "  1. Run 'az login' if not already logged in"
    echo "  2. Review the module README.md"
    echo "  3. Start with Exercise 1 in exercises/exercise1-bicep-basics/"
}

# Run main
main