#!/usr/bin/env bash
# detach - Remove this capability from an integrating project
#
# Usage:
#   From the capability root:
#     ./.capability/detach
#
#   From integrating project:
#     _issue-facade/.capability/detach
#     # or
#     capabilities/issue-facade/.capability/detach
#
# This script helps cleanly remove a capability integration, creating
# a manifest for potential re-integration with updated architecture.

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

info() { echo -e "${BLUE}$1${NC}"; }
success() { echo -e "${GREEN}$1${NC}"; }
warn() { echo -e "${YELLOW}$1${NC}"; }
error() { echo -e "${RED}Error: $1${NC}" >&2; exit 1; }

# Detect capability information
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CAPABILITY_ROOT="$(dirname "$SCRIPT_DIR")"
CAPABILITY_NAME="$(basename "$CAPABILITY_ROOT")"

# Try to read capability metadata
CAPABILITY_FILE=""
if [ -f "$CAPABILITY_ROOT"/CAPABILITY-*.yaml ]; then
    CAPABILITY_FILE=$(ls "$CAPABILITY_ROOT"/CAPABILITY-*.yaml | head -1)
    CAPABILITY_FAMILY=$(basename "$CAPABILITY_FILE" .yaml | sed 's/^CAPABILITY-//')
else
    warn "No CAPABILITY-*.yaml file found, using directory name"
    CAPABILITY_FAMILY="$CAPABILITY_NAME"
fi

echo -e "${BLUE}╔════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║   Capability Detachment Tool                  ║${NC}"
echo -e "${BLUE}╔════════════════════════════════════════════════╝${NC}"
echo ""
info "Capability: $CAPABILITY_NAME"
info "Family:     $CAPABILITY_FAMILY"
info "Location:   $CAPABILITY_ROOT"
echo ""

# Detect parent project
PARENT_DIR="$(dirname "$CAPABILITY_ROOT")"
PARENT_NAME="$(basename "$PARENT_DIR")"

# Determine integration pattern
INTEGRATION_PATTERN="unknown"
if [[ "$CAPABILITY_NAME" == _* ]]; then
    INTEGRATION_PATTERN="underscore-prefix"
elif [[ "$PARENT_NAME" == "capabilities" ]]; then
    INTEGRATION_PATTERN="capabilities-directory"
elif [[ "$PARENT_NAME" == "c" ]]; then
    INTEGRATION_PATTERN="short-alias"
else
    INTEGRATION_PATTERN="custom"
fi

info "Integration pattern: $INTEGRATION_PATTERN"
echo ""

# Safety check
warn "⚠️  This will remove the capability integration from the parent project."
echo ""
echo "The following will happen:"
echo "  1. Create detachment manifest (DETACHED-$CAPABILITY_NAME.yaml)"
echo "  2. Remove capability directory: $CAPABILITY_ROOT"
echo "  3. Clean up any integration artifacts"
echo ""
read -p "Continue? (yes/no): " confirm

if [[ "$confirm" != "yes" ]]; then
    info "Detachment cancelled."
    exit 0
fi

echo ""
info "Creating detachment manifest..."

# Create detachment manifest
MANIFEST_FILE="$PARENT_DIR/DETACHED-$CAPABILITY_NAME.yaml"

cat > "$MANIFEST_FILE" <<EOF
# Detachment Manifest
# This file records the removal of the $CAPABILITY_NAME capability
# Use this information to re-integrate with updated architecture

detachment:
  timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ)
  capability_name: $CAPABILITY_NAME
  capability_family: $CAPABILITY_FAMILY
  integration_pattern: $INTEGRATION_PATTERN
  original_location: $CAPABILITY_ROOT

capability_metadata:
EOF

# Append capability metadata if available
if [ -n "$CAPABILITY_FILE" ]; then
    echo "  spec_file: $(basename "$CAPABILITY_FILE")" >> "$MANIFEST_FILE"

    # Try to extract key metadata
    if command -v yq &> /dev/null; then
        {
            echo "  version: $(yq eval '.metadata.version' "$CAPABILITY_FILE" 2>/dev/null || echo 'unknown')"
            echo "  implementation: $(yq eval '.metadata.implementation' "$CAPABILITY_FILE" 2>/dev/null || echo 'unknown')"
            echo "  maturity: $(yq eval '.metadata.maturity' "$CAPABILITY_FILE" 2>/dev/null || echo 'unknown')"
        } >> "$MANIFEST_FILE"
    fi
fi

cat >> "$MANIFEST_FILE" <<EOF

integration_details:
  parent_project: $PARENT_NAME
  parent_path: $PARENT_DIR

re_integration_guide: |
  To re-integrate this capability using the new architecture:

  # Option 1: Git submodule (recommended)
  cd $PARENT_DIR
  git submodule add <repo-url> _$CAPABILITY_NAME
  pip install -e _$CAPABILITY_NAME/

  # Option 2: Clone directly
  cd $PARENT_DIR
  git clone <repo-url> _$CAPABILITY_NAME
  pip install -e _$CAPABILITY_NAME/

  # Option 3: Copy into project
  cd $PARENT_DIR
  cp -r /path/to/$CAPABILITY_NAME _$CAPABILITY_NAME
  pip install -e _$CAPABILITY_NAME/

  Note: Use underscore prefix (_$CAPABILITY_NAME) per ReusableCapabilitiesArchitecture

notes:
  - The original integration used pattern: $INTEGRATION_PATTERN
  - New architecture recommends: underscore-prefix at repo root
  - See ReusableCapabilitiesArchitecture.md for details

repository_info:
  # Fill in if re-integrating from git
  git_url: ""  # e.g., https://github.com/markitect/$CAPABILITY_NAME
  git_branch: ""  # e.g., main
  git_commit: ""  # Optional: specific commit to use
EOF

success "✓ Created manifest: $MANIFEST_FILE"
echo ""

# Check for git
if git -C "$CAPABILITY_ROOT" rev-parse --git-dir > /dev/null 2>&1; then
    REPO_URL=$(git -C "$CAPABILITY_ROOT" config --get remote.origin.url 2>/dev/null || echo "")
    BRANCH=$(git -C "$CAPABILITY_ROOT" rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")
    COMMIT=$(git -C "$CAPABILITY_ROOT" rev-parse HEAD 2>/dev/null || echo "")

    if [ -n "$REPO_URL" ]; then
        info "Git repository detected:"
        echo "  URL:    $REPO_URL"
        echo "  Branch: $BRANCH"
        echo "  Commit: $COMMIT"
        echo ""

        # Update manifest with git info
        sed -i "s|git_url: \"\"|git_url: \"$REPO_URL\"|" "$MANIFEST_FILE"
        sed -i "s|git_branch: \"\"|git_branch: \"$BRANCH\"|" "$MANIFEST_FILE"
        sed -i "s|git_commit: \"\"|git_commit: \"$COMMIT\"|" "$MANIFEST_FILE"
    fi
fi

# Check if this is a git submodule
if [ -f "$PARENT_DIR/.gitmodules" ] && grep -q "$CAPABILITY_NAME" "$PARENT_DIR/.gitmodules"; then
    warn "⚠️  This appears to be a git submodule"
    echo ""
    echo "To properly remove a submodule:"
    echo "  cd $PARENT_DIR"
    echo "  git submodule deinit -f $CAPABILITY_ROOT"
    echo "  git rm -f $CAPABILITY_ROOT"
    echo "  rm -rf .git/modules/$CAPABILITY_NAME"
    echo ""
    read -p "Run these commands now? (yes/no): " run_submodule

    if [[ "$run_submodule" == "yes" ]]; then
        cd "$PARENT_DIR"
        git submodule deinit -f "$CAPABILITY_ROOT" || warn "Submodule deinit failed (might not be initialized)"
        git rm -f "$CAPABILITY_ROOT" || warn "Git rm failed"
        rm -rf .git/modules/"$CAPABILITY_NAME" || warn "Module cleanup failed"
        success "✓ Git submodule removed"
    else
        warn "Skipping submodule removal - you'll need to do this manually"
        info "Removing directory anyway..."
        rm -rf "$CAPABILITY_ROOT"
    fi
else
    # Not a submodule, just remove directory
    info "Removing capability directory..."
    rm -rf "$CAPABILITY_ROOT"
    success "✓ Directory removed"
fi

echo ""
success "═══════════════════════════════════════"
success "  Capability detached successfully!"
success "═══════════════════════════════════════"
echo ""
info "Manifest saved to: $MANIFEST_FILE"
echo ""
echo "To re-integrate using new architecture:"
echo "  1. Read the manifest: cat $MANIFEST_FILE"
echo "  2. Follow re_integration_guide in the manifest"
echo "  3. Use underscore prefix: _$CAPABILITY_NAME/"
echo ""
info "See ReusableCapabilitiesArchitecture.md for details"
