import textwrap


def _json_to_bibtex(data):
    """Make a bibtex entry from CMIP6 Data Citation json data."""
    url = 'url not found'
    title = data.get('titles', ['title not found'])[0]
    publisher = data.get('publisher', 'publisher not found')
    year = data.get('publicationYear', 'publicationYear not found')
    authors = 'creators not found'
    doi = 'doi not found'

    if 'creators' in data:
        author_list = [
            item.get('creatorName', '') for item in data['creators']
        ]
        authors = ' and '.join(author_list)
        if not authors:
            authors = 'creators not found'

    if 'identifier' in data:
        doi = data['identifier'].get('id', 'doi not found')
        url = f'https://doi.org/{doi}'

    bibtex_entry = textwrap.dedent(f"""
        @misc{{{url},
        \turl = {{{url}}},
        \ttitle = {{{title}}},
        \tpublisher = {{{publisher}}},
        \tyear = {year},
        \tauthor = {{{authors}}},
        \tdoi = {{{doi}}},
        }}
        """).lstrip()
    return bibtex_entry