# Unified Tech Stack Service

A comprehensive service that combines recommendations from both the **Template Manager** and **Tech Stack Selector** services to provide unified, intelligent tech stack recommendations.

## 🎯 Overview

The Unified Tech Stack Service acts as a **unison** between two powerful recommendation engines:

1. **Template Manager Service** - Provides permutation and combination-based recommendations
2. **Tech Stack Selector Service** - Provides domain and budget-based recommendations

## 🚀 Features

### Core Capabilities
- **Unified Recommendations**: Combines both template-based and domain-based recommendations
- **Intelligent Analysis**: Analyzes and compares recommendations from both services
- **Hybrid Approach**: Provides the best of both worlds in a single response
- **Service Health Monitoring**: Monitors both underlying services
- **Flexible Configuration**: Configurable endpoints and preferences

### API Endpoints

#### 1. Comprehensive Recommendations (NEW - Includes Claude AI)
```http
POST /api/unified/comprehensive-recommendations
```

**Request Body:**
```json
{
  "template": {
    "id": "template-uuid",
    "title": "E-commerce Platform",
    "description": "A comprehensive e-commerce solution",
    "category": "E-commerce",
    "type": "web-app"
  },
  "features": [
    {
      "id": "feature-1",
      "name": "User Authentication",
      "description": "Secure user login and registration",
      "feature_type": "essential",
      "complexity": "medium",
      "business_rules": ["Users must verify email"],
      "technical_requirements": ["JWT tokens", "Password hashing"]
    }
  ],
  "businessContext": {
    "questions": [
      {
        "question": "What is your target audience?",
        "answer": "Small to medium businesses"
      }
    ]
  },
  "projectName": "E-commerce Platform",
  "projectType": "E-commerce",
  "templateId": "template-uuid",
  "budget": 15000,
  "domain": "ecommerce",
  "includeClaude": true,
  "includeTemplateBased": true,
  "includeDomainBased": true
}
```

**Response:**
```json
{
  "success": true,
  "data": {
    "claude": {
      "success": true,
      "data": {
        "claude_recommendations": {
          "technology_recommendations": {
            "frontend": {
              "framework": "React",
              "libraries": ["TypeScript", "Tailwind CSS"],
              "reasoning": "Modern, scalable frontend solution"
            },
            "backend": {
              "language": "Node.js",
              "framework": "Express.js",
              "libraries": ["TypeScript", "Prisma"],
              "reasoning": "JavaScript ecosystem consistency"
            }
          },
          "implementation_strategy": {...},
          "business_alignment": {...},
          "risk_assessment": {...}
        },
        "functional_requirements": {...}
      }
    },
    "templateBased": {...},
    "domainBased": {...},
    "unified": {
      "techStacks": [...],
      "technologies": [...],
      "recommendations": [...],
      "confidence": 0.9,
      "approach": "comprehensive",
      "claudeRecommendations": {...},
      "templateRecommendations": {...},
      "domainRecommendations": {...}
    },
    "analysis": {
      "claude": {
        "status": "success",
        "hasRecommendations": true,
        "hasFunctionalRequirements": true
      },
      "templateManager": {...},
      "techStackSelector": {...},
      "comparison": {
        "comprehensiveScore": 0.9,
        "recommendationQuality": "excellent"
      }
    }
  }
}
```

#### 2. Unified Recommendations (Legacy)
```http
POST /api/unified/recommendations
```

**Request Body:**
```json
{
  "templateId": "template-uuid",
  "budget": 10000,
  "domain": "finance",
  "features": ["feature1", "feature2"],
  "preferences": {
    "includePermutations": true,
    "includeCombinations": true,
    "includeDomainRecommendations": true
  }
}
```

**Response:**
```json
{
  "success": true,
  "data": {
    "templateBased": {
      "permutations": {...},
      "combinations": {...},
      "template": {...}
    },
    "domainBased": {
      "recommendations": [...],
      "confidence": 0.85
    },
    "unified": {
      "techStacks": [...],
      "technologies": [...],
      "recommendations": [...],
      "confidence": 0.9,
      "approach": "hybrid"
    },
    "analysis": {
      "templateManager": {...},
      "techStackSelector": {...},
      "comparison": {...}
    }
  }
}
```

#### 2. Template-Based Recommendations
```http
POST /api/unified/template-recommendations
```

#### 3. Domain-Based Recommendations
```http
POST /api/unified/domain-recommendations
```

#### 4. Analysis Endpoint
```http
POST /api/unified/analyze
```

#### 5. Service Status
```http
GET /api/unified/status
```

## 🔧 Architecture

### Service Components

```
┌─────────────────────────────────────────────────────────────┐
│                    Unified Tech Stack Service               │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────┐ │
│  │ Template Manager│  │ Tech Stack      │  │ Unified     │ │
│  │ Client          │  │ Selector Client │  │ Service     │ │
│  └─────────────────┘  └─────────────────┘  └─────────────┘ │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────┐ │
│  │ Template        │  │ Domain-Based    │  │ Analysis    │ │
│  │ Recommendations │  │ Recommendations │  │ Engine      │ │
│  └─────────────────┘  └─────────────────┘  └─────────────┘ │
└─────────────────────────────────────────────────────────────┘
```

### Data Flow

1. **Request Processing**: Receives unified request with template ID, budget, domain, and features
2. **Parallel Service Calls**: Calls both Template Manager and Tech Stack Selector services
3. **Data Aggregation**: Combines responses from both services
4. **Intelligent Merging**: Merges technologies and recommendations intelligently
5. **Analysis**: Performs comparative analysis between both approaches
6. **Unified Response**: Returns comprehensive unified recommendations

## 🛠️ Installation & Setup

### Prerequisites
- Node.js 18+
- Docker (optional)
- Access to Template Manager Service (port 8009)
- Access to Tech Stack Selector Service (port 8002)

### Local Development

1. **Clone and Install**
```bash
cd services/unified-tech-stack-service
npm install
```

2. **Environment Setup**
```bash
# Run the setup script
./setup-env.sh

# Or manually copy and configure
cp env.example .env
# Edit .env with your configuration
```

3. **Configure Claude AI API Key**
```bash
# Get your API key from: https://console.anthropic.com/
# Add to .env file:
CLAUDE_API_KEY=your_actual_api_key_here
```

4. **Start Service**
```bash
npm start
# or for development
npm run dev
```

5. **Test the Service**
```bash
node test-comprehensive-integration.js
```

### Docker Deployment

1. **Build Image**
```bash
docker build -t unified-tech-stack-service .
```

2. **Run Container**
```bash
docker run -p 8010:8010 \
  -e TEMPLATE_MANAGER_URL=http://host.docker.internal:8009 \
  -e TECH_STACK_SELECTOR_URL=http://host.docker.internal:8002 \
  unified-tech-stack-service
```

## 📊 Usage Examples

### Example 1: Complete Unified Recommendation

```bash
curl -X POST "http://localhost:8010/api/unified/recommendations" \
  -H "Content-Type: application/json" \
  -d '{
    "templateId": "0163731b-18e5-4d4e-86a1-aa2c05ae3140",
    "budget": 15000,
    "domain": "finance",
    "features": ["trading", "analytics", "security"],
    "preferences": {
      "includePermutations": true,
      "includeCombinations": true,
      "includeDomainRecommendations": true
    }
  }'
```

### Example 2: Template-Only Recommendations

```bash
curl -X POST "http://localhost:8010/api/unified/template-recommendations" \
  -H "Content-Type: application/json" \
  -d '{
    "templateId": "0163731b-18e5-4d4e-86a1-aa2c05ae3140",
    "recommendationType": "both"
  }'
```

### Example 3: Domain-Only Recommendations

```bash
curl -X POST "http://localhost:8010/api/unified/domain-recommendations" \
  -H "Content-Type: application/json" \
  -d '{
    "budget": 10000,
    "domain": "ecommerce",
    "features": ["payment", "inventory", "shipping"]
  }'
```

### Example 4: Service Analysis

```bash
curl -X POST "http://localhost:8010/api/unified/analyze" \
  -H "Content-Type: application/json" \
  -d '{
    "templateId": "0163731b-18e5-4d4e-86a1-aa2c05ae3140",
    "budget": 12000,
    "domain": "healthcare",
    "features": ["patient-management", "billing", "analytics"]
  }'
```

## 🔍 How It Works

### 1. Claude AI Recommendations (NEW - Intelligence Matters)
- **AI-Powered**: Uses Claude AI to analyze template, features, and business context
- **Context-Aware**: Considers business questions and answers for personalized recommendations
- **Comprehensive**: Provides detailed reasoning for each technology choice
- **Source**: Claude AI (Anthropic)
- **Use Case**: When you need intelligent, context-aware recommendations

### 2. Template-Based Recommendations (Order Matters)
- **Permutations**: `[Feature A, Feature B, Feature C]` ≠ `[Feature C, Feature A, Feature B]`
- **Combinations**: `{Feature A, Feature B, Feature C}` = `{Feature C, Feature A, Feature B}`
- **Source**: Template Manager Service
- **Use Case**: When user selects features in specific order or as unordered sets

### 3. Domain-Based Recommendations (Context Matters)
- **Budget-Aware**: Recommendations based on budget constraints
- **Domain-Specific**: Tailored for specific business domains (finance, healthcare, etc.)
- **Source**: Tech Stack Selector Service
- **Use Case**: When user has budget and domain requirements

### 4. Comprehensive Approach (Best of All Three)
- **AI + Template + Domain**: Combines all three approaches intelligently
- **Technology Merging**: Deduplicates and merges technologies from all sources
- **Confidence Scoring**: Calculates comprehensive confidence scores
- **Quality Assessment**: Analyzes recommendation quality from all services
- **Fallback Mechanisms**: Graceful degradation when services are unavailable

## 📈 Benefits

### For Developers
- **Single API**: One endpoint for all tech stack recommendations
- **Comprehensive Data**: Gets Claude AI, template-based, and domain-based insights
- **Intelligent Analysis**: Built-in comparison and analysis across all sources
- **Flexible Usage**: Can use individual services or comprehensive approach
- **AI-Powered**: Leverages Claude AI for intelligent, context-aware recommendations

### For Applications
- **Better Recommendations**: More comprehensive and accurate recommendations from multiple sources
- **Reduced Complexity**: Single service to integrate instead of multiple
- **Improved Reliability**: Fallback mechanisms if services fail
- **Enhanced Analytics**: Built-in analysis and comparison capabilities
- **Context-Aware**: Considers business context and requirements for personalized recommendations

## 🔧 Configuration

### Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `PORT` | Service port | `8010` |
| `TEMPLATE_MANAGER_URL` | Template Manager service URL | `http://localhost:8009` |
| `TECH_STACK_SELECTOR_URL` | Tech Stack Selector service URL | `http://localhost:8002` |
| `CLAUDE_API_KEY` | Claude AI API key | Required for AI recommendations |
| `ANTHROPIC_API_KEY` | Anthropic API key (alternative) | Required for AI recommendations |
| `REQUEST_TIMEOUT` | Request timeout in ms | `30000` |
| `CACHE_TTL` | Cache TTL in ms | `300000` |

### Feature Flags

- `ENABLE_TEMPLATE_RECOMMENDATIONS`: Enable template-based recommendations
- `ENABLE_DOMAIN_RECOMMENDATIONS`: Enable domain-based recommendations
- `ENABLE_CLAUDE_RECOMMENDATIONS`: Enable Claude AI recommendations
- `ENABLE_ANALYSIS`: Enable analysis features
- `ENABLE_CACHING`: Enable response caching

## 🚨 Error Handling

The service includes comprehensive error handling:

- **Service Unavailability**: Graceful degradation when one service is down
- **Timeout Handling**: Configurable timeouts for external service calls
- **Data Validation**: Input validation and sanitization
- **Fallback Mechanisms**: Fallback to available services when possible

## 📊 Monitoring

### Health Checks
- **Service Health**: `GET /health`
- **Service Status**: `GET /api/unified/status`
- **Individual Service Health**: Monitors both underlying services

### Metrics
- Request count and response times
- Service availability status
- Recommendation quality scores
- Error rates and types

## 🔮 Future Enhancements

- **Machine Learning Integration**: ML-based recommendation scoring
- **Caching Layer**: Redis-based caching for improved performance
- **Rate Limiting**: Built-in rate limiting and throttling
- **WebSocket Support**: Real-time recommendation updates
- **GraphQL API**: GraphQL endpoint for flexible data querying

## 🤝 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.

---

**The Unified Tech Stack Service provides the perfect unison between Claude AI, template-based, and domain-based tech stack recommendations, giving you the best of all worlds in a single, intelligent service.** 🚀

## 🧪 Testing

### Test Comprehensive Integration

Run the test script to verify the new comprehensive endpoint:

```bash
# Make sure the unified service is running
npm start

# In another terminal, run the test
node test-comprehensive-integration.js
```

This will test the new comprehensive endpoint that combines Claude AI, template-based, and domain-based recommendations.

## 🔧 Troubleshooting

### Claude AI Not Working

**Problem**: Claude AI recommendations are not working
**Solution**: 
1. Check if API key is configured: `grep CLAUDE_API_KEY .env`
2. Get API key from: https://console.anthropic.com/
3. Add to .env: `CLAUDE_API_KEY=your_key_here`
4. Restart service: `npm start`

### Service Not Starting

**Problem**: Service fails to start
**Solution**:
1. Check if port 8013 is available: `lsof -i :8013`
2. Install dependencies: `npm install`
3. Check environment: `./setup-env.sh`

### Template/Domain Services Not Available

**Problem**: Template-based or domain-based recommendations fail
**Solution**:
1. Ensure Template Manager is running on port 8009
2. Ensure Tech Stack Selector is running on port 8002
3. Check service URLs in .env file

### Frontend Integration Issues

**Problem**: Frontend can't connect to unified service
**Solution**:
1. Ensure unified service is running on port 8013
2. Check CORS configuration
3. Verify API endpoint: `/api/unified/comprehensive-recommendations`
