#!/bin/bash
set -euo pipefail

# DevPod one-time setup for Foxhunt development
# Prerequisites: devpod CLI installed, kubectl configured for foxhunt cluster
#
# Install DevPod:
#   curl -fsSL https://devpod.sh/install.sh | bash
#
# Usage:
#   ./scripts/devpod-setup.sh
#   devpod up .                  # from the foxhunt repo root
#   devpod up git@100.90.76.85:2222/root/foxhunt.git  # from anywhere

echo "=== Foxhunt DevPod Setup ==="

# Check prerequisites
command -v devpod >/dev/null 2>&1 || { echo "Error: devpod not installed. Run: curl -fsSL https://devpod.sh/install.sh | bash"; exit 1; }
command -v kubectl >/dev/null 2>&1 || { echo "Error: kubectl not found"; exit 1; }

# Verify cluster access
if ! kubectl -n foxhunt get ns foxhunt >/dev/null 2>&1; then
    echo "Error: Cannot reach foxhunt namespace. Check kubectl config."
    exit 1
fi

# Ensure PVC exists
if ! kubectl -n foxhunt get pvc dev-home-pvc >/dev/null 2>&1; then
    echo "Creating dev-home-pvc (50Gi block storage)..."
    kubectl apply -f infra/k8s/storage/dev-home-pvc.yaml
fi

# Add kubernetes provider (idempotent)
devpod provider add kubernetes 2>/dev/null || true

# Configure provider
devpod provider set kubernetes \
    KUBERNETES_NAMESPACE=foxhunt \
    NODE_SELECTOR="k8s.scaleway.com/pool-name=gpu-dev" \
    DISK_SIZE=10Gi \
    STORAGE_CLASS=scw-bssd \
    INACTIVITY_TIMEOUT=30m \
    IMAGE_PULL_SECRETS=gitlab-registry \
    POD_MANIFEST_TEMPLATE=.devcontainer/pod-template.yaml

# Configure image pull secrets if not already present
if ! kubectl -n foxhunt get secret gitlab-registry >/dev/null 2>&1; then
    echo ""
    echo "NOTE: You need to create the gitlab-registry pull secret:"
    echo "  kubectl -n foxhunt create secret docker-registry gitlab-registry \\"
    echo "    --docker-server=gitlab-registry.foxhunt.svc.cluster.local:5000 \\"
    echo "    --docker-username=<user> --docker-password=<token>"
    echo ""
fi

echo ""
echo "=== Setup complete ==="
echo ""
echo "Usage:"
echo "  devpod up .                                         # from repo root"
echo "  devpod up git@100.90.76.85:2222/root/foxhunt.git   # from anywhere"
echo ""
echo "Open in DevPod link (bookmark this):"
echo "  https://devpod.sh/open#ssh://git@100.90.76.85:2222/root/foxhunt.git"
echo ""
echo "Session lifecycle:"
echo "  devpod up foxhunt     # start/reconnect"
echo "  devpod stop foxhunt   # stop (PVC preserved, node scales down)"
echo "  devpod delete foxhunt # delete workspace (PVC preserved)"
echo ""
