#!/usr/bin/env bash
set -euo pipefail

# Huskies migration script
#
# Migrates an existing storkit project to huskies by renaming the .storkit/
# directory to .huskies/ and updating the .mcp.json server registration.
#
# Usage:
#   script/migrate [PROJECT_PATH]
#
# If PROJECT_PATH is omitted, the current directory is used.

PROJECT_PATH="${1:-$(pwd)}"

if [ ! -d "$PROJECT_PATH" ]; then
  echo "Error: '$PROJECT_PATH' is not a directory."
  exit 1
fi

STORKIT_DIR="$PROJECT_PATH/.storkit"
HUSKIES_DIR="$PROJECT_PATH/.huskies"
MCP_JSON="$PROJECT_PATH/.mcp.json"

echo "==> Migrating project at: $PROJECT_PATH"

# ── Rename .storkit/ → .huskies/ ──────────────────────────────────
if [ -d "$STORKIT_DIR" ]; then
  if [ -d "$HUSKIES_DIR" ]; then
    echo "  .huskies/ already exists — skipping directory rename."
  else
    mv "$STORKIT_DIR" "$HUSKIES_DIR"
    echo "  Renamed .storkit/ → .huskies/"
  fi
else
  if [ -d "$HUSKIES_DIR" ]; then
    echo "  .huskies/ already present (already migrated)."
  else
    echo "  No .storkit/ or .huskies/ directory found — nothing to migrate."
    exit 0
  fi
fi

# ── Update .mcp.json ──────────────────────────────────────────────
if [ -f "$MCP_JSON" ]; then
  if grep -q '"storkit"' "$MCP_JSON"; then
    # Replace the MCP server key "storkit" with "huskies"
    python3 -c "
import json, sys
with open(sys.argv[1]) as f:
    cfg = json.load(f)
servers = cfg.get('mcpServers', {})
if 'storkit' in servers and 'huskies' not in servers:
    servers['huskies'] = servers.pop('storkit')
cfg['mcpServers'] = servers
with open(sys.argv[1], 'w') as f:
    json.dump(cfg, f, indent=2)
    f.write('\n')
" "$MCP_JSON"
    echo "  Updated .mcp.json: renamed mcpServers key 'storkit' → 'huskies'"
  else
    echo "  .mcp.json already uses 'huskies' key — skipping."
  fi
else
  echo "  No .mcp.json found — skipping."
fi

# ── Update root-level .gitignore ──────────────────────────────────
GITIGNORE="$PROJECT_PATH/.gitignore"
if [ -f "$GITIGNORE" ]; then
  if grep -q "\.storkit_port" "$GITIGNORE"; then
    sed -i 's/\.storkit_port/\.huskies_port/g' "$GITIGNORE"
    echo "  Updated .gitignore: .storkit_port → .huskies_port"
  fi
fi

echo ""
echo "==> Migration complete."
echo "    Restart huskies to pick up the new directory layout."
