# -*- coding: utf-8 -*-
import dataiku
import pandas as pd, numpy as np
from dataiku import pandasutils as pdu

# Read recipe inputs
topics_keywords_agg_windows = dataiku.Dataset("topics_keywords_agg_windows")
topics_keywords_agg_windows_df = topics_keywords_agg_windows.get_dataframe()


topics_keywords_agg_windows_df = topics_keywords_agg_windows_df.rename(columns={"llm_rating_avg": "2. Topic Rating", "keywords": "1. Keyword", "count": "3. # occurences"})

topics_keywords_agg_windows_df["2. Topic Rating"] = topics_keywords_agg_windows_df["2. Topic Rating"].apply(lambda rating:np.round(rating,2))

table = pd.pivot(topics_keywords_agg_windows_df, values=['1. Keyword', "2. Topic Rating","3. # occurences"], index='rownumber',

                       columns=['topic_name']).swaplevel(axis=1)

table.columns = table.columns.map(' | '.join).str.strip('|')
top_keywords_pivoted_df = table.reindex(sorted(table.columns), axis=1)


# Write recipe outputs
top_keywords_pivoted = dataiku.Dataset("top_keywords_pivoted")
top_keywords_pivoted.write_with_schema(top_keywords_pivoted_df)
