#!/bin/bash

# Fix workspace permissions
sudo chown -R vscode:vscode /workspace

# Load environment variables first - these must be available to all scripts
devcontainerDir=/tmp/.devcontainer
postCreateEnvFile=$devcontainerDir/postCreate.env.tmp
[ -f $postCreateEnvFile ] || {
    echo "❌ The env file: $postCreateEnvFile does not exist! This should have been generated by the build.sh script."
    exit 1
}

eval "$(grep -v '^#' $postCreateEnvFile | sed 's/^/export /')"
export workingCopy=/workspace/ai-code-forge
export worktreesDir=/workspace/worktrees/ai-code-forge

echo "Configuration from initializeCommand:"
echo "repositoryName: ai-code-forge"
echo "repositoryNameWithOwner: ondrasek/ai-code-forge"
echo "gitUserName: $gitUserName"
echo "gitUserEmail: $gitUserEmail"
echo "workingCopy: $workingCopy"
echo "worktreesDir: $worktreesDir"

# Detect if we're in a container environment
export CONTAINER_ENV=1

# Detect runtime environment for scripts
export RUNTIME_ENV="devcontainer"
if [ "$CODESPACES" = "true" ]; then
  export RUNTIME_ENV="codespaces"
  echo "🌐 GitHub Codespaces environment detected"
else
  echo "🐳 DevContainer environment detected"
fi

set -e

# Execute setup scripts in order
postCreateScriptsDir=$(dirname $0)/postCreate-scripts
echo "🔄 Running setup scripts in: $postCreateScriptsDir"

# Static installations now handled by Dockerfile:
# - System package updates (apt-upgrade.sh)
# - Python tools installation (install-python-tools.sh) 
# - Zsh installation (install-zsh.sh)
# - Oh-my-zsh configuration (configure-oh-my-zsh.sh)

# Node.js tools (require DevContainer Node.js feature to be available):
"$postCreateScriptsDir/install-ai-tools.sh"
"$postCreateScriptsDir/install-mcp-tools.sh"

# Runtime-specific configurations:
"$postCreateScriptsDir/install-apt-dependencies.sh"
"$postCreateScriptsDir/configure-git.sh"
"$postCreateScriptsDir/setup-github-authentication.sh"
"$postCreateScriptsDir/clone-repository.sh"
"$postCreateScriptsDir/setup-workspace.sh"
"$postCreateScriptsDir/configure-worktree-shell-commands.sh"
"$postCreateScriptsDir/setup-environment-variables.sh"
"$postCreateScriptsDir/setup-shell-navigation.sh"
"$postCreateScriptsDir/verify-all-tools-installed.sh"

echo "🎉 All setup scripts completed successfully!"