"""
API Documentation Interface for Streamlit
Comprehensive documentation for the SIM Analytics API
"""

import streamlit as st
import requests
import json
from auth import check_permission

def show_api_documentation():
    """Display comprehensive API documentation"""
    st.header("📚 SIM Analytics API Documentation v1.1.3")
    st.markdown("Complete guide for integrating with the SIM Analytics API")
    
    # Production domain info
    st.info("**Production API Base URL:** https://radius.telkom.click/api/v1")
    st.info("**Public Documentation:** https://radius.telkom.click/api-docs")
    
    # Quick Start Section
    st.subheader("🚀 Quick Start")
    
    with st.expander("Getting Started", expanded=True):
        st.markdown("""
        ### Prerequisites
        - **API Key**: You need a valid API key to access the endpoints
        - **Base URL**: All API requests should be made to the base URL
        - **Authentication**: Include your API key in request headers
        
        ### Authentication Types
        - **Admin API Key**: Full access to all endpoints (create, read, update, delete)
        - **User API Key**: Read-only access to analytics and reports
        """)
        
        st.code("""
# Example API Request (Python)
import requests

headers = {
    'X-API-Key': 'your_api_key_here',
    'Content-Type': 'application/json'
}

response = requests.get('https://radius.telkom.click/api/v1/clients', headers=headers)
data = response.json()
        """, language="python")
    
    # NEW: SIM-Based Protocol Analysis
    st.subheader("🆕 NEW: SIM-Based Protocol Analysis")
    
    with st.expander("SIM Protocol Analysis - Individual SIM Analysis", expanded=True):
        st.markdown("### GET /api/v1/analytics/protocols/{sim_number}")
        st.markdown("**Description**: Get protocol analysis for specific SIM card with exact usage matching")
        st.markdown("**Authentication**: User or Admin")
        st.markdown("**New Features**: Per-SIM analysis, byte-level precision, data validation")
        
        st.code("""
GET /api/v1/analytics/protocols/89270277240011345783

Response:
{
    "sim_number": "89270277240011345783",
    "client_name": "TechCorp Solutions",
    "usage_records": [
        {
            "id": 179,
            "total_usage_gb": 309.800,
            "date_from": "2024-01-01",
            "date_to": "2024-01-31"
        }
    ],
    "protocol_data": [...],
    "data_validation": [
        {
            "recorded_usage": 309.800,
            "protocol_total": 309.821,
            "discrepancy": 0.021
        }
    ],
    "total_records": 1
}
        """, language="json")
        
        st.markdown("### GET /api/v1/analytics/protocols/{sim_number}/{usage_record_id}")
        st.markdown("**Description**: Get detailed protocol analysis for specific usage period")
        st.markdown("**Authentication**: User or Admin")
        st.markdown("**Features**: Exact usage matching, discrepancy detection, category breakdown")
        
        st.code("""
GET /api/v1/analytics/protocols/89270277240011345783/179

Response:
{
    "sim_number": "89270277240011345783",
    "usage_record": {
        "id": 179,
        "total_usage_gb": 309.800,
        "date_from": "2024-01-01",
        "date_to": "2024-01-31",
        "client_name": "TechCorp Solutions"
    },
    "protocol_data": [
        {
            "protocol_name": "HTTP",
            "category": "Web",
            "usage_gb": 185.523,
            "percentage": 59.9
        }
    ],
    "category_data": [
        {
            "category": "Web",
            "category_total": 185.523,
            "protocol_count": 5
        }
    ],
    "data_validation": {
        "recorded_usage": 309.800,
        "protocol_total": 309.821,
        "discrepancy": 0.021
    },
    "exact_match": false
}
        """, language="json")

    # API Reference
    st.subheader("📖 Core API Reference")
    
    # Health Check
    with st.expander("Health Check"):
        st.markdown("### GET /api/v1/health")
        st.markdown("**Description**: Check API health status")
        st.markdown("**Authentication**: None required")
        
        st.code("""
GET /api/v1/health

Response:
{
    "status": "healthy",
    "timestamp": "2024-01-15T10:30:00Z",
    "version": "1.0.0"
}
        """, language="json")
    
    # Client Management
    with st.expander("👥 Client Management"):
        st.markdown("### Client Endpoints")
        
        # List Clients
        st.markdown("#### GET /api/v1/clients")
        st.markdown("**Description**: Retrieve all clients")
        st.markdown("**Authentication**: User or Admin")
        
        st.code("""
GET /api/v1/clients

Response:
{
    "clients": [
        {
            "client_id": "JSmith0001",
            "client_name": "John Smith",
            "created_at": "2024-01-01T10:00:00Z"
        }
    ],
    "count": 1
}
        """, language="json")
        
        # Create Client
        st.markdown("#### POST /api/v1/clients")
        st.markdown("**Description**: Create a new client")
        st.markdown("**Authentication**: Admin only")
        
        st.code("""
POST /api/v1/clients
Content-Type: application/json

{
    "client_name": "John Smith"
}

Response:
{
    "message": "Client created successfully",
    "client": {
        "client_id": "JSmith0001",
        "client_name": "John Smith"
    }
}
        """, language="json")
        
        # Get Client Details
        st.markdown("#### GET /api/v1/clients/{client_id}")
        st.markdown("**Description**: Get detailed client information including SIM cards")
        st.markdown("**Authentication**: User or Admin")
        
        st.code("""
GET /api/v1/clients/JSmith0001

Response:
{
    "client": {
        "client_id": "JSmith0001",
        "client_name": "John Smith",
        "created_at": "2024-01-01T10:00:00Z"
    },
    "sim_cards": [
        {
            "id": 1,
            "sim_number": "1234567890",
            "msisdn": "1234567890123456",
            "fup_gb": 50
        }
    ],
    "sim_count": 1
}
        """, language="json")
        
        # Delete Client
        st.markdown("#### DELETE /api/v1/clients/{client_id}")
        st.markdown("**Description**: Delete a client and all associated data")
        st.markdown("**Authentication**: Admin only")
        
        st.code("""
DELETE /api/v1/clients/JSmith0001

Response:
{
    "message": "Client deleted successfully"
}
        """, language="json")
    
    # SIM Management
    with st.expander("📱 SIM Card Management"):
        st.markdown("### SIM Card Endpoints")
        
        # List SIMs
        st.markdown("#### GET /api/v1/sims")
        st.markdown("**Description**: Retrieve all SIM cards")
        st.markdown("**Authentication**: User or Admin")
        st.markdown("**Query Parameters**: `client_id` (optional) - Filter by specific client")
        
        st.code("""
GET /api/v1/sims?client_id=JSmith0001

Response:
{
    "sim_cards": [
        {
            "id": 1,
            "client_id": "JSmith0001",
            "client_name": "John Smith",
            "sim_number": "1234567890",
            "msisdn": "1234567890123456",
            "fup_gb": 50,
            "created_at": "2024-01-01T10:00:00Z"
        }
    ],
    "count": 1
}
        """, language="json")
        
        # Create SIMs
        st.markdown("#### POST /api/v1/sims")
        st.markdown("**Description**: Create one or multiple SIM cards")
        st.markdown("**Authentication**: Admin only")
        
        st.code("""
# Single SIM Creation
POST /api/v1/sims
Content-Type: application/json

{
    "client_id": "JSmith0001",
    "sim_number": "1234567890",
    "msisdn": "1234567890123456",
    "fup_gb": 50
}

# Bulk SIM Creation
POST /api/v1/sims
Content-Type: application/json

{
    "sim_cards": [
        {
            "client_id": "JSmith0001",
            "sim_number": "1234567890",
            "msisdn": "1234567890123456",
            "fup_gb": 50
        },
        {
            "client_id": "JSmith0001",
            "sim_number": "0987654321",
            "msisdn": "6543210987654321",
            "fup_gb": 100
        }
    ]
}

Response:
{
    "message": "2 SIM card(s) created successfully",
    "sim_cards": [...]
}
        """, language="json")
    
    # Usage Data
    with st.expander("📊 Usage Data Management"):
        st.markdown("### Usage Data Endpoints")
        
        # Get Usage Records
        st.markdown("#### GET /api/v1/usage")
        st.markdown("**Description**: Retrieve usage records with optional filtering")
        st.markdown("**Authentication**: User or Admin")
        st.markdown("**Query Parameters**:")
        st.markdown("- `client_id` (optional) - Filter by client")
        st.markdown("- `sim_number` (optional) - Filter by SIM number")  
        st.markdown("- `msisdn` (optional) - Filter by MSISDN")
        st.markdown("- `limit` (optional, default: 100) - Number of records to return")
        st.markdown("- `offset` (optional, default: 0) - Number of records to skip")
        
        st.code("""
GET /api/v1/usage?client_id=JSmith0001&limit=10

Response:
{
    "usage_records": [
        {
            "id": 1,
            "client_id": "JSmith0001",
            "client_name": "John Smith",
            "sim_number": "1234567890",
            "msisdn": "1234567890123456",
            "total_usage_gb": 25.5,
            "date_from": "2024-01-01",
            "date_to": "2024-01-31",
            "fup_reached": false,
            "fup_gb": 50,
            "created_at": "2024-01-01T10:00:00Z"
        }
    ],
    "count": 1,
    "limit": 10,
    "offset": 0
}
        """, language="json")
        
        # Create Usage Record
        st.markdown("#### POST /api/v1/usage")
        st.markdown("**Description**: Create a new usage record")
        st.markdown("**Authentication**: Admin only")
        
        st.code("""
POST /api/v1/usage
Content-Type: application/json

{
    "client_id": "JSmith0001",
    "sim_number": "1234567890",
    "msisdn": "1234567890123456",
    "total_usage_gb": 25.5,
    "date_from": "2024-01-01",
    "date_to": "2024-01-31",
    "fup_reached": false
}

Response:
{
    "message": "Usage record created successfully",
    "record_id": 123
}
        """, language="json")
    
    # Analytics
    with st.expander("📈 Analytics & Reports"):
        st.markdown("### Analytics Endpoints")
        
        # Usage Summary
        st.markdown("#### GET /api/v1/analytics/summary")
        st.markdown("**Description**: Get usage analytics summary")
        st.markdown("**Authentication**: User or Admin")
        st.markdown("**Query Parameters**: `client_id` (optional) - Get summary for specific client")
        
        st.code("""
GET /api/v1/analytics/summary?client_id=JSmith0001

Response:
{
    "summary": {
        "total_records": 12,
        "total_usage_gb": 345.67,
        "fup_exceeded_count": 2
    },
    "top_clients": [
        {
            "client_name": "John Smith",
            "client_id": "JSmith0001",
            "records": 12,
            "total_usage": 345.67
        }
    ]
}
        """, language="json")
        
        # Protocol Analysis
        st.markdown("#### GET /api/v1/analytics/protocols")
        st.markdown("**Description**: Get protocol usage analysis")
        st.markdown("**Authentication**: User or Admin")
        st.markdown("**Query Parameters**: `client_id` (optional) - Get protocols for specific client")
        
        st.code("""
GET /api/v1/analytics/protocols

Response:
{
    "protocols": [
        {
            "protocol_name": "HTTP",
            "category": "Web",
            "total_usage_gb": 123.45,
            "avg_percentage": 35.7,
            "usage_count": 8
        }
    ],
    "categories": [
        {
            "category": "Web",
            "total_usage_gb": 200.15,
            "protocol_count": 5
        }
    ],
    "total_protocols": 15
}
        """, language="json")
    
    # Error Handling
    with st.expander("⚠️ Error Handling"):
        st.markdown("### HTTP Status Codes")
        st.markdown("""
        - **200 OK**: Request successful
        - **201 Created**: Resource created successfully
        - **400 Bad Request**: Invalid request data
        - **401 Unauthorized**: Invalid or missing API key
        - **403 Forbidden**: Insufficient permissions
        - **404 Not Found**: Resource not found
        - **409 Conflict**: Resource already exists
        - **429 Too Many Requests**: Rate limit exceeded
        - **500 Internal Server Error**: Server error
        """)
        
        st.markdown("### Error Response Format")
        st.code("""
{
    "error": "Invalid API key",
    "message": "The provided API key is invalid or inactive"
}
        """, language="json")
    
    # Rate Limiting
    with st.expander("⏱️ Rate Limiting"):
        st.markdown("""
        ### Rate Limits
        - Each API key has a configurable rate limit (default: 1000 requests/hour)
        - Rate limits are enforced per API key
        - When rate limit is exceeded, the API returns HTTP 429
        
        ### Best Practices
        - Implement exponential backoff for retries
        - Cache responses when possible
        - Use bulk endpoints for multiple operations
        - Monitor your usage through the admin dashboard
        """)
    
    # Integration Examples
    st.subheader("💡 Integration Examples")
    
    # Python Example
    with st.expander("🐍 Python Integration"):
        st.code("""
import requests
import json

class SIMAnalyticsAPI:
    def __init__(self, api_key, base_url="https://your-domain/api/v1"):
        self.api_key = api_key
        self.base_url = base_url
        self.headers = {
            'X-API-Key': api_key,
            'Content-Type': 'application/json'
        }
    
    def create_client_and_sims(self, client_name, sim_data):
        # Create client
        client_response = requests.post(
            f"{self.base_url}/clients",
            headers=self.headers,
            json={"client_name": client_name}
        )
        
        if client_response.status_code == 201:
            client = client_response.json()['client']
            client_id = client['client_id']
            
            # Add client_id to each SIM
            for sim in sim_data:
                sim['client_id'] = client_id
            
            # Create SIMs
            sims_response = requests.post(
                f"{self.base_url}/sims",
                headers=self.headers,
                json={"sim_cards": sim_data}
            )
            
            return {
                'client': client,
                'sims': sims_response.json() if sims_response.status_code == 201 else None
            }
        
        return None
    
    def get_client_analytics(self, client_id):
        response = requests.get(
            f"{self.base_url}/analytics/summary?client_id={client_id}",
            headers=self.headers
        )
        
        return response.json() if response.status_code == 200 else None

# Usage Example
api = SIMAnalyticsAPI("your_admin_api_key_here")

# Create client with multiple SIMs
result = api.create_client_and_sims(
    "John Smith Corporation", 
    [
        {
            "sim_number": "1234567890",
            "msisdn": "1234567890123456",
            "fup_gb": 50
        },
        {
            "sim_number": "0987654321", 
            "msisdn": "6543210987654321",
            "fup_gb": 100
        }
    ]
)

if result:
    client_id = result['client']['client_id']
    print(f"Created client: {client_id}")
    
    # Get analytics
    analytics = api.get_client_analytics(client_id)
    print(f"Analytics: {analytics}")
        """, language="python")
    
    # JavaScript Example
    with st.expander("🟨 JavaScript Integration"):
        st.code("""
class SIMAnalyticsAPI {
    constructor(apiKey, baseUrl = 'https://your-domain/api/v1') {
        this.apiKey = apiKey;
        this.baseUrl = baseUrl;
        this.headers = {
            'X-API-Key': apiKey,
            'Content-Type': 'application/json'
        };
    }

    async createClientAndSims(clientName, simData) {
        try {
            // Create client
            const clientResponse = await fetch(`${this.baseUrl}/clients`, {
                method: 'POST',
                headers: this.headers,
                body: JSON.stringify({ client_name: clientName })
            });

            if (clientResponse.ok) {
                const clientResult = await clientResponse.json();
                const clientId = clientResult.client.client_id;

                // Add client_id to each SIM
                const simsWithClientId = simData.map(sim => ({
                    ...sim,
                    client_id: clientId
                }));

                // Create SIMs
                const simsResponse = await fetch(`${this.baseUrl}/sims`, {
                    method: 'POST',
                    headers: this.headers,
                    body: JSON.stringify({ sim_cards: simsWithClientId })
                });

                const simsResult = simsResponse.ok ? await simsResponse.json() : null;

                return {
                    client: clientResult.client,
                    sims: simsResult
                };
            }
        } catch (error) {
            console.error('API Error:', error);
            return null;
        }
    }

    async getUsageData(clientId = null, limit = 100) {
        try {
            const params = new URLSearchParams();
            if (clientId) params.append('client_id', clientId);
            params.append('limit', limit);

            const response = await fetch(`${this.baseUrl}/usage?${params}`, {
                headers: this.headers
            });

            return response.ok ? await response.json() : null;
        } catch (error) {
            console.error('API Error:', error);
            return null;
        }
    }
}

// Usage Example
const api = new SIMAnalyticsAPI('your_admin_api_key_here');

// Create client with SIMs
api.createClientAndSims('Tech Corp', [
    {
        sim_number: '1234567890',
        msisdn: '1234567890123456',
        fup_gb: 50
    }
]).then(result => {
    if (result) {
        console.log('Created:', result);
        
        // Get usage data
        return api.getUsageData(result.client.client_id);
    }
}).then(usage => {
    console.log('Usage data:', usage);
});
        """, language="javascript")
    
    # cURL Examples
    with st.expander("🌐 cURL Examples"):
        st.code("""
# Create a new client
curl -X POST https://your-domain/api/v1/clients \\
  -H "X-API-Key: your_admin_api_key" \\
  -H "Content-Type: application/json" \\
  -d '{"client_name": "John Smith"}'

# Create multiple SIM cards
curl -X POST https://your-domain/api/v1/sims \\
  -H "X-API-Key: your_admin_api_key" \\
  -H "Content-Type: application/json" \\
  -d '{
    "sim_cards": [
      {
        "client_id": "JSmith0001",
        "sim_number": "1234567890",
        "msisdn": "1234567890123456", 
        "fup_gb": 50
      },
      {
        "client_id": "JSmith0001",
        "sim_number": "0987654321",
        "msisdn": "6543210987654321",
        "fup_gb": 100
      }
    ]
  }'

# Get client analytics
curl -X GET "https://your-domain/api/v1/analytics/summary?client_id=JSmith0001" \\
  -H "X-API-Key: your_user_api_key"

# Get usage data with filtering
curl -X GET "https://your-domain/api/v1/usage?client_id=JSmith0001&limit=50" \\
  -H "X-API-Key: your_user_api_key"
        """, language="bash")
    
    # Testing Section
    st.subheader("🧪 API Testing")
    
    if check_permission('admin'):
        with st.expander("Test API Endpoints", expanded=False):
            st.markdown("### Live API Testing")
            st.info("Test API endpoints directly from this interface.")
            
            # API Key input
            test_api_key = st.text_input("API Key", type="password", help="Enter your API key to test endpoints")
            
            if test_api_key:
                # Test endpoint selection
                endpoint = st.selectbox(
                    "Select Endpoint",
                    [
                        "GET /api/v1/health",
                        "GET /api/v1/clients", 
                        "GET /api/v1/sims",
                        "GET /api/v1/usage",
                        "GET /api/v1/analytics/summary"
                    ]
                )
                
                if st.button("🚀 Test Endpoint", type="primary"):
                    try:
                        # Construct base URL (assuming same domain)
                        base_url = st.get_option("server.headless")
                        if base_url:
                            base_url = "http://localhost:5000/api/v1"
                        else:
                            base_url = "/api/v1"
                        
                        headers = {'X-API-Key': test_api_key}
                        
                        # Map endpoints
                        endpoint_map = {
                            "GET /api/v1/health": f"{base_url}/health",
                            "GET /api/v1/clients": f"{base_url}/clients",
                            "GET /api/v1/sims": f"{base_url}/sims", 
                            "GET /api/v1/usage": f"{base_url}/usage",
                            "GET /api/v1/analytics/summary": f"{base_url}/analytics/summary"
                        }
                        
                        url = endpoint_map.get(endpoint)
                        
                        if url:
                            with st.spinner("Testing endpoint..."):
                                response = requests.get(url, headers=headers, timeout=10)
                                
                                st.write(f"**Status Code:** {response.status_code}")
                                st.write(f"**Response Time:** {response.elapsed.total_seconds():.3f}s")
                                
                                if response.headers.get('content-type', '').startswith('application/json'):
                                    st.code(json.dumps(response.json(), indent=2), language="json")
                                else:
                                    st.text(response.text)
                        
                    except requests.exceptions.RequestException as e:
                        st.error(f"❌ Request failed: {str(e)}")
                    except Exception as e:
                        st.error(f"❌ Error: {str(e)}")
    else:
        st.info("🔐 API testing requires admin privileges.")
    
    # Support Section
    st.subheader("🆘 Support & Resources")
    
    col1, col2 = st.columns(2)
    with col1:
        st.markdown("""
        ### 📞 Getting Help
        - Check this documentation for comprehensive API details
        - Review error messages and status codes
        - Verify your API key permissions and rate limits
        - Test endpoints with curl or API testing tools
        """)
    
    with col2:
        st.markdown("""
        ### 🔧 Troubleshooting
        - **401 Unauthorized**: Check your API key
        - **403 Forbidden**: Upgrade to admin key if needed
        - **429 Rate Limited**: Reduce request frequency
        - **500 Server Error**: Check request format and data
        """)