# 📚 InspectDoc API Documentation Guide

Welcome! This guide explains how to use the InspectDoc API for document authentication.

## 🚀 Quick Start (5 Minutes)

### 1. **Get Your API Key**
```bash
curl -X POST http://localhost:5001/api/billing/signup \
  -H "Content-Type: application/json" \
  -d '{
    "client_id": "my-app",
    "email": "your@email.com"
  }'

# Save the api_key from response
```

### 2. **Analyze Your First Document**
```bash
curl -X POST http://localhost:5001/api/analyze \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "file=@document.jpg"
```

### 3. **Check the Result**
```json
{
  "success": true,
  "overall_authenticity_score": 0.92,
  "is_authentic": true,
  "risk_level": "AUTHENTIC"
}
```

✅ **Done!** Your document is authentic.

---

## 📖 Documentation Options

### **For Quick Testing**
📍 Go to: **[API_QUICK_REFERENCE.md](API_QUICK_REFERENCE.md)**
- 5-minute quick start
- All endpoints at a glance
- Common code examples
- Error reference

### **For Interactive Testing**
📍 Go to: **http://localhost:5001/apidocs**
- Test endpoints directly in browser
- See request/response examples
- Swagger UI with full documentation
- Try-it-out functionality

### **For Integration**
📍 Go to: **[OPENAPI_DOCS.md](OPENAPI_DOCS.md)**
- SDK generation instructions
- IDE integration setup
- Postman import guide
- Best practices

### **For Complete Reference**
📍 Go to: **[API_DOCS.md](API_DOCS.md)**
- Full endpoint documentation
- All request/response formats
- Rate limiting details
- Feature explanations

### **For Raw Spec**
📍 Get: **http://localhost:5001/apispec.json**
- OpenAPI 3.0 specification
- Machine-readable format
- Use with tools and generators

---

## 🔑 Authentication

All API endpoints (except signup and plans) require an API key:

```bash
curl http://localhost:5001/api/analyze \
  -H "Authorization: Bearer sk_live_YOUR_KEY" \
  -F "file=@document.jpg"
```

### Getting an API Key
1. Sign up: `POST /api/billing/signup`
2. Provide `client_id` and `email`
3. Receive `api_key` in response
4. Save it securely (you won't be able to retrieve it again)

---

## 📊 API Overview

### Core Endpoints

| Endpoint | Method | Purpose | Auth |
|----------|--------|---------|------|
| `/api/billing/signup` | POST | Create account | ❌ |
| `/api/billing/plans` | GET | View pricing | ❌ |
| `/api/analyze` | POST | Analyze single document | ✅ |
| `/api/batch-analyze` | POST | Analyze multiple documents | ✅ |
| `/api/health` | GET | Check API status | ❌ |

### Subscription Plans

| Plan | Monthly Limit | Price | Use Case |
|------|---------------|-------|----------|
| **Free** | 100 requests | $0 | Testing & development |
| **Pro** | 5,000 requests | $29 | Regular users |
| **Enterprise** | 100,000 requests | $199 | Large-scale operations |

---

## 🎯 Common Use Cases

### **Case 1: Verify a Single Document**
```python
import requests

response = requests.post(
    "http://localhost:5001/api/analyze",
    files={"file": open("document.jpg", "rb")},
    headers={"Authorization": "Bearer sk_live_..."}
)
data = response.json()
print(f"Authentic: {data['is_authentic']}")
```

### **Case 2: Batch Upload 10 Documents**
```javascript
const formData = new FormData();
for (let file of files) {
    formData.append("files", file);
}

const response = await fetch("http://localhost:5001/api/batch-analyze", {
  method: "POST",
  headers: { "Authorization": "Bearer sk_live_..." },
  body: formData
});
```

### **Case 3: Check Your Plan & Usage**
```bash
curl http://localhost:5001/api/billing/current-plan \
  -H "Authorization: Bearer sk_live_..."

# Response shows:
# - Your plan level
# - Usage this month
# - Remaining quota
```

---

## 📈 Understanding Results

### Authenticity Score

The API returns a score from **0 to 1**:

- **0.0 - 0.3** 🔴 **SUSPICIOUS**
  - Likely fake or AI-generated
  - Action: Reject or review manually

- **0.3 - 0.7** 🟡 **UNCERTAIN**
  - Some signs of tampering detected
  - Action: Manual review recommended

- **0.7 - 1.0** 🟢 **AUTHENTIC**
  - Document appears genuine
  - Action: Accept the document

### Response Format

```json
{
  "success": true,
  "timestamp": "2026-02-11T10:30:00Z",
  "overall_authenticity_score": 0.92,
  "is_authentic": true,
  "risk_level": "AUTHENTIC",
  "vlm_verification": {
    "performed": true,
    "verdict": "GENUINE",
    "confidence": 95.5,
    "analysis": "Document shows no signs of AI generation or tampering"
  }
}
```

---

## ⚠️ Rate Limiting & Quotas

Each plan has a monthly request limit:

| Plan | Limit | Reset |
|------|-------|-------|
| Free | 100/month | 1st of month |
| Pro | 5,000/month | 1st of month |
| Enterprise | 100,000/month | 1st of month |

**When quota is exceeded (402 response):**
```json
{
  "error": "Quota exceeded. Upgrade your plan to continue.",
  "code": "quota_exceeded",
  "remaining_quota": 0,
  "reset_date": "2026-03-01T00:00:00Z"
}
```

**Solution:** Upgrade your plan or wait for the monthly reset.

---

## 🛠️ Integration Options

### **Option 1: Use Swagger UI (Easiest)**
1. Visit: `http://localhost:5001/apidocs`
2. Click "Authorize" and enter your API key
3. Click "Try it out" on any endpoint
4. See live responses

### **Option 2: Use cURL (Command Line)**
```bash
curl -X POST http://localhost:5001/api/analyze \
  -H "Authorization: Bearer sk_live_..." \
  -F "file=@document.jpg"
```

### **Option 3: Use Postman (Desktop App)**
1. Import: `http://localhost:5001/apispec.json`
2. Set up collection variables
3. Click "Send" to test

### **Option 4: Use Generated SDK**
```bash
# Generate Python client
openapi-generator-cli generate \
  -i http://localhost:5001/apispec.json \
  -g python \
  -o inspectdoc-client

# Use in your code
from inspectdoc_client import DefaultApi
```

---

## 🚨 Error Handling

| Status | Error | Solution |
|--------|-------|----------|
| 401 | Invalid API key | Generate a new key or check existing one |
| 402 | Quota exceeded | Upgrade plan or wait for monthly reset |
| 400 | Bad request | Check file format (must be jpg/png/gif/tiff/webp/bmp) |
| 413 | File too large | Compress image (max 50MB) |
| 500 | Server error | Try again or contact support |

---

## 💡 Best Practices

### ✅ Do:
- Store API key securely (use environment variables)
- Implement retry logic with exponential backoff
- Cache results to avoid duplicate analyses
- Monitor rate limit headers
- Use batch endpoint for multiple files

### ❌ Don't:
- Commit API keys to Git
- Expose API key in client-side code
- Send API key in URL query parameters
- Make unlimited requests to test
- Store sensitive data in logs

---

## 📱 Code Examples

### Python
```python
import requests

def analyze_document(api_key, file_path):
    with open(file_path, 'rb') as f:
        response = requests.post(
            'http://localhost:5001/api/analyze',
            files={'file': f},
            headers={'Authorization': f'Bearer {api_key}'}
        )
    return response.json()

# Usage
result = analyze_document('sk_live_...', 'document.jpg')
print(f"Authentic: {result['is_authentic']}")
```

### JavaScript
```javascript
async function analyzeDocument(apiKey, file) {
  const formData = new FormData();
  formData.append('file', file);

  const response = await fetch('http://localhost:5001/api/analyze', {
    method: 'POST',
    headers: { 'Authorization': `Bearer ${apiKey}` },
    body: formData
  });
  
  return response.json();
}

// Usage
const file = document.getElementById('input').files[0];
const result = await analyzeDocument('sk_live_...', file);
console.log(result.is_authentic);
```

### cURL
```bash
API_KEY="sk_live_..."

curl -X POST http://localhost:5001/api/analyze \
  -H "Authorization: Bearer $API_KEY" \
  -F "file=@document.jpg" \
  -s | jq '.overall_authenticity_score'
```

---

## 🔗 Resources

| Resource | Link | Purpose |
|----------|------|---------|
| **Quick Reference** | [API_QUICK_REFERENCE.md](API_QUICK_REFERENCE.md) | Fast lookup guide |
| **Interactive Docs** | http://localhost:5001/apidocs | Try endpoints live |
| **OpenAPI Spec** | http://localhost:5001/apispec.json | Machine-readable spec |
| **Full Docs** | [API_DOCS.md](API_DOCS.md) | Complete reference |
| **OpenAPI Guide** | [OPENAPI_DOCS.md](OPENAPI_DOCS.md) | Integration guide |

---

## 📞 Support

- **Email**: support@inspectdoc.com
- **Interactive Docs**: http://localhost:5001/apidocs
- **Issues**: Check error responses and [API_DOCS.md](API_DOCS.md)

---

## 🎉 Ready to Get Started?

1. **Sign up**: `POST /api/billing/signup`
2. **Test**: Go to http://localhost:5001/apidocs
3. **Integrate**: Use [API_QUICK_REFERENCE.md](API_QUICK_REFERENCE.md) for code samples
4. **Deploy**: Follow [OPENAPI_DOCS.md](OPENAPI_DOCS.md) for production setup

Happy coding! 🚀

