# Logo Generator API Reference

## Quick Start

### 1. Setup Environment Variable

```bash
# .env file
OPENAI_API_KEY="sk-your-openai-api-key-here"
```

Get your key: https://platform.openai.com/api-keys

### 2. Test API Status

```bash
curl http://localhost:3000/api/ai/generate-logo
```

Expected response:
```json
{
  "service": "DALL-E 3 Logo Generator",
  "status": "configured",
  "message": "Ready to generate logos",
  "supportedStyles": [...],
  "maxColors": 5
}
```

## API Endpoints

### GET `/api/ai/generate-logo`

Check service status and configuration.

**Response:**
```typescript
{
  service: string;
  status: "configured" | "not_configured";
  message: string;
  supportedStyles: string[];
  maxColors: number;
}
```

**Example:**
```bash
curl -X GET http://localhost:3000/api/ai/generate-logo
```

---

### POST `/api/ai/generate-logo`

Generate a logo using DALL-E 3.

**Request Body:**
```typescript
{
  projectId: string;           // Project ID
  companyName: string;         // Required: Company/brand name
  style: LogoStyle;            // Required: One of the supported styles
  colors: string[];            // Required: 1-5 hex color codes
  description?: string;        // Optional: Additional context
  industry?: string;           // Optional: Industry/sector
  mood?: string[];            // Optional: Mood descriptors
}

type LogoStyle =
  | "modern"
  | "minimalist"
  | "vintage"
  | "playful"
  | "professional"
  | "abstract"
  | "geometric"
  | "organic";
```

**Success Response (200):**
```json
{
  "success": true,
  "logoUrl": "https://oaidalleapiprodscus.blob.core.windows.net/...",
  "message": "Logo generated successfully!"
}
```

**Error Response (400/500):**
```json
{
  "success": false,
  "error": "Error message",
  "details": [...]  // Only for validation errors
}
```

**Example Request:**
```bash
curl -X POST http://localhost:3000/api/ai/generate-logo \
  -H "Content-Type: application/json" \
  -d '{
    "projectId": "clx123abc",
    "companyName": "TechVision",
    "style": "modern",
    "colors": ["#7b2ff7", "#00f0ff", "#ffffff"],
    "industry": "Technology",
    "mood": ["Innovative", "Trustworthy"],
    "description": "A tech company focused on AI and cloud solutions"
  }'
```

**Example Response:**
```json
{
  "success": true,
  "logoUrl": "https://oaidalleapiprodscus.blob.core.windows.net/private/org-xyz/user-abc/img-123.png?st=2024-...",
  "message": "Logo generated successfully!"
}
```

## Request Validation

### Required Fields
- `projectId`: Non-empty string
- `companyName`: 1-100 characters
- `style`: Must be one of the 8 supported styles
- `colors`: Array with 1-5 hex color codes

### Optional Fields
- `description`: Max 500 characters
- `industry`: String (no max length)
- `mood`: Array of strings

### Validation Errors

**Invalid Style:**
```json
{
  "success": false,
  "error": "Invalid input",
  "details": [{
    "code": "invalid_enum_value",
    "expected": ["modern", "minimalist", ...],
    "received": "invalid-style",
    "path": ["style"]
  }]
}
```

**Too Many Colors:**
```json
{
  "success": false,
  "error": "Invalid input",
  "details": [{
    "code": "too_big",
    "maximum": 5,
    "type": "array",
    "path": ["colors"]
  }]
}
```

## DALL-E 3 Integration Details

### Model Configuration
```typescript
{
  model: "dall-e-3",
  n: 1,                    // Number of images (always 1 for DALL-E 3)
  size: "1024x1024",       // Image dimensions
  quality: "standard",     // "standard" or "hd"
  response_format: "url"   // Returns temporary URL
}
```

### Prompt Construction

The API builds a comprehensive prompt:

```
Create a professional logo design for "{companyName}".
Style: {style}
Colors: {color1}, {color2}, ...
{for industry} for the {industry} industry
{with mood} with a {mood1}, {mood2} mood.
{description}
The logo should be clean, scalable, and memorable. Design it on a transparent or white background, perfectly centered, ready for use as a brand identity. High quality, professional logo design.
```

**Example Prompt:**
```
Create a professional logo design for "TechVision".
Style: modern
Colors: #7b2ff7, #00f0ff, #ffffff for the Technology industry with a Innovative, Trustworthy mood.
A tech company focused on AI and cloud solutions
The logo should be clean, scalable, and memorable. Design it on a transparent or white background, perfectly centered, ready for use as a brand identity. High quality, professional logo design.
```

## Error Handling

### Common Errors

#### 1. API Key Not Configured
```json
{
  "success": false,
  "error": "OpenAI API key not configured. Please add OPENAI_API_KEY to your environment variables."
}
```
**Solution:** Add `OPENAI_API_KEY` to `.env` file

#### 2. OpenAI API Error
```json
{
  "success": false,
  "error": "Billing hard limit has been reached"
}
```
**Solution:** Add credits to OpenAI account

#### 3. Rate Limit
```json
{
  "success": false,
  "error": "Rate limit exceeded"
}
```
**Solution:** Wait and retry, or upgrade OpenAI plan

#### 4. Content Policy Violation
```json
{
  "success": false,
  "error": "Your request was rejected as a result of our safety system"
}
```
**Solution:** Modify prompt to comply with OpenAI policies

## Response Time

- **Average**: 15-25 seconds
- **Range**: 10-30 seconds
- **Timeout**: None set (uses fetch default)

Progress tracking is client-side simulation for UX.

## Image URL Details

### Temporary URLs
- DALL-E returns temporary Azure Blob Storage URLs
- URLs expire after ~1 hour
- Should be downloaded and stored permanently

### Recommended Storage Flow
1. Generate logo via API
2. Receive temporary URL
3. Download image server-side
4. Upload to permanent storage (S3, Cloudinary, etc.)
5. Save permanent URL to database
6. Return permanent URL to client

### Current Implementation
- Returns temporary DALL-E URL directly
- Client can download immediately
- TODO: Implement permanent storage

## Cost Tracking

### DALL-E 3 Pricing (2024)
- **Standard (1024x1024)**: $0.040/image
- **HD (1024x1024)**: $0.080/image

### Recommended Monitoring
```javascript
// Track generations in database
const generation = await db.logoGeneration.create({
  data: {
    projectId,
    userId,
    cost: 0.04,  // Standard quality
    timestamp: new Date(),
    parameters: { companyName, style, colors }
  }
});
```

## Rate Limits

### OpenAI Tier Limits (Tier 1)
- **RPM** (Requests per minute): 5
- **RPD** (Requests per day): 200
- **TPM** (Tokens per minute): 200,000

Higher tiers have increased limits.

## Best Practices

### 1. Validate Client-Side First
```typescript
if (!companyName.trim()) {
  setError("Company name required");
  return;
}
if (colors.length === 0 || colors.length > 5) {
  setError("Select 1-5 colors");
  return;
}
```

### 2. Show Progress
```typescript
const [isGenerating, setIsGenerating] = useState(false);
const [progress, setProgress] = useState(0);

// Simulate progress for UX
const interval = setInterval(() => {
  setProgress(p => Math.min(p + 10, 90));
}, 500);
```

### 3. Handle Errors Gracefully
```typescript
try {
  const response = await fetch("/api/ai/generate-logo", {...});
  const data = await response.json();

  if (!response.ok) {
    throw new Error(data.error || "Generation failed");
  }

  setGeneratedLogo(data.logoUrl);
} catch (error) {
  setError(error.message);
  // Show user-friendly message
}
```

### 4. Store Results
```typescript
// After successful generation
await fetch("/api/assets", {
  method: "POST",
  body: JSON.stringify({
    projectId,
    name: `${companyName} Logo`,
    type: "IMAGE",
    url: logoUrl,  // Permanent URL after storage
    data: JSON.stringify({ style, colors })
  })
});
```

## TypeScript Types

```typescript
// Request
interface LogoGenerationRequest {
  projectId: string;
  companyName: string;
  style: LogoStyle;
  colors: string[];
  description?: string;
  industry?: string;
  mood?: string[];
}

// Response
interface LogoGenerationResponse {
  success: true;
  logoUrl: string;
  message: string;
}

// Error
interface LogoGenerationError {
  success: false;
  error: string;
  details?: any[];
}
```

## Testing

### Test Status Endpoint
```bash
npm run dev
curl http://localhost:3000/api/ai/generate-logo
```

### Test Generation (with valid API key)
```bash
curl -X POST http://localhost:3000/api/ai/generate-logo \
  -H "Content-Type: application/json" \
  -d '{
    "projectId": "test-123",
    "companyName": "Test Co",
    "style": "modern",
    "colors": ["#7b2ff7"]
  }'
```

### Check Response Time
```bash
time curl -X POST ... # Will show total time
```

---

For issues or questions, check:
- OpenAI Status: https://status.openai.com
- OpenAI Docs: https://platform.openai.com/docs/guides/images
- VYLO Documentation: See LOGO_GENERATOR_README.md
