#!/bin/bash

# Local Development Setup Script for Developer Onboarding MCP Server
# This script sets up everything needed to test the system locally

set -e

echo "🚀 Setting up Developer Onboarding MCP Server for Local Testing"
echo "=============================================================="

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

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check prerequisites
check_prerequisites() {
    print_status "Checking prerequisites..."
    
    # Check Node.js
    if ! command -v node &> /dev/null; then
        print_error "Node.js is not installed. Please install Node.js 18 or higher."
        exit 1
    fi
    
    NODE_VERSION=$(node --version | cut -d'v' -f2 | cut -d'.' -f1)
    if [ "$NODE_VERSION" -lt 18 ]; then
        print_error "Node.js version $NODE_VERSION is too old. Please install Node.js 18 or higher."
        exit 1
    fi
    
    print_success "Node.js $(node --version) detected"
    
    # Check npm
    if ! command -v npm &> /dev/null; then
        print_error "npm is not installed. Please install npm."
        exit 1
    fi
    
    print_success "npm $(npm --version) detected"
    
    # Check if we're in the right directory
    if [ ! -f "package.json" ]; then
        print_error "package.json not found. Please run this script from the project root directory."
        exit 1
    fi
    
    print_success "Project directory verified"
}

# Install dependencies
install_dependencies() {
    print_status "Installing dependencies..."
    
    if npm install; then
        print_success "Dependencies installed successfully"
    else
        print_error "Failed to install dependencies"
        exit 1
    fi
}

# Build the project
build_project() {
    print_status "Building the project..."
    
    if npm run build; then
        print_success "Project built successfully"
    else
        print_error "Build failed"
        exit 1
    fi
}

# Setup local database
setup_database() {
    print_status "Setting up local database..."
    
    # Create data directory
    mkdir -p data
    mkdir -p logs
    
    print_success "Database directories created"
}

# Create local configuration
create_local_config() {
    print_status "Creating local configuration..."
    
    # Create .env file for local development
    cat > .env << EOF
NODE_ENV=development
LOG_LEVEL=debug
DATABASE_PATH=./data/onboarding-local.db
PORT=3000
EOF

    print_success "Local configuration created (.env file)"
}

# Create Cursor MCP configuration
create_cursor_config() {
    print_status "Creating Cursor MCP configuration..."
    
    # Get the absolute path to the built server
    CURRENT_DIR=$(pwd)
    SERVER_PATH="$CURRENT_DIR/dist/index.js"
    
    # Determine Cursor config path based on OS
    if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "win32" ]]; then
        CURSOR_CONFIG_DIR="$APPDATA/Cursor/User"
        CURSOR_CONFIG_PATH="$CURSOR_CONFIG_DIR/mcp_servers.json"
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        CURSOR_CONFIG_DIR="$HOME/Library/Application Support/Cursor/User"
        CURSOR_CONFIG_PATH="$CURSOR_CONFIG_DIR/mcp_servers.json"
    else
        CURSOR_CONFIG_DIR="$HOME/.config/Cursor/User"
        CURSOR_CONFIG_PATH="$CURSOR_CONFIG_DIR/mcp_servers.json"
    fi
    
    # Create Cursor config directory if it doesn't exist
    mkdir -p "$CURSOR_CONFIG_DIR"
    
    # Create or update MCP servers configuration
    if [ -f "$CURSOR_CONFIG_PATH" ]; then
        print_warning "Cursor MCP configuration already exists. Creating backup..."
        cp "$CURSOR_CONFIG_PATH" "$CURSOR_CONFIG_PATH.backup.$(date +%s)"
    fi
    
    # Create the MCP configuration
    cat > "$CURSOR_CONFIG_PATH" << EOF
{
  "servers": {
    "developer-onboarding-local": {
      "command": "node",
      "args": ["$SERVER_PATH"],
      "env": {
        "NODE_ENV": "development",
        "LOG_LEVEL": "debug",
        "DATABASE_PATH": "$CURRENT_DIR/data/onboarding-local.db"
      }
    }
  }
}
EOF

    print_success "Cursor MCP configuration created at: $CURSOR_CONFIG_PATH"
    print_warning "Please restart Cursor IDE to load the new MCP server configuration"
}

# Create test data
create_test_data() {
    print_status "Creating test data..."
    
    # Create a simple test script
    cat > scripts/create-test-data.js << 'EOF'
const fs = require('fs');
const path = require('path');

// Create sample project structure for testing
const testProjectPath = path.join(__dirname, '..', 'test-project');

// Create test project directories
const directories = [
    'src/components',
    'src/pages',
    'src/utils',
    'src/api',
    'tests/unit',
    'tests/integration',
    'docs',
    'scripts',
    'public'
];

directories.forEach(dir => {
    const fullPath = path.join(testProjectPath, dir);
    fs.mkdirSync(fullPath, { recursive: true });
});

// Create sample files
const files = {
    'package.json': JSON.stringify({
        name: 'test-project',
        version: '1.0.0',
        description: 'Sample project for testing Developer Onboarding MCP',
        main: 'src/index.js',
        scripts: {
            start: 'node src/index.js',
            test: 'jest',
            dev: 'nodemon src/index.js'
        },
        dependencies: {
            express: '^4.18.0',
            react: '^18.0.0',
            'react-dom': '^18.0.0'
        },
        devDependencies: {
            jest: '^29.0.0',
            nodemon: '^2.0.0',
            '@testing-library/react': '^13.0.0'
        }
    }, null, 2),
    'README.md': `# Test Project

This is a sample project for testing the Developer Onboarding MCP Server.

## Getting Started

1. Install dependencies: \`npm install\`
2. Start development server: \`npm run dev\`
3. Run tests: \`npm test\`

## Tech Stack

- **Frontend**: React 18
- **Backend**: Express.js
- **Testing**: Jest + React Testing Library
- **Development**: Nodemon

## Project Structure

- \`src/\` - Source code
- \`tests/\` - Test files
- \`docs/\` - Documentation
- \`public/\` - Static assets
`,
    'src/index.js': `const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

app.get('/', (req, res) => {
    res.json({ message: 'Hello from Test Project!' });
});

app.listen(port, () => {
    console.log(\`Server running on port \${port}\`);
});`,
    'src/components/Header.jsx': `import React from 'react';

const Header = ({ title }) => {
    return (
        <header>
            <h1>{title}</h1>
        </header>
    );
};

export default Header;`,
    'tests/unit/header.test.js': `import { render, screen } from '@testing-library/react';
import Header from '../../src/components/Header';

test('renders header with title', () => {
    render(<Header title="Test Title" />);
    const headerElement = screen.getByText(/Test Title/i);
    expect(headerElement).toBeInTheDocument();
});`,
    '.gitignore': `node_modules/
.env
dist/
build/
*.log
.DS_Store`,
    'docs/setup.md': `# Setup Guide

## Development Environment

1. Install Node.js 18+
2. Clone the repository
3. Run \`npm install\`
4. Copy \`.env.example\` to \`.env\`
5. Start with \`npm run dev\`

## Testing

Run the test suite with:
\`\`\`bash
npm test
\`\`\`
`
};

Object.entries(files).forEach(([filename, content]) => {
    const filePath = path.join(testProjectPath, filename);
    fs.writeFileSync(filePath, content);
});

console.log('✅ Test project created at:', testProjectPath);
console.log('📁 Project structure:');
console.log('   - Frontend: React components');
console.log('   - Backend: Express.js server');
console.log('   - Testing: Jest test files');
console.log('   - Documentation: README and setup guide');
EOF

    # Run the test data creation script
    node scripts/create-test-data.js
    print_success "Test project created for onboarding testing"
}

# Create testing instructions
create_testing_guide() {
    print_status "Creating testing guide..."
    
    cat > TESTING.md << 'EOF'
# Local Testing Guide

## 🚀 Quick Start

Your Developer Onboarding MCP Server is now set up for local testing!

## 📋 Testing Steps

### 1. Start the MCP Server
```bash
npm start
```

The server will start and create a local SQLite database in the `data/` directory.

### 2. Test in Cursor IDE

1. **Restart Cursor IDE** to load the new MCP configuration
2. **Open the test project** created at `./test-project/`
3. **Open Command Palette** (`Ctrl+Shift+P` or `Cmd+Shift+P`)
4. **Look for MCP tools** - you should see the onboarding tools available

### 3. Test the Onboarding Flow

#### Step 1: Identify Your Role
```
Use the "identify-user-role" tool with:
- action: "present_roles"
```

#### Step 2: Select Your Role
```
Use the "identify-user-role" tool with:
- action: "select_role"
- projectPath: "./test-project"
- userName: "Your Name"
- role: "frontend" (or your preferred role)
- experienceLevel: "intermediate"
```

#### Step 3: Analyze the Project
```
Use the "analyze-project" tool with:
- projectPath: "./test-project"
- includeFileContent: false
```

#### Step 4: Start Onboarding Session
```
Use the "track-progress" tool with:
- action: "start_session"
- userName: "Your Name"
- projectPath: "./test-project"
- role: "frontend"
```

#### Step 5: Get Your Progress
```
Use the "track-progress" tool with:
- action: "get_progress"
- userName: "Your Name"
- projectPath: "./test-project"
- role: "frontend"
```

### 4. Test Other Features

#### Generate Documentation
```
Use the "generate-documentation" tool with:
- projectPath: "./test-project"
- role: "frontend"
- documentType: "overview"
- experienceLevel: "intermediate"
```

#### Manage User Profile
```
Use the "manage-user" tool with:
- action: "get_profile"
- userName: "Your Name"
```

#### Analyze Code
```
Use the "analyze-code" tool with:
- projectPath: "./test-project"
- role: "frontend"
- analysisType: "patterns"
```

## 🔍 Testing Resources

### Test Resources Available
- `project://` - Access project analysis data
- `onboarding://` - View onboarding progress
- `user://` - Access user profiles
- `knowledge://` - Browse documentation and guides

### Example Resource Queries
After setting up your profile and project, try accessing:
- `project://{projectId}/overview`
- `onboarding://overview`
- `user://{userId}/profile`
- `knowledge://guides/getting-started`

## 📊 What to Test

### ✅ Core Functionality
- [ ] User role identification works
- [ ] Project analysis completes successfully
- [ ] Progress tracking saves and retrieves data
- [ ] Documentation generation creates relevant content
- [ ] User management stores profile information

### ✅ Data Persistence
- [ ] User data persists between sessions
- [ ] Project analysis is cached and reused
- [ ] Progress milestones are saved correctly
- [ ] Session data maintains continuity

### ✅ Error Handling
- [ ] Invalid project paths are handled gracefully
- [ ] Missing user information prompts for input
- [ ] Network/database errors show helpful messages
- [ ] Tool validation prevents invalid operations

## 🐛 Troubleshooting

### MCP Server Not Connecting
1. Check if the server is running (`npm start`)
2. Verify Cursor configuration path is correct
3. Restart Cursor IDE completely
4. Check server logs in `logs/` directory

### Database Issues
1. Check if `data/` directory exists and is writable
2. Delete `data/onboarding-local.db` to reset database
3. Check server logs for database errors

### Tool Not Working
1. Verify tool parameters match the schema
2. Check for typos in tool names
3. Review server logs for detailed error messages
4. Ensure user profile is set up correctly

## 📝 Expected Results

After successful testing, you should see:
- ✅ User profile created with role and preferences
- ✅ Project analysis completed with tech stack detection
- ✅ Onboarding milestones initialized for your role
- ✅ Progress tracking working across sessions
- ✅ Documentation generated based on your role
- ✅ Resources accessible through Cursor

## 🎯 Next Steps

Once local testing is successful:
1. Review the generated documentation and progress
2. Test different roles and experience levels
3. Try the system with different project structures
4. Explore the enterprise deployment options

Happy testing! 🚀
EOF

    print_success "Testing guide created (TESTING.md)"
}

# Main execution
main() {
    echo
    print_status "Starting local setup..."
    echo
    
    check_prerequisites
    echo
    
    install_dependencies
    echo
    
    build_project
    echo
    
    setup_database
    echo
    
    create_local_config
    echo
    
    create_cursor_config
    echo
    
    create_test_data
    echo
    
    create_testing_guide
    echo
    
    print_success "🎉 Local setup completed successfully!"
    echo
    echo "📋 Next Steps:"
    echo "1. Restart Cursor IDE to load the MCP configuration"
    echo "2. Run 'npm start' to start the MCP server"
    echo "3. Open the test project in Cursor: ./test-project/"
    echo "4. Follow the testing guide in TESTING.md"
    echo
    echo "🚀 Happy testing!"
}

# Run main function
main
