"""
AWS Lambda function for Amazon Connect integration with ToxMod KVS Adapter

This function is triggered from an Amazon Connect contact flow to start
KVS (Kinesis Video Streams) processing and audio analysis for a call.

Prerequisites:
1. Lambda execution role with permissions to make HTTP requests
3. Amazon Connect instance with KVS enabled
4. Proper IAM role configured for Modulate to access KVS

Usage in Connect:
- Add "Invoke AWS Lambda function" block in your contact flow
- Configure this function to be called when call starts
- The function will automatically extract contact ID and construct stream name
"""

import json
import logging
from typing import Any, Dict

import requests

# Configure logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)


def lambda_handler(event: Dict[str, Any], context: Any) -> Dict[str, Any]:
    """
    Lambda handler for Connect KVS processing integration

    Args:
        event: Connect event data containing contact information
        context: Lambda context object

    Returns:
        dict: Response indicating success/failure and any relevant data
    """

    try:
        # Move these to environment variables for production

        # Swap `prod` for single tenant prefix if you were given one
        TOXMOD_API_URL = "https://prod-aws-connect.modulate.ai"

        # Account ID and API key are available in the ToxMod Web console
        TOXMOD_ACCOUNT_ID = "your-modulate-account-uuid"
        TOXMOD_API_KEY = "your-modulate-api-key"

        # AWS IAM role ARN granting Modulate KVS access (must be configured per your environment)
        KVS_ROLE_ARN = "arn:aws:iam::123456789012:role/ConnectKVSAccessRole"

        # Connect KVS configuration
        CONNECT_INSTANCE_PREFIX = "modulate-connect-toxmod-demo"

        # Extract contact information from Connect event
        contact_data = event["Details"]["ContactData"]
        contact_id = contact_data["ContactId"]

        logger.info(f"Processing Connect call with contact ID: {contact_id}")

        # Construct KVS stream name using your Connect instance pattern
        stream_name = f"{CONNECT_INSTANCE_PREFIX}-contact-{contact_id}"

        # Prepare API request parameters
        params = {
            "streamName": stream_name,
            "callerName": f"caller-{contact_id}",
            "agentName": f"agent-{contact_id}",
            "callName": contact_id,  # Use contact UUID as unique call identifier
            "roleArn": KVS_ROLE_ARN,
        }

        # Prepare headers
        headers = {"X-Account-ID": TOXMOD_ACCOUNT_ID, "X-API-Key": TOXMOD_API_KEY}

        logger.info(f"Calling ToxMod API: {TOXMOD_API_URL}/kvs with stream: {stream_name}")

        # Make HTTP request to ToxMod KVS Adapter
        response = requests.get(
            f"{TOXMOD_API_URL}/kvs", params=params, headers=headers, timeout=10.0  # 10 second timeout
        )

        # Get response text
        response_text = response.text

        if response.status_code == 200:
            logger.info(f"ToxMod processing started successfully for contact {contact_id}")
            return {
                "statusCode": 200,
                "success": True,
                "message": "KVS processing started successfully",
                "contactId": contact_id,
                "streamName": stream_name,
                "response": response_text,
            }
        elif response.status_code == 400:
            logger.error(f"Bad request to ToxMod API: {response_text}")
            return {
                "statusCode": 400,
                "success": False,
                "message": "Invalid request parameters",
                "error": response_text,
            }
        elif response.status_code == 403:
            logger.error(f"Authentication failed with ToxMod API: {response_text}")
            return {"statusCode": 403, "success": False, "message": "Authentication failed", "error": response_text}
        elif response.status_code == 500:
            logger.error(f"ToxMod API internal error: {response_text}")
            return {"statusCode": 500, "success": False, "message": "ToxMod service error", "error": response_text}
        else:
            logger.error(f"Unexpected response from ToxMod API: {response.status_code} - {response_text}")
            return {
                "statusCode": response.status_code,
                "success": False,
                "message": f"Unexpected response: {response.status_code}",
                "error": response_text,
            }

    except KeyError as e:
        logger.error(f"Missing required data in Connect event: {str(e)}")
        return {
            "statusCode": 400,
            "success": False,
            "message": "Invalid Connect event data",
            "error": f"Missing field: {str(e)}",
        }

    except requests.exceptions.Timeout:
        logger.error("Timeout calling ToxMod API")
        return {
            "statusCode": 504,
            "success": False,
            "message": "Timeout connecting to ToxMod service",
            "error": "Request timed out",
        }

    except requests.exceptions.RequestException as e:
        logger.error(f"Request error calling ToxMod API: {str(e)}")
        return {"statusCode": 502, "success": False, "message": "Error connecting to ToxMod service", "error": str(e)}

    except Exception as e:
        logger.error(f"Unexpected error: {str(e)}")
        return {"statusCode": 500, "success": False, "message": "Internal Lambda error", "error": str(e)}


# Example Connect event structure for testing
EXAMPLE_CONNECT_EVENT = {
    "Details": {
        "ContactData": {
            "ContactId": "43f4161d-f2ad-45b9-85c5-cda9519fe4cf",
            "CustomerEndpoint": {"Address": "+12345678901", "Type": "TELEPHONE_NUMBER"},
            "SystemEndpoint": {"Address": "+18005551234", "Type": "TELEPHONE_NUMBER"},
            "Queue": {
                "Name": "BasicQueue",
                "ARN": "arn:aws:connect:us-east-1:123456789012:instance/12345678-1234-1234-1234-123456789012/queue/87654321-4321-4321-4321-210987654321",
            },
            "Attributes": {},
            "Channel": "VOICE",
        }
    }
}

# For local testing
if __name__ == "__main__":
    # Test the function locally
    test_context = type(
        "Context", (), {"function_name": "connect-toxmod-integration", "aws_request_id": "test-request-id"}
    )()

    result = lambda_handler(EXAMPLE_CONNECT_EVENT, test_context)
    print(json.dumps(result, indent=2))
