# Prompt to Wireframe - Backend

A Flask-based backend service that generates SVG wireframes from natural language prompts using Claude AI. The system converts user descriptions into precise, scalable vector graphics that can be rendered directly in the frontend.

## 🚀 Features

- **AI-Powered Generation**: Uses Claude AI to analyze prompts and create wireframe layouts
- **SVG Output**: Generates precise SVG wireframes with proper positioning and styling
- **Flexible Response Types**: Supports both SVG and JSON responses for compatibility
- **Real-time Processing**: Fast wireframe generation with minimal latency
- **Scalable Architecture**: Built with Flask for easy deployment and scaling

## 🏗️ Architecture

### Backend Stack
- **Flask 3.0** - Web framework
- **Claude AI** - Natural language processing
- **SVG Generation** - Vector graphics creation
- **Python 3.9+** - Runtime environment

### Response System
The backend can generate two types of responses:

1. **SVG Response** (Primary)
   - Direct SVG content
   - Precise positioning and styling
   - Better frontend rendering performance

2. **JSON Response** (Fallback)
   - Structured wireframe specifications
   - Compatible with existing frontend logic
   - Used when SVG generation fails

## 📁 Project Structure

```
backend/
├── app.py                 # Main Flask application
├── requirements.txt       # Python dependencies
├── run.py                # Application entry point
├── env.example           # Environment variables template
├── start_backend.bat     # Windows startup script
├── start_backend.sh      # Unix startup script
└── test_api.py           # API testing script
```

## 🔧 Installation

### Prerequisites
- Python 3.9 or higher
- pip package manager
- Claude AI API access

### Setup Steps

1. **Clone the repository**
   ```bash
   git clone <repository-url>
   cd wireframe-tool/tldraw-editor/backend
   ```

2. **Create virtual environment**
   ```bash
   python -m venv venv
   
   # Windows
   venv\Scripts\activate
   
   # Unix/Mac
   source venv/bin/activate
   ```

3. **Install dependencies**
   ```bash
   pip install -r requirements.txt
   ```

4. **Configure environment**
   ```bash
   cp env.example .env
   # Edit .env with your Claude AI API key
   ```

5. **Start the server**
   ```bash
   # Windows
   start_backend.bat
   
   # Unix/Mac
   ./start_backend.sh
   
   # Or directly
   python run.py
   ```

## 🔌 API Endpoints

### Generate Wireframe
**POST** `/generate-wireframe`

Generates a wireframe from a natural language prompt.

#### Request Body
```json
{
  "prompt": "Dashboard with header, sidebar, and 3 stats cards"
}
```

#### Response Types

**SVG Response** (Preferred)
```
Content-Type: image/svg+xml

<svg width="800" height="600" viewBox="0 0 800 600">
  <!-- SVG wireframe content -->
</svg>
```

**JSON Response** (Fallback)
```
Content-Type: application/json

{
  "success": true,
  "wireframe": {
    "layout": { ... },
    "styling": { ... },
    "annotations": { ... }
  }
}
```

### Health Check
**GET** `/health`

Returns server status and health information.

## 🎯 SVG Generation

### SVG Structure
The generated SVGs follow a consistent structure:

```xml
<svg width="800" height="600" viewBox="0 0 800 600">
  <defs>
    <!-- Filters, gradients, and definitions -->
  </defs>
  <g>
    <!-- Header section -->
    <rect x="0" y="0" width="800" height="60" fill="#f0f0f0"/>
    <text x="20" y="35">Header</text>
    
    <!-- Sidebar -->
    <rect x="0" y="60" width="200" height="540" fill="#e0e0e0"/>
    
    <!-- Main content -->
    <rect x="220" y="60" width="580" height="540" fill="#ffffff"/>
    
    <!-- Content elements -->
    <rect x="240" y="80" width="160" height="120" fill="#f8f9fa"/>
    <text x="250" y="100">Stats Card 1</text>
  </g>
</svg>
```

### Element Types Supported
- **Rectangles**: Header, sidebar, content areas, cards
- **Text**: Labels, titles, descriptions
- **Groups**: Logical sections and containers
- **Paths**: Complex shapes and icons
- **Circles/Ellipses**: Icons and decorative elements

## 🤖 AI Integration

### Claude AI Processing
The backend uses Claude AI to:

1. **Analyze Prompts**: Understand user requirements
2. **Generate Layouts**: Create logical wireframe structures
3. **Apply UX Principles**: Follow design best practices
4. **Output SVG**: Generate precise vector graphics

### Prompt Processing Flow
```
User Prompt → Claude AI → Layout Analysis → SVG Generation → Response
```

### Example Prompts
- "Dashboard with header, left sidebar, 3 stats cards, line chart, and footer"
- "Landing page with hero section, feature grid, and contact form"
- "E-commerce product page with image gallery and product details"

## 🔧 Configuration

### Environment Variables
```bash
# Claude AI Configuration
CLAUDE_API_KEY=your_api_key_here
CLAUDE_MODEL=claude-3-sonnet-20240229

# Server Configuration
FLASK_ENV=development
FLASK_DEBUG=True
PORT=5000

# CORS Configuration
CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
```

### API Configuration
```python
# app.py
app.config['CLAUDE_API_KEY'] = os.getenv('CLAUDE_API_KEY')
app.config['CLAUDE_MODEL'] = os.getenv('CLAUDE_MODEL', 'claude-3-sonnet-20240229')
app.config['MAX_PROMPT_LENGTH'] = 1000
```

## 🚀 Deployment

### Development
```bash
python run.py
# Server runs on http://localhost:5000
```

### Production
```bash
# Using Gunicorn
gunicorn -w 4 -b 0.0.0.0:5000 run:app

# Using uWSGI
uwsgi --http :5000 --module run:app
```

### Docker Deployment
```dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 5000
CMD ["python", "run.py"]
```

## 🧪 Testing

### API Testing
```bash
python test_api.py
```

### Manual Testing
```bash
# Test with curl
curl -X POST http://localhost:5000/generate-wireframe \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Simple dashboard with header and sidebar"}'

# Test health endpoint
curl http://localhost:5000/health
```

### Load Testing
```bash
# Using Apache Bench
ab -n 100 -c 10 -p test_data.json \
  -T application/json \
  http://localhost:5000/generate-wireframe
```

## 📊 Monitoring

### Health Checks
- Server status monitoring
- API response time tracking
- Error rate monitoring
- Resource usage tracking

### Logging
```python
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@app.route('/generate-wireframe', methods=['POST'])
def generate_wireframe():
    logger.info(f"Received prompt: {request.json.get('prompt', '')[:100]}...")
    # ... processing logic
```

## 🔒 Security

### API Key Management
- Secure storage of Claude AI API keys
- Environment variable protection
- Key rotation support

### Input Validation
- Prompt length limits
- Content sanitization
- Rate limiting support

### CORS Configuration
```python
from flask_cors import CORS

CORS(app, origins=os.getenv('CORS_ORIGINS', '').split(','))
```

## 🐛 Troubleshooting

### Common Issues

1. **Claude AI API Errors**
   - Verify API key is valid
   - Check API quota and limits
   - Ensure proper model access

2. **SVG Generation Failures**
   - Check prompt complexity
   - Verify SVG output format
   - Review error logs

3. **Performance Issues**
   - Monitor response times
   - Check server resources
   - Optimize AI model usage

### Debug Mode
Enable debug logging:
```python
app.config['DEBUG'] = True
logging.getLogger().setLevel(logging.DEBUG)
```

## 📈 Performance Optimization

### Caching Strategies
- Response caching for similar prompts
- SVG template caching
- AI response caching

### Async Processing
- Background SVG generation
- Queue-based processing
- WebSocket updates

### Resource Management
- Connection pooling
- Memory optimization
- CPU usage monitoring

## 🔮 Future Enhancements

### Planned Features
- **Template System**: Pre-built wireframe templates
- **Custom Styling**: User-defined color schemes
- **Export Options**: PNG, PDF, and other formats
- **Collaboration**: Real-time editing and sharing
- **Version Control**: Wireframe history and branching

### Scalability Improvements
- **Microservices**: Separate AI and SVG services
- **Load Balancing**: Multiple backend instances
- **CDN Integration**: Global content delivery
- **Database Storage**: Wireframe persistence

## 🤝 Contributing

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

### Development Guidelines
- Follow PEP 8 style guidelines
- Add type hints for new functions
- Include docstrings for all functions
- Write tests for new features

## 📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

## 🆘 Support

For support and questions:
- Create an issue in the repository
- Check the troubleshooting section
- Review the frontend documentation
- Contact the development team

---

**Note**: This backend service is designed to work with the Prompt to Wireframe frontend application, providing SVG wireframe generation capabilities through Claude AI integration.
