#!/bin/bash

# Demo script for RAG integration with OpenRouter TUI
# This script demonstrates the key features and usage patterns

set -e

echo "🚀 OpenRouter RAG + TUI Demo"
echo "================================"

# Check if binary exists
if [ ! -f "./openrouter" ]; then
    echo "📦 Building OpenRouter TUI..."
    go build -o openrouter
    echo "✅ Build complete!"
fi

# Check API key
if [ -z "$OPENROUTER_API_KEY" ]; then
    echo "⚠️  Warning: OPENROUTER_API_KEY not set"
    echo "   Set your API key: export OPENROUTER_API_KEY='your-key-here'"
    echo "   RAG features will be unavailable without it"
    echo ""
fi

# Create demo files for indexing
echo "📁 Creating demo files for RAG indexing..."
mkdir -p demo_files

cat > demo_files/main.go << 'EOF'
package main

import (
    "fmt"
    "log"
    "net/http"
)

// User represents a user in the system
type User struct {
    ID       int    `json:"id"`
    Name     string `json:"name"`
    Email    string `json:"email"`
}

// UserService handles user operations
type UserService struct {
    users []User
}

// CreateUser adds a new user to the system
func (s *UserService) CreateUser(name, email string) (*User, error) {
    if name == "" || email == "" {
        return nil, fmt.Errorf("name and email are required")
    }
    
    user := User{
        ID:    len(s.users) + 1,
        Name:  name,
        Email: email,
    }
    
    s.users = append(s.users, user)
    return &user, nil
}

// GetUser retrieves a user by ID
func (s *UserService) GetUser(id int) (*User, error) {
    for _, user := range s.users {
        if user.ID == id {
            return &user, nil
        }
    }
    return nil, fmt.Errorf("user not found")
}

// StartServer starts the HTTP server
func StartServer() {
    service := &UserService{}
    
    http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
        // Handle user operations
        fmt.Fprintf(w, "User API endpoint")
    })
    
    log.Println("Server starting on :8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func main() {
    fmt.Println("Starting user management system...")
    StartServer()
}
EOF

cat > demo_files/database.go << 'EOF'
package main

import (
    "database/sql"
    "fmt"
    _ "github.com/lib/pq"
)

// Database handles database connections
type Database struct {
    conn *sql.DB
}

// Connect establishes a database connection
func (db *Database) Connect(dsn string) error {
    conn, err := sql.Open("postgres", dsn)
    if err != nil {
        return fmt.Errorf("failed to connect to database: %w", err)
    }
    
    if err := conn.Ping(); err != nil {
        return fmt.Errorf("failed to ping database: %w", err)
    }
    
    db.conn = conn
    return nil
}

// CreateUserTable creates the users table
func (db *Database) CreateUserTable() error {
    query := `
        CREATE TABLE IF NOT EXISTS users (
            id SERIAL PRIMARY KEY,
            name VARCHAR(255) NOT NULL,
            email VARCHAR(255) UNIQUE NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    `
    
    _, err := db.conn.Exec(query)
    if err != nil {
        return fmt.Errorf("failed to create users table: %w", err)
    }
    
    return nil
}

// InsertUser inserts a new user into the database
func (db *Database) InsertUser(name, email string) error {
    query := "INSERT INTO users (name, email) VALUES ($1, $2)"
    _, err := db.conn.Exec(query, name, email)
    if err != nil {
        return fmt.Errorf("failed to insert user: %w", err)
    }
    
    return nil
}
EOF

cat > demo_files/README.md << 'EOF'
# User Management System

This is a demo user management system built in Go.

## Features

- User creation and retrieval
- HTTP API endpoints
- Database integration with PostgreSQL
- Error handling and validation

## API Endpoints

### Create User
```
POST /users
{
    "name": "John Doe",
    "email": "john@example.com"
}
```

### Get User
```
GET /users/{id}
```

## Database Schema

The system uses a PostgreSQL database with the following schema:

```sql
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

## Error Handling

The application implements comprehensive error handling:
- Input validation for required fields
- Database connection error handling
- HTTP error responses
- Logging for debugging

## Getting Started

1. Set up PostgreSQL database
2. Configure connection string
3. Run the application
4. Test the API endpoints
EOF

cat > demo_files/config.yaml << 'EOF'
# Application Configuration
server:
  host: "localhost"
  port: 8080
  timeout: 30s

database:
  host: "localhost"
  port: 5432
  name: "userdb"
  user: "postgres"
  password: "password"
  ssl_mode: "disable"
  max_connections: 10

logging:
  level: "info"
  format: "json"
  output: "stdout"

features:
  enable_metrics: true
  enable_health_check: true
  enable_swagger: true
EOF

echo "✅ Demo files created in demo_files/"
echo ""

echo "🎯 RAG + TUI Integration Features:"
echo "=================================="
echo ""
echo "🔧 Key Features:"
echo "  • Semantic search across your codebase"
echo "  • Interactive document management"
echo "  • AI agent with RAG tools"
echo "  • Real-time CodeBase updates"
echo "  • Multi-format file support (25+ types)"
echo ""
echo "⌨️  Keyboard Shortcuts:"
echo "  • Ctrl+R  - RAG CodeBase Management"
echo "  • Ctrl+K  - Commands (includes RAG commands)"
echo "  • Ctrl+H  - Help and shortcuts"
echo ""
echo "📚 RAG Page Controls (Ctrl+R):"
echo "  • s - Search documents"
echo "  • i - Index files"
echo "  • c - Clear CodeBase"
echo "  • t - Show statistics"
echo "  • r - Refresh"
echo "  • Esc - Return to main chat"
echo ""
echo "🤖 Available RAG Commands (Ctrl+K):"
echo "  • RAG Search - Open CodeBase browser"
echo "  • Index Current Directory - Auto-index project files"
echo "  • Clear CodeBase - Reset all indexed data"
echo "  • RAG Statistics - View system stats"
echo ""

echo "🚀 Demo Workflow:"
echo "================"
echo ""
echo "1. 📖 Start the TUI:"
echo "   ./openrouter"
echo ""
echo "2. 🔑 First, make sure your API key is set:"
echo "   export OPENROUTER_API_KEY='your-key'"
echo "   (RAG automatically uses the same API key as the TUI)"
echo ""
echo "3. 📁 Index the demo files:"
echo "   • Press Ctrl+K"
echo "   • Select 'Index Current Directory'"
echo "   • Or press Ctrl+R, then 'i', enter 'demo_files/*.go,demo_files/*.md'"
echo ""
echo "4. 🔍 Test RAG search:"
echo "   • Press Ctrl+R"
echo "   • Press 's'"
echo "   • Try queries like:"
echo "     - 'user management functions'"
echo "     - 'database connection code'"
echo "     - 'error handling patterns'"
echo "     - 'HTTP server setup'"
echo ""
echo "5. 💬 Chat with AI about your code:"
echo "   • Press Esc to return to main chat (from RAG page)"
echo "   • Ask questions like:"
echo "     - 'What functions are defined in my Go files?'"
echo "     - 'Show me the database schema'"
echo "     - 'How is error handling implemented?'"
echo "     - 'Explain the user creation process'"
echo ""
echo "6. 📊 Check statistics:"
echo "   • Press Ctrl+R, then 't'"
echo "   • Or ask AI: 'Show me RAG statistics'"
echo ""

echo "🎨 Advanced Features to Try:"
echo "============================"
echo ""
echo "🔀 Hybrid Search:"
echo "   Ask AI: 'Use hybrid search to find database AND user code'"
echo ""
echo "🔗 Similarity Search:"
echo "   Ask AI: 'Find code similar to the CreateUser function'"
echo ""
echo "📈 System Analysis:"
echo "   Ask AI: 'Analyze my RAG CodeBase coverage'"
echo ""
echo "🎯 Filtered Search:"
echo "   Ask AI: 'Search for error handling only in Go files'"
echo ""

echo "💡 Pro Tips:"
echo "============"
echo ""
echo "• Use specific, technical queries for better results"
echo "• The AI automatically uses RAG tools when discussing code"
echo "• Check logs (Ctrl+L) if you encounter issues"
echo "• Clear and re-index if search quality degrades"
echo "• Monitor memory usage with statistics"
echo ""

echo "🚀 Ready to start! Run:"
echo "   ./openrouter"
echo ""
echo "Then follow the demo workflow above."
echo "Press Ctrl+C to exit the TUI when done."
echo ""
echo "Happy coding with RAG-enhanced AI assistance! 🎉" 