# 🤖 DizzCall AI - Client API Documentation

## Overview
This API allows your client to test and integrate with the DizzCall AI phone system. The AI can handle customer calls, provide responses, and simulate real phone conversations.

## Base URL
```
https://princedevops.live/dizzcall-ai/public/api/client-test
```

## Authentication
**No authentication required** - These are public testing endpoints.

---

## 📞 API Endpoints

### 1. Test System Connection
**GET** `/connection`

Check if the AI system is operational.

**Response:**
```json
{
  "success": true,
  "message": "AI System Status Check",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "details": {
    "ai_service": "operational",
    "database": "connected"
  },
  "system_status": "operational"
}
```

**cURL Example:**
```bash
curl -X GET "https://princedevops.live/dizzcall-ai/public/api/client-test/connection"
```

---

### 2. Simulate Phone Call
**POST** `/simulate-call`

Simulate what happens when someone calls your Twilio number.

**Request Body:**
```json
{
  "caller_phone": "+1234567890",
  "message": "Hello, I'm interested in your services",
  "conversation_type": "general"
}
```

**Parameters:**
- `caller_phone` (required): Phone number of the caller
- `message` (required): What the caller says (max 500 characters)
- `conversation_type` (optional): Type of conversation (`general`, `sales`, `support`, `technical`)

**Response:**
```json
{
  "success": true,
  "message": "Phone call simulation completed",
  "data": {
    "caller_phone": "+1234567890",
    "user_message": "Hello, I'm interested in your services",
    "ai_response": "Hi there! This is Alex from Dizaart Systems. I'm excited to help you today. What can I assist you with?",
    "response_time_ms": 1250,
    "model_used": "gemini-1.5-flash",
    "conversation_type": "general",
    "timestamp": "2024-01-15T10:30:00.000Z"
  }
}
```

**cURL Example:**
```bash
curl -X POST "https://princedevops.live/dizzcall-ai/public/api/client-test/simulate-call" \
  -H "Content-Type: application/json" \
  -d '{
    "caller_phone": "+1234567890",
    "message": "What are your prices for software development?",
    "conversation_type": "sales"
  }'
```

---

### 3. Test Multiple AI Responses
**POST** `/test-responses`

Test multiple messages to see how the AI responds to different scenarios.

**Request Body:**
```json
{
  "test_messages": [
    "Hello, I need help with your services",
    "What are your prices for software development?",
    "I need technical support for my project",
    "Can I schedule a meeting with your team?"
  ],
  "conversation_type": "general"
}
```

**Parameters:**
- `test_messages` (required): Array of messages to test (1-10 messages)
- `conversation_type` (optional): Type of conversation

**Response:**
```json
{
  "success": true,
  "message": "AI response testing completed",
  "data": {
    "total_tests": 4,
    "conversation_type": "general",
    "results": [
      {
        "test_number": 1,
        "user_message": "Hello, I need help with your services",
        "ai_response": "Hi there! This is Alex from Dizaart Systems...",
        "response_time_ms": 1200,
        "model_used": "gemini-1.5-flash",
        "success": true
      }
    ],
    "timestamp": "2024-01-15T10:30:00.000Z"
  }
}
```

---

### 4. Simulate Twilio Webhook
**POST** `/simulate-webhook`

Simulate what happens when Twilio sends webhook data to your system.

**Request Body:**
```json
{
  "from_phone": "+1234567890",
  "speech_result": "Hello, I need help with your services"
}
```

**Parameters:**
- `from_phone` (optional): Caller's phone number
- `speech_result` (optional): What the caller said

**Response:**
```json
{
  "success": true,
  "message": "Webhook simulation completed",
  "data": {
    "webhook_received": {
      "CallSid": "CA1234567890abcdef",
      "From": "+1234567890",
      "To": "+16084969211",
      "CallStatus": "in-progress",
      "Direction": "inbound",
      "SpeechResult": "Hello, I need help with your services",
      "Confidence": "0.95"
    },
    "ai_response": "Hi there! This is Alex from Dizaart Systems...",
    "twiml_response": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response>...</Response>",
    "call_logged": true,
    "timestamp": "2024-01-15T10:30:00.000Z"
  }
}
```

---

### 5. Get Performance Metrics
**GET** `/performance`

Get system performance and statistics.

**Response:**
```json
{
  "success": true,
  "message": "Performance metrics retrieved",
  "data": {
    "ai_response_time_ms": 1200,
    "ai_available": true,
    "recent_calls_7_days": 45,
    "successful_calls_7_days": 42,
    "success_rate": 93.33,
    "system_uptime": "operational",
    "timestamp": "2024-01-15T10:30:00.000Z"
  }
}
```

---

### 6. Test Predefined Scenarios
**GET** `/scenarios`

Test common customer scenarios automatically.

**Response:**
```json
{
  "success": true,
  "message": "Scenario testing completed",
  "data": {
    "total_scenarios": 7,
    "results": [
      {
        "scenario": "greeting",
        "message": "Hello, I'm interested in your services",
        "ai_response": "Hi there! This is Alex from Dizaart Systems...",
        "response_time_ms": 1200,
        "success": true
      }
    ],
    "timestamp": "2024-01-15T10:30:00.000Z"
  }
}
```

---

## 🎯 Client Integration Examples

### JavaScript/Node.js
```javascript
const axios = require('axios');

const API_BASE = 'https://princedevops.live/dizzcall-ai/public/api/client-test';

// Test connection
async function testConnection() {
  try {
    const response = await axios.get(`${API_BASE}/connection`);
    console.log('System Status:', response.data.success ? 'Online' : 'Offline');
  } catch (error) {
    console.error('Connection test failed:', error.message);
  }
}

// Simulate phone call
async function simulateCall(message) {
  try {
    const response = await axios.post(`${API_BASE}/simulate-call`, {
      caller_phone: '+1234567890',
      message: message,
      conversation_type: 'general'
    });
    
    console.log('AI Response:', response.data.data.ai_response);
    console.log('Response Time:', response.data.data.response_time_ms + 'ms');
  } catch (error) {
    console.error('Call simulation failed:', error.message);
  }
}

// Test multiple scenarios
async function testScenarios() {
  try {
    const response = await axios.post(`${API_BASE}/test-responses`, {
      test_messages: [
        'Hello, I need help',
        'What are your prices?',
        'Can I schedule a meeting?'
      ]
    });
    
    response.data.data.results.forEach(result => {
      console.log(`${result.test_number}. ${result.user_message}`);
      console.log(`   AI: ${result.ai_response}`);
      console.log(`   Time: ${result.response_time_ms}ms\n`);
    });
  } catch (error) {
    console.error('Scenario testing failed:', error.message);
  }
}
```

### Python
```python
import requests
import json

API_BASE = 'https://princedevops.live/dizzcall-ai/public/api/client-test'

def test_connection():
    try:
        response = requests.get(f'{API_BASE}/connection')
        data = response.json()
        print(f"System Status: {'Online' if data['success'] else 'Offline'}")
    except Exception as e:
        print(f"Connection test failed: {e}")

def simulate_call(message):
    try:
        payload = {
            'caller_phone': '+1234567890',
            'message': message,
            'conversation_type': 'general'
        }
        response = requests.post(f'{API_BASE}/simulate-call', json=payload)
        data = response.json()
        
        print(f"AI Response: {data['data']['ai_response']}")
        print(f"Response Time: {data['data']['response_time_ms']}ms")
    except Exception as e:
        print(f"Call simulation failed: {e}")

def test_scenarios():
    try:
        payload = {
            'test_messages': [
                'Hello, I need help',
                'What are your prices?',
                'Can I schedule a meeting?'
            ]
        }
        response = requests.post(f'{API_BASE}/test-responses', json=payload)
        data = response.json()
        
        for result in data['data']['results']:
            print(f"{result['test_number']}. {result['user_message']}")
            print(f"   AI: {result['ai_response']}")
            print(f"   Time: {result['response_time_ms']}ms\n")
    except Exception as e:
        print(f"Scenario testing failed: {e}")
```

### PHP
```php
<?php
$apiBase = 'https://princedevops.live/dizzcall-ai/public/api/client-test';

function testConnection() {
    global $apiBase;
    try {
        $response = file_get_contents($apiBase . '/connection');
        $data = json_decode($response, true);
        echo "System Status: " . ($data['success'] ? 'Online' : 'Offline') . "\n";
    } catch (Exception $e) {
        echo "Connection test failed: " . $e->getMessage() . "\n";
    }
}

function simulateCall($message) {
    global $apiBase;
    try {
        $payload = json_encode([
            'caller_phone' => '+1234567890',
            'message' => $message,
            'conversation_type' => 'general'
        ]);
        
        $context = stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => 'Content-Type: application/json',
                'content' => $payload
            ]
        ]);
        
        $response = file_get_contents($apiBase . '/simulate-call', false, $context);
        $data = json_decode($response, true);
        
        echo "AI Response: " . $data['data']['ai_response'] . "\n";
        echo "Response Time: " . $data['data']['response_time_ms'] . "ms\n";
    } catch (Exception $e) {
        echo "Call simulation failed: " . $e->getMessage() . "\n";
    }
}
?>
```

---

## 🌐 Web Dashboard

### Client Test Dashboard
Visit: `https://princedevops.live/dizzcall-ai/public/client-test-dashboard`

This provides a user-friendly interface to:
- Test phone call simulations
- Run quick message tests
- View system performance
- Test different scenarios
- View real-time results

---

## 📊 Response Codes

| Code | Description |
|------|-------------|
| 200 | Success |
| 400 | Bad Request (validation error) |
| 500 | Internal Server Error |

---

## 🔧 Error Handling

All endpoints return consistent error responses:

```json
{
  "success": false,
  "message": "Error description",
  "error": "Detailed error message",
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

---

## 📞 Real Phone Integration

### Twilio Webhook URLs
When your client's dialer redirects calls to your system, use these webhook URLs:

- **Incoming Calls**: `https://princedevops.live/dizzcall-ai/public/api/twilio/webhook/incoming`
- **Speech Processing**: `https://princedevops.live/dizzcall-ai/public/api/twilio/webhook/speech`
- **Outbound Calls**: `https://princedevops.live/dizzcall-ai/public/api/twilio/webhook/outbound`

### Phone Number
Your AI system is configured to handle calls to: **+16084969211**

---

## 🚀 Quick Start for Client

1. **Test Connection**: `GET /api/client-test/connection`
2. **Simulate Call**: `POST /api/client-test/simulate-call`
3. **Test Scenarios**: `GET /api/client-test/scenarios`
4. **Check Performance**: `GET /api/client-test/performance`
5. **Use Web Dashboard**: Visit `/client-test-dashboard`

---

## 📞 Support

For technical support or questions about the API:
- **Email**: info@dizaartsystems.com
- **Phone**: +16084969211 (AI will answer!)
- **Web Dashboard**: Test the system live

---

**🎉 Your AI phone system is ready for client testing!**
