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

# setup.sh — Symlink CLAUDE.md files from insights-ai into each service repository.
#
# Usage:
#   ./setup.sh              # Symlink all services
#   ./setup.sh --dry-run    # Show what would be done without making changes
#   ./setup.sh --remove     # Remove all symlinks created by this script

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PARENT_DIR="$(dirname "$SCRIPT_DIR")"

DRY_RUN=false
REMOVE=false

for arg in "$@"; do
    case "$arg" in
        --dry-run) DRY_RUN=true ;;
        --remove)  REMOVE=true ;;
        *)         echo "Unknown argument: $arg"; exit 1 ;;
    esac
done

# Services that already have their own CLAUDE.md — only symlink if absent
EXISTING_CLAUDE_MD=(
    "frontend-insights"
    "graphql-analytics"
)

# Services that need CLAUDE.md created via symlink
NEW_CLAUDE_MD=(
    "dbt-analytics"
    "graphql-knowledge-search"
    "graphql-knowledge"
    "graphql-product"
    "graphql-user"
    "graphql-router"
    "ows-analytics"
    "ows-charts"
    "ows-playlist"
    "orchard-suite"
)

link_service() {
    local service="$1"
    local source="$SCRIPT_DIR/services/${service}.md"
    local target="$PARENT_DIR/${service}/CLAUDE.md"

    if [ ! -f "$source" ]; then
        echo "  SKIP  $service (no source file: services/${service}.md)"
        return
    fi

    if [ ! -d "$PARENT_DIR/$service" ]; then
        echo "  SKIP  $service (directory not found: $PARENT_DIR/$service)"
        return
    fi

    if $REMOVE; then
        if [ -L "$target" ]; then
            if $DRY_RUN; then
                echo "  WOULD REMOVE  $target"
            else
                rm "$target"
                echo "  REMOVED  $target"
            fi
        else
            echo "  SKIP  $target (not a symlink)"
        fi
        return
    fi

    if [ -f "$target" ] && [ ! -L "$target" ]; then
        echo "  KEEP  $service (has own CLAUDE.md — not overwriting)"
        return
    fi

    if [ -L "$target" ]; then
        local current
        current="$(readlink "$target")"
        if [ "$current" = "$source" ]; then
            echo "  OK    $service (symlink already correct)"
            return
        fi
    fi

    if $DRY_RUN; then
        echo "  WOULD LINK  $target -> $source"
    else
        ln -sf "$source" "$target"
        echo "  LINKED  $target -> services/${service}.md"
    fi
}

echo ""
echo "insights-ai setup"
echo "=================="
echo "Source: $SCRIPT_DIR/services/"
echo "Target: $PARENT_DIR/"
echo ""

if $DRY_RUN; then
    echo "Mode: DRY RUN (no changes will be made)"
    echo ""
fi

if $REMOVE; then
    echo "Mode: REMOVE (removing symlinks)"
    echo ""
fi

echo "--- Services with existing CLAUDE.md (skip if present) ---"
for service in "${EXISTING_CLAUDE_MD[@]}"; do
    link_service "$service"
done

echo ""
echo "--- Services needing CLAUDE.md ---"
for service in "${NEW_CLAUDE_MD[@]}"; do
    link_service "$service"
done

echo ""
echo "Done."
