import requests


def query_crossref_with_citation_list(query, score_threshold = 60.0, verbose=False):
    """
    Query crossref with the input plain text query.
    Parameters
    ----------
    query: str
        Plain text query, usually all the fields from the parser are joint
        (see extract_citation_list_from_pdf.query_from_citation_list)
    score_threshold: float
        Threshold to accept the first match.
        It is data (query and target match) dependant.
    verbose: bool
        print extra info to stdout

    Returns
    -------
    Tuple[score (Float), doi (Str)]
        Returns the score of the first match. If the score is higher than
        input threshold and the match has a DOI field, returns the DOI. Otherwise the doi would be None.
    """
    url_crossref = "https://api.crossref.org/works"
    payload = {'query.bibliographic' : query}

    if not query.strip():
        raise Exception("Input query is empty")
    r = requests.get(url_crossref, params=payload)
    # Will raise if not ok (status_code == requests.codes.ok (i.e 200))
    r.raise_for_status()

    if verbose:
        print(r.url)

    response = r.json()
    try:
        first_item = response["message"]["items"][0]
    except IndexError:
        print("QUERY is too short, ignoring.")
        first_score = 0
        return first_score, None

    first_score = first_item["score"]
    has_doi = "DOI" in first_item
    if has_doi:
        first_doi = first_item["DOI"]
    else:
        first_doi = None

    if verbose:
        print("SCORE FIRST: ", first_score)
        if "title" in first_item:
            print("TITLE FIRST: ", first_item["title"][0])

    # second_item = response["message"]["items"][1]
    if first_score >= score_threshold and first_doi:
        return first_score, first_doi

    return first_score, None