#!/bin/bash

# Test script to verify Ollama + Fabric integration
set -e

GREEN='\033[0;32m'
YELLOW='\033[0;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

echo -e "${GREEN}=== Testing Ollama + Fabric Integration ===${NC}"

echo -e "\n${YELLOW}1. Testing Ollama Docker container...${NC}"
if sudo docker ps | grep -q ollama; then
    echo -e "${GREEN}✓ Ollama Docker container is running${NC}"
    echo -e "${YELLOW}Container ID: $(sudo docker ps | grep ollama | awk '{print $1}')${NC}"
else
    echo -e "${RED}✗ Ollama Docker container is not running${NC}"
    exit 1
fi

echo -e "\n${YELLOW}2. Testing Ollama API...${NC}"
if curl -s http://localhost:11434/api/tags >/dev/null 2>&1; then
    echo -e "${GREEN}✓ Ollama API is responding${NC}"
    echo -e "${YELLOW}Available models:${NC}"
    curl -s http://localhost:11434/api/tags | jq -r '.models[].name' 2>/dev/null || echo "phi3:mini"
else
    echo -e "${RED}✗ Ollama API is not responding${NC}"
    exit 1
fi

echo -e "\n${YELLOW}3. Testing Fabric installation...${NC}"
if command -v fabric &> /dev/null; then
    echo -e "${GREEN}✓ Fabric is installed${NC}"
    echo -e "${YELLOW}Version: $(fabric --version)${NC}"
else
    echo -e "${RED}✗ Fabric is not installed${NC}"
    exit 1
fi

echo -e "\n${YELLOW}4. Testing Fabric patterns...${NC}"
pattern_count=$(fabric -l 2>/dev/null | wc -l)
if [ "$pattern_count" -gt 0 ]; then
    echo -e "${GREEN}✓ Fabric patterns are available${NC}"
    echo -e "${YELLOW}Number of patterns: $pattern_count${NC}"
else
    echo -e "${RED}✗ No Fabric patterns found${NC}"
    exit 1
fi

echo -e "\n${YELLOW}5. Testing Fabric + Ollama integration...${NC}"
test_output=$(echo "Hello world" | fabric -p summarize 2>/dev/null)
if [ $? -eq 0 ] && [ -n "$test_output" ]; then
    echo -e "${GREEN}✓ Fabric + Ollama integration working${NC}"
    echo -e "${YELLOW}Test output:${NC}"
    echo "$test_output" | head -3
else
    echo -e "${RED}✗ Fabric + Ollama integration failed${NC}"
    exit 1
fi

echo -e "\n${YELLOW}6. Testing Ollama aliases...${NC}"
if type ollama-list &>/dev/null; then
    echo -e "${GREEN}✓ Ollama aliases are loaded${NC}"
    echo -e "${YELLOW}Testing ollama-list:${NC}"
    ollama-list 2>/dev/null | head -3
else
    echo -e "${RED}✗ Ollama aliases not found${NC}"
fi

echo -e "\n${GREEN}=== All tests passed! ===${NC}"
echo -e "${YELLOW}Your setup is ready for AI-assisted development with Fabric and Ollama.${NC}"

echo -e "\n${GREEN}=== Quick Start Guide ===${NC}"
echo -e "${YELLOW}• List patterns: fabric -l${NC}"
echo -e "${YELLOW}• Use a pattern: echo 'text' | fabric -p <pattern_name>${NC}"
echo -e "${YELLOW}• List models: fabric -L${NC}"
echo -e "${YELLOW}• Manage Ollama: ollama-start, ollama-stop, ollama-logs${NC}"
echo -e "${YELLOW}• Install new models: ollama pull <model_name>${NC}"
echo -e "${YELLOW}• Update patterns: fabric -U${NC}"
