#!/usr/bin/env bash

set -e

# Parse command line arguments
agent_mode=false
auto_yes=false
for arg in "$@"; do
    case $arg in
        --agent)
            agent_mode=true
            shift
            ;;
        -y|--yes)
            auto_yes=true
            shift
            ;;
    esac
done

interactive_only() {
    if ! $agent_mode; then
        "$@"
    fi
}

onboarding_pass=true

# region: Onboarding checks

if [ ! -f "mise.local.toml" ]; then
    cat > mise.local.toml << EOF
# Local mise configuration
# This file is gitignored and can contain tools and environment variables
# that you personally need for local development.

[tools]
# Add your local tools here. Example:
# dive = "latest"

[env]
# Add your local environment variables here. Example:
# EXAMPLE_VAR = "value"
EOF
    echo "✅ Created mise.local.toml file"
fi

if [ -f "mise.worktree.local.toml" ]; then
    echo "ℹ️ Found mise.worktree.local.toml. Running zero with MISE_ENV=worktree."
    export MISE_ENV=worktree
fi

check_command() {
    local cmd=$1
    local instructions=$2

    if ! command -v "$cmd" &> /dev/null; then
        onboarding_pass=false
        
        echo "## \`$cmd\` not found:"
        echo "$instructions" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
        echo
    fi
}

# Install mise automatically in agent mode
if $agent_mode && ! command -v mise &> /dev/null; then
    echo "⏳ Installing mise..."
    curl -fsSL https://mise.run | sh
    export PATH="$HOME/.local/bin:$PATH"
    mise trust
else
    check_command "mise" "
    Install it from here: https://mise.jdx.dev/
    - Make sure to update your .zprofile (zsh), .profile (bash), ...
    - Additionaly enable completions for better DX: https://mise.jdx.dev/installing-mise.html#autocompletion
    "
fi


if ! $agent_mode; then
    check_command "docker" "
    Install it from here: https://www.docker.com/
    "
fi

if ! $agent_mode && [[ "$(uname -s)" == "Darwin" ]]; then
    if ! command -v limactl &> /dev/null; then
        echo "⚠️  limactl not found. Assistant runtime (Lima + Firecracker) won't work locally."
        echo "   Install from https://lima-vm.io/ or via Homebrew: brew install lima"
        echo "   Skip this if you don't need to run the assistant runtime locally."
        echo
    fi
fi

if [ $onboarding_pass = "false" ]; then
    echo "❌ Onboarding checks failed. Please fix the issues above and rerun this script."
    exit 1
fi

# endregion: Onboarding checks

echo -e "\n⏳ Installing tools"
mise install

echo -e "\n⏳ Installing dependencies"
mise run install

echo -e "\n⏳ Setting up API keys and secrets"
interactive_only mise run zero:github
interactive_only mise run zero:openrouter
interactive_only mise run zero:idp
interactive_only mise run zero:melange
interactive_only mise run zero:fly
mise run zero:encryption
mise run zero:tls
assistant_runtime_provider="$(mise env GRAM_ASSISTANT_RUNTIME_PROVIDER 2>/dev/null | sed -n 's/^export GRAM_ASSISTANT_RUNTIME_PROVIDER=//p')"
assistant_runtime_provider="${assistant_runtime_provider:-local}"
if [[ "$assistant_runtime_provider" == "local" ]]; then
    interactive_only mise run zero:assistants-runtime
    if ! $agent_mode && [[ "$(uname -s)" == "Darwin" ]] && command -v limactl &> /dev/null; then
        mise run zero:assistants-lima

        assistant_arch="$(uname -m)"
        assistant_arch="${assistant_arch/aarch64/aarch64}"
        assistant_arch="${assistant_arch/arm64/aarch64}"
        assistant_arch="${assistant_arch/x86_64/x86_64}"
        assistant_artifact_dir="agents/runtime-artifacts/${assistant_arch}"
        if [ ! -f "${assistant_artifact_dir}/firecracker" ] || [ ! -f "${assistant_artifact_dir}/vmlinux.bin" ] || [ ! -f "${assistant_artifact_dir}/assistant-rootfs.ext4" ]; then
            echo -e "\n⏳ Building assistant runtime artifacts"
            mise run build:assistants-local
        fi
    fi
else
    echo "ℹ️  Skipping local assistant runtime setup: GRAM_ASSISTANT_RUNTIME_PROVIDER=${assistant_runtime_provider}"
fi

echo -e "\n⏳ Building internal SDK"
mise run build:internal-sdk

echo -e "\n⏳ Updating VS Code and Cursor editor settings"
mise run install:vscode

echo -e "\n⏳ Setting up hooks"
interactive_only mise run zero:hk
interactive_only mise run zero:claude

echo -e "\n⏳ Cleaning up stale processes and Temporal state"
interactive_only mise run zero:cleanup
echo "✅ Cleaned up stale state"

echo -e "\n⏳ Starting infra"
interactive_only mise infra:start

echo -e "\n⏳ Running migrations"
mise run zero:migrations
mise db:migrate
mise clickhouse:migrate

interactive_only mise run zero:devidp

interactive_only mise zero:summary

echo -e "\n✅ All set up!"

if $auto_yes; then
    exec mise run start
elif ! $agent_mode; then
    echo "Want me to start the server and dashboard (\`mise run start\`)?"
    echo -n "[y/N] "
    read -r answer
    answer=$(echo "$answer" | tr '[:upper:]' '[:lower:]')
    if [ "$answer" = "y" ]; then
    exec mise run start
    fi
fi
