#!/bin/bash
# sync-prompts.sh — Update prompts from the Piebald-AI repo
#
# Usage: ./scripts/sync-prompts.sh
#
# Pulls latest Claude system prompts and checks for changes.
# Does NOT overwrite local adaptations — reports differences.

set -e

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

SCRIPT_PATH="$(readlink -f "${BASH_SOURCE[0]}")"
SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
CLAUDE_PROMPTS_DIR="$HOME/.qwen/claude-prompts/system-prompts"

echo -e "${BLUE}╔══════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║     Claude Style — Sync Prompts         ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════╝${NC}"
echo ""

# Check if Claude prompts are available
if [ ! -d "$CLAUDE_PROMPTS_DIR" ]; then
    echo -e "${YELLOW}Claude prompts not found. Cloning Piebald-AI repo...${NC}"
    mkdir -p "$(dirname "$CLAUDE_PROMPTS_DIR")"
    git clone https://github.com/Piebald-AI/claude-code-system-prompts.git "$HOME/.qwen/claude-prompts" 2>/dev/null || {
        echo -e "${RED}✗ Failed to clone. Clone manually:${NC}"
        echo "  git clone https://github.com/Piebald-AI/claude-code-system-prompts.git ~/.qwen/claude-prompts"
        exit 1
    }
else
    echo -e "${YELLOW}Updating Claude prompts repo...${NC}"
    pushd "$HOME/.qwen/claude-prompts" > /dev/null
    (git pull 2>/dev/null || echo -e "${YELLOW}⚠ Could not pull (check git)${NC}")
    popd > /dev/null || true
fi

# Compare and report
echo ""
echo -e "${YELLOW}Checking for changes in core prompts...${NC}"

CHANGES=0
for local_file in "$PROJECT_DIR/prompts/core"/*.md; do
    if [ -f "$local_file" ]; then
        BASENAME=$(basename "$local_file")
        # Find corresponding Claude file (by grep of source URL)
        CLAUDE_FILE=""
        SOURCE_URL=$(grep -o 'https://github.com/Piebald-AI/claude-code-system-prompts.*' "$local_file" | head -1 | sed 's/>.*$//')
        if [ -n "$SOURCE_URL" ]; then
            # Extract filename from URL path
            CLAUDE_BASENAME=$(echo "$SOURCE_URL" | sed 's|.*/system-prompts/||')
            if [ -f "$CLAUDE_PROMPTS_DIR/$CLAUDE_BASENAME" ]; then
                CLAUDE_FILE="$CLAUDE_PROMPTS_DIR/$CLAUDE_BASENAME"
            fi
        fi

        if [ -n "$CLAUDE_FILE" ] && [ -f "$CLAUDE_FILE" ]; then
            # Compare content (ignoring comments/headers)
            if ! diff -q <(grep -v '^>' "$local_file" | grep -v '^<!--' | grep -v '^-->') <(grep -v '^<!--' "$CLAUDE_FILE" | grep -v '^-->') &>/dev/null; then
                echo -e "${YELLOW}⚠ $BASENAME differs from source${NC}"
                CHANGES=$((CHANGES + 1))
            fi
        fi
    fi
done

if [ $CHANGES -eq 0 ]; then
    echo -e "${GREEN}✓ All local prompts are up to date${NC}"
else
    echo ""
    echo -e "${YELLOW}$CHANGES prompt(s) differ from source.${NC}"
    echo "  Review and update them manually in prompts/core/"
fi
