import pandas as pd


def read_wos(
    path: str,
    encoding: str = "utf-8"
) -> pd.DataFrame:
    """Converts a .txt file generated by Clarivate Web of Science into a Pandas DataFrame.

    Parameters
    ----------
    path : str
        Path
    encoding : str, optional
        Encoding, by default "utf-8"

    Returns
    -------
    pd.DataFrame
        A pandas DataFrame
    """

    data = open(path, "r", encoding=encoding)
    output = []

    # Defines initial variables
    article = {}
    last_valid_item = None

    for line in data:
        item = line[0:2].strip()    # Two-characters code
        content = line[3:].strip()  # Content associated to the variable

        # Each article is separated by \n
        if line == "\n":
            if article:
                output.append(article)
            article = {}

        elif item != "":
            last_valid_item = item
            if item in ["AF", "AU", "BE", "C1", "CR", "ID"]:
                article[item] = [content]
            else:
                article[item] = content

        elif item == "" and line != "\n":
            if last_valid_item in ["AB", "C3", "CT", "DE", "EM", "FU", "FX", "OI", "PA", "RI", "SC", "SO", "TI", "WC"]:
                article[last_valid_item] = article[last_valid_item] + \
                    " " + content
            else:
                article[last_valid_item] = article[last_valid_item] + [content]

    return pd.DataFrame(output)
