import json
import requests
import logging
from django.http import HttpResponse, JsonResponse

# Set up logging
logger = logging.getLogger(__name__)

# Set the base URL for the Splunk SOAR instance
REST_BASE_URL = 'https://x.x.x.x/'  # Replace with your Splunk SOAR instance URL

def _get_auth_token_from_request(request):
    """Parse authentication information from request headers."""
    auth_token = request.META.get('HTTP_PH_AUTH_TOKEN')
    if not auth_token:
        logger.warning('No auth token found in request')
        raise Exception('Invalid request. Please use "ph-auth-token" to authenticate the request')
    logger.warning('Auth token retrieved successfully')
    return auth_token

def handle_request(request, path_parts=None):
    """REST handler function to parse specific fields from JSON payload."""
    logger.warning('Handling request')
    try:
        data = json.loads(request.body.decode('utf-8'))
        logger.warning('Request data parsed successfully')

        # Parse the test data fields and static field mapping from SupernaZT to Splunk Soar schema located here https://docs.splunk.com/Documentation/SOARonprem/6.1.1/PlatformAPI/RESTContainers
        container_data = {
            "username": data.get("userName", ""),
            "sid": data.get("user", ""),
            "severity": "high", # "severity": data.get("severity",""),
            "protocol": data.get("protocol", ""),
            "kill_chain": "Exploitation", # static mapping choices are Reconnaissance, Weaponization, Delivery, Exploitation, Installation, Command & Control ,Actions on Objectives
            "sensitivity": "red", #static mapping to red
            "source_data_identifier": data.get("id", ""), #set the event id in Superna = to the container ID in splunk to correclate between the systems
            "files": data.get("files", []),
            "nes": data.get("nes", []),
            "shares": data.get("shares", []),
            "name": "Superna Security Event", #static mapping
            "description": "Superna Security Edition Ransomware event detection",
            "label": "events" #static mapping to type event
        }
        logger.warning(f'Parsed container data: {container_data}')

        # Headers for Splunk SOAR API requests
        headers = {'ph-auth-token': _get_auth_token_from_request(request)}

        # URL for creating a container in Splunk SOAR
        url = f"{REST_BASE_URL}rest/container/"
        logger.warning(f'Sending request to Splunk SOAR API at {url}')

        # Making a POST request to Splunk SOAR API to create a container
        response = requests.post(url, json=container_data, headers=headers, verify=False)
        if response.status_code in [200, 201]:
            logger.warning('Container created successfully in Splunk SOAR')
            container_info = {"message": "Container created successfully", "container_id": response.json().get("id")}
            logger.warning(f'Container Info: {json.dumps(container_info)}')  # Logging the container info
            container_id = response.json().get("id")  # Get the container ID from the response
            create_artifacts(container_id, data, headers)  # Call to create artifacts
            return
        else:
            logger.warning(f'Failed to create container. Status: {response.status_code}, Response: {response.text}')
            return HttpResponse(f"Failed to create container. Status: {response.status_code}, Response: {response.text}", status=response.status_code)

    except json.JSONDecodeError as e:
        logger.warning(f"JSON Decode Error: {str(e)}")
        return HttpResponse(f"Error in parsing JSON data: {str(e)}", status=400, content_type='text/plain')
    except Exception as e:
        logger.warning(f"Error processing request: {str(e)}")
        return HttpResponse(f"Error processing request: {str(e)}", status=500, content_type='text/plain')



def create_artifacts(container_id, data, headers):
    """Function to create artifacts for the given container."""
    artifacts_url = f"{REST_BASE_URL}rest/artifact/"
    artifacts_data = []

    # Fields to create artifacts for - find field names in sample json payload to extract from webhook and include in the artifact creation
    fields = ["clientIPs", "userName", "user", "protocol", "state","shares","files","nes","clients","numfiles","snapshots","nfsProtocols"]

    for field in fields:
        if field in data:
            artifact = {
                "container_id": container_id,
                "data": {field: data[field]},
                "label": field,
                "source_data_identifier": f"{field}-{data[field]}",
                "name": f"{field.capitalize()} Artifact"
            }
            artifacts_data.append(artifact)

    # Creating artifacts in Splunk SOAR
    for artifact in artifacts_data:
        response = requests.post(artifacts_url, json=artifact, headers=headers, verify=False)
        if response.status_code not in [200, 201]:
            logger.warning(f'Failed to create artifact. Status: {response.status_code}, Response: {response.text}')



        # After container creation
        if response.status_code in [200, 201]:
            container_id = response.json().get("id")
            create_artifacts(container_id, data, headers)
            # ... [rest of the success response handling] ...
