"""Functions for creating tickets"""

import os
import platform
import pwd
import requests

TIMEOUT = 30


class TicketError(RuntimeError):
    """When creating a ticket failed on the relay side"""

    __module__ = 'rads'


def make_ticket(
    dest: str,
    subject: str,
    body: str,
    sender: str | None = None,
    timeout=TIMEOUT,
):
    """Create a ticket through the ticket relay

    Args:
        sender (str): who created the ticket. Defaults to currentuser@fqdn
        dest (str): ticket queue (e.g. str@imhadmin.net)
        body (str): ticket body

    Raises:
        TicketError: creating a ticket failed on the relay side
        requests.RequestException: errors contacting ticketrelay
    """
    if not sender:
        fqdn = platform.node()
        # zendesk will reject the ticket if the server's hostname isn't set
        # to an actual FQDN
        if '.' not in fqdn:
            fqdn = f"{fqdn}.local"
        sender = f'{pwd.getpwuid(os.getuid()).pw_name}@{fqdn}'
    req = requests.post(
        "https://ticketrelay.imhadmin.net/create_ticket",
        headers={
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        timeout=timeout,
        json={"sender": sender, "subject": subject, "dest": dest, "body": body},
    ).json()
    if req['error']:
        raise TicketError(req['error'])


make_ticket.__module__ = 'rads'
