"""
This module defines functions to interact with the p.defau.lt service for uploading and retrieving code snippets.

Functions:
- get_service_tag(): Returns a string representing the service tag for p.defau.lt.
- upload(data): Uploads a code snippet to p.defau.lt and returns a dictionary containing metadata about the upload.
- get(trace): Retrieves the code snippet associated with the provided trace from p.defau.lt.
"""

import requests
import json
import hashlib

URL = 'https://p.defau.lt/submit.php'
NAME_PREFIX = 'defau_'

def get_service_tag():
    return 'p.defau.lt'

def upload(data):
    json_data = json.dumps(data)
    md5sum = hashlib.md5(json_data.encode('utf-8')).hexdigest()

    try:
        response = requests.post(URL, data={'code': json_data})
        response.raise_for_status()
        key = response.url
        name = f"{NAME_PREFIX}{md5sum[:5]}"
        return {'name': name, 'service': get_service_tag(), 'key': key, 'md5sum': md5sum}
    except requests.exceptions.RequestException as e:
        print(e)
        return None

def get(trace):
    url = trace[key]
    response = requests.request.get(url)
    return response.content

