# Template: install.sh.template
# Purpose:  Post-clone install script for the GitHub bundle — sets up workspace on a fresh machine
# Variables: team_name, orchestrator_name
# Rendered by: generate.py
#!/usr/bin/env bash
# install.sh — {{TEAM_NAME}} AGI Team Installer
# Generated by agi-farm on {{DATE}}
# Preset: {{PRESET}} agents | Frameworks: {{FRAMEWORKS}}

set -euo pipefail

WORKSPACE="${HOME}/.openclaw/workspace"
BUNDLE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SKILL_DIR="${HOME}/.openclaw/skills/agi-farm"

echo "🌾 Installing {{TEAM_NAME}} AGI Team..."
echo "   Workspace: ${WORKSPACE}"
echo "   Bundle:    ${BUNDLE_DIR}"
echo ""

# 1. Check prerequisites
if ! command -v openclaw &>/dev/null; then
  echo "❌ OpenClaw not found. Install it first: https://openclaw.dev"
  exit 1
fi

if ! command -v python3 &>/dev/null; then
  echo "❌ Python 3 required."
  exit 1
fi

# 2. Check agi-farm skill
if [ ! -f "${SKILL_DIR}/generate.py" ]; then
  echo "📦 Installing agi-farm skill..."
  git clone --depth 1 https://github.com/oabdelmaksoud/AGI-Farm.git "${SKILL_DIR}"
  echo "   agi-farm skill installed."
fi

# 3. Copy bundle to workspace
echo "📁 Setting up bundle..."
mkdir -p "${WORKSPACE}/agi-farm-bundle"
cp "${BUNDLE_DIR}/team.json" "${WORKSPACE}/agi-farm-bundle/team.json"

# 4. Generate workspace files
echo "🔨 Generating workspace files from team.json..."
python3 "${SKILL_DIR}/generate.py" \
  --team-json "${WORKSPACE}/agi-farm-bundle/team.json" \
  --output "${WORKSPACE}" \
  --all-agents --shared --bundle

# 5. Initialize JSON registries
echo "📊 Initializing registries..."
[ -f "${WORKSPACE}/TASKS.json" ] || echo '[]' > "${WORKSPACE}/TASKS.json"

python3 - <<'PYEOF'
import json, os
from pathlib import Path
workspace = Path(os.environ["HOME"]) / ".openclaw/workspace"
team_path = workspace / "agi-farm-bundle/team.json"
if team_path.exists():
    team = json.loads(team_path.read_text())
    status = {a["id"]: {"status": "available", "name": a["name"], "emoji": a["emoji"]}
              for a in team.get("agents", [])}
    (workspace / "AGENT_STATUS.json").write_text(json.dumps(status, indent=2))
    print(f"   AGENT_STATUS.json: {len(status)} agents registered")
PYEOF

echo ""
echo "✅ {{TEAM_NAME}} AGI Team installed!"
echo ""
echo "   Workspace:      ${WORKSPACE}/"
echo "   Orchestrator:   {{ORCHESTRATOR_NAME}}"
echo "   Agents:         {{PRESET}}"
echo "   Frameworks:     {{FRAMEWORKS}}"
echo ""
echo "Next steps:"
echo "   1. Open OpenClaw and talk to {{ORCHESTRATOR_NAME}}"
echo "   2. Check team status: /agi-farm status"
echo "   3. Assign your first task"
