# Unison - Unified Tech Stack Recommendation Service

Unison is a production-ready Node.js service that combines recommendations from both the `tech-stack-selector` and `template-manager` services, then uses Claude AI to generate a single, optimized tech stack recommendation that balances cost, domain requirements, and template-feature compatibility.

## 🚀 Features

- **Unified Recommendations**: Combines recommendations from both tech-stack-selector and template-manager services
- **Claude AI Integration**: Uses Claude AI to analyze and optimize recommendations
- **Robust Error Handling**: Graceful fallbacks when services are unavailable
- **Schema Validation**: Strict JSON schema validation using Ajv
- **Production Ready**: Comprehensive logging, health checks, and monitoring
- **Rate Limiting**: Built-in rate limiting to prevent abuse
- **Docker Support**: Fully containerized with Docker and Docker Compose

## 📋 Prerequisites

- Node.js 18+ 
- Docker and Docker Compose
- Access to tech-stack-selector service (port 8002)
- Access to template-manager service (ports 8009, 8013)
- Claude API key (optional, service works with fallbacks)

## 🏗️ Architecture

```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   Client App    │───▶│   Unison Service │───▶│ Claude AI API   │
└─────────────────┘    │   (Port 8010)    │    └─────────────────┘
                       └─────────┬────────┘
                                 │
                    ┌────────────┼────────────┐
                    │            │            │
            ┌───────▼──────┐ ┌───▼────┐ ┌────▼──────┐
            │ Tech Stack   │ │Template│ │Template   │
            │ Selector     │ │Manager │ │Manager AI │
            │ (Port 8002)  │ │(8009)  │ │(Port 8013)│
            └──────────────┘ └────────┘ └───────────┘
```

## 🛠️ Installation

### Using Docker Compose (Recommended)

The Unison service is already integrated into the main `docker-compose.yml` file. To start it:

```bash
# Start all services including Unison
docker-compose up -d unison

# Or start the entire stack
docker-compose up -d
```

### Manual Installation

1. **Clone and navigate to the service directory:**
   ```bash
   cd services/unison
   ```

2. **Install dependencies:**
   ```bash
   npm install
   ```

3. **Set up environment variables:**
   ```bash
   # The config.env file is already configured with all necessary variables
   # You can modify it if needed for your specific setup
   cp config.env .env  # Optional: create a .env file from config.env
   ```

4. **Start the service:**
   ```bash
   npm start
   # Or for development
   npm run dev
   ```

## ⚙️ Configuration

### Environment Variables

The service uses a `config.env` file for environment variables. This file is already configured with all necessary variables for the Unison service and integrates with your existing infrastructure.

**Key Configuration Sections:**
- **Service Configuration**: Port, host, environment settings
- **External Service URLs**: Tech stack selector and template manager endpoints
- **Claude AI Configuration**: API key (model and token settings use defaults)
- **Database Configuration**: PostgreSQL, Neo4j, Redis, MongoDB settings
- **Security & Authentication**: JWT secrets and API keys
- **Email Configuration**: SMTP settings for notifications
- **CORS Configuration**: Cross-origin resource sharing settings

| Variable | Default | Description |
|----------|---------|-------------|
| `NODE_ENV` | `production` | Environment mode |
| `PORT` | `8010` | Service port |
| `HOST` | `0.0.0.0` | Service host |
| `TECH_STACK_SELECTOR_URL` | `http://pipeline_tech_stack_selector:8002` | Tech stack selector service URL |
| `TEMPLATE_MANAGER_URL` | `http://pipeline_template_manager:8009` | Template manager service URL |
| `TEMPLATE_MANAGER_AI_URL` | `http://pipeline_template_manager:8013` | Template manager AI service URL |
| `CLAUDE_API_KEY` | `${CLAUDE_API_KEY}` | Claude API key (from environment) |
| `CLAUDE_MODEL` | `claude-3-sonnet-20240229` | Claude model to use |
| `CLAUDE_MAX_TOKENS` | `4000` | Maximum tokens for Claude |
| `RATE_LIMIT_WINDOW_MS` | `900000` | Rate limit window (15 minutes) |
| `RATE_LIMIT_MAX_REQUESTS` | `100` | Max requests per window |
| `LOG_LEVEL` | `info` | Logging level |
| `REQUEST_TIMEOUT` | `30000` | Request timeout in ms |
| `HEALTH_CHECK_TIMEOUT` | `5000` | Health check timeout in ms |

## 📡 API Endpoints

### Base URL
```
http://localhost:8010
```

### Endpoints

#### 1. **POST** `/api/recommendations/unified`
Get unified tech stack recommendation combining both services.

**Request Body:**
```json
{
  "domain": "web development",
  "budget": 500.0,
  "preferredTechnologies": ["React", "Node.js", "PostgreSQL"],
  "templateId": "uuid-string",
  "includeSimilar": true,
  "includeKeywords": true,
  "forceRefresh": false
}
```

**Response:**
```json
{
  "success": true,
  "data": {
    "stack_name": "Game Development Stack",
    "monthly_cost": 199,
    "setup_cost": 1200,
    "team_size": "3-5",
    "development_time": 5,
    "satisfaction": 92,
    "success_rate": 85,
    "frontend": "Unity",
    "backend": "Node.js",
    "database": "MongoDB",
    "cloud": "AWS GameLift",
    "testing": "Unity Test Framework",
    "mobile": "Unity Mobile",
    "devops": "Jenkins",
    "ai_ml": "ML.NET",
    "recommended_tool": "Discord",
    "recommendation_score": 94.5,
    "message": "AI recommendations retrieved successfully"
  },
  "source": "unified",
  "message": "Unified recommendation generated successfully",
  "processingTime": 1250,
  "services": {
    "techStackSelector": "available",
    "templateManager": "available",
    "claudeAI": "available"
  },
  "claudeModel": "claude-3-sonnet-20240229"
}
```

#### 2. **GET** `/api/recommendations/tech-stack`
Get recommendations from tech-stack-selector only.

**Query Parameters:**
- `domain` (optional): Domain for recommendations
- `budget` (optional): Budget constraint
- `preferredTechnologies` (optional): Comma-separated list of preferred technologies

#### 3. **GET** `/api/recommendations/template/:templateId`
Get recommendations from template-manager only.

**Query Parameters:**
- `force_refresh` (optional): Force refresh recommendations

#### 4. **GET** `/api/recommendations/schemas`
Get available validation schemas.

#### 5. **GET** `/health`
Health check endpoint.

#### 6. **GET** `/`
Service information and available endpoints.

## 🔧 Usage Examples

### Basic Unified Recommendation

```bash
curl -X POST http://localhost:8010/api/recommendations/unified \
  -H "Content-Type: application/json" \
  -d '{
    "domain": "e-commerce",
    "budget": 1000.0,
    "preferredTechnologies": ["Vue.js", "Django", "Redis"]
  }'
```

### With Template ID

```bash
curl -X POST http://localhost:8010/api/recommendations/unified \
  -H "Content-Type: application/json" \
  -d '{
    "domain": "startup",
    "budget": 100.0,
    "templateId": "123e4567-e89b-12d3-a456-426614174000",
    "includeSimilar": true,
    "forceRefresh": true
  }'
```

### Tech Stack Only

```bash
curl "http://localhost:8010/api/recommendations/tech-stack?domain=web%20development&budget=500"
```

### Template Only

```bash
curl "http://localhost:8010/api/recommendations/template/123e4567-e89b-12d3-a456-426614174000?force_refresh=true"
```

## 🏥 Health Monitoring

### Health Check
```bash
curl http://localhost:8010/health
```

### Detailed Health Check
```bash
curl http://localhost:8010/health/detailed
```

## 📊 Response Schema

The unified recommendation follows a strict JSON schema:

```json
{
  "stack_name": "string (descriptive name)",
  "monthly_cost": "number (0-10000)",
  "setup_cost": "number (0-50000)",
  "team_size": "string (e.g., '1-2', '3-5')",
  "development_time": "number (1-52 weeks)",
  "satisfaction": "number (0-100)",
  "success_rate": "number (0-100)",
  "frontend": "string (frontend technology)",
  "backend": "string (backend technology)",
  "database": "string (database technology)",
  "cloud": "string (cloud platform)",
  "testing": "string (testing framework)",
  "mobile": "string (mobile technology)",
  "devops": "string (devops tool)",
  "ai_ml": "string (AI/ML technology)",
  "recommended_tool": "string (primary tool)",
  "recommendation_score": "number (0-100)",
  "message": "string (explanation)"
}
```

## 🔄 Service Dependencies

Unison depends on the following services:

1. **tech-stack-selector** (port 8002)
   - Provides budget and domain-based recommendations
   - Must be healthy for full functionality

2. **template-manager** (ports 8009, 8013)
   - Provides template-based recommendations
   - AI service on port 8013 for Claude integration
   - Must be healthy for full functionality

3. **Claude AI** (external)
   - Optional but recommended for unified recommendations
   - Falls back to tech-stack-selector if unavailable

## 🚨 Error Handling

The service includes comprehensive error handling:

- **Service Unavailable**: Falls back to available services
- **Invalid Requests**: Returns detailed validation errors
- **Claude AI Errors**: Falls back to tech-stack-selector
- **Schema Validation**: Ensures response format compliance
- **Rate Limiting**: Prevents abuse with configurable limits

## 📝 Logging

Logs are written to:
- Console (development)
- `logs/combined.log` (all logs)
- `logs/error.log` (error logs only)

Log levels: `error`, `warn`, `info`, `debug`

## 🧪 Testing

```bash
# Run tests
npm test

# Run with coverage
npm run test:coverage

# Lint code
npm run lint
```

## 🐳 Docker

### Build Image
```bash
docker build -t unison .
```

### Run Container
```bash
docker run -p 8010:8010 \
  -e CLAUDE_API_KEY=your_key_here \
  -e TECH_STACK_SELECTOR_URL=http://tech-stack-selector:8002 \
  -e TEMPLATE_MANAGER_URL=http://template-manager:8009 \
  unison
```

## 🔧 Development

### Project Structure
```
services/unison/
├── src/
│   ├── app.js                 # Main application
│   ├── middleware/            # Express middleware
│   ├── routes/               # API routes
│   ├── services/             # External service integrations
│   └── utils/                # Utility functions
├── logs/                     # Log files
├── Dockerfile               # Docker configuration
├── package.json             # Dependencies
├── start.sh                 # Startup script
└── README.md               # This file
```

### Adding New Features

1. **New API Endpoints**: Add to `src/routes/`
2. **External Services**: Add to `src/services/`
3. **Middleware**: Add to `src/middleware/`
4. **Validation**: Update schemas in `src/utils/schemaValidator.js`

## 📈 Monitoring

### Metrics to Monitor
- Response times
- Error rates
- Service availability
- Claude AI usage
- Rate limit hits

### Health Indicators
- All external services healthy
- Claude AI available
- Response time < 5 seconds
- Error rate < 1%

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## 📄 License

MIT License - see LICENSE file for details.

## 🆘 Support

For issues and questions:
1. Check the logs in `logs/` directory
2. Verify external services are running
3. Check environment variables
4. Review the health endpoint

## 🔄 Changelog

### v1.0.0
- Initial release
- Unified recommendation service
- Claude AI integration
- Comprehensive error handling
- Docker support
- Production-ready logging and monitoring
