# -------------------------------------------------------------------------------- NOTEBOOK-CELL: CODE
# -*- coding: utf-8 -*-
import dataiku
import pandas as pd, numpy as np
from dataiku import pandasutils as pdu
from html_template import template_email
from commons.python.dku_utils.core import get_current_project_and_variables

# Read recipe inputs
conclusion = dataiku.Dataset("conclusion")
conclusion_df = conclusion.get_dataframe()

# -------------------------------------------------------------------------------- NOTEBOOK-CELL: CODE
project, variables = get_current_project_and_variables()
value = variables['standard']['value']

# -------------------------------------------------------------------------------- NOTEBOOK-CELL: CODE
categories = conclusion_df['category'].unique()

# -------------------------------------------------------------------------------- NOTEBOOK-CELL: CODE
client = dataiku.api_client()
instance_url = client.get_general_settings().get_raw().get('studioExternalUrl')
project_key = project.project_key
historical_dashboard_url = instance_url + '/projects/' + project_key + '/dashboards/j4Pjdob_financial-forecasting-dashboard/view/Xm7cZR7'
forecast_dashboard_url = instance_url + '/projects/' + project_key + '/dashboards/j4Pjdob_financial-forecasting-dashboard/view/VjukuwQ'

# -------------------------------------------------------------------------------- NOTEBOOK-CELL: CODE
emails = dict()

# Write recipe outputs
reports = dataiku.Folder("MUYvkF60")

for category in categories:
    conclusions = conclusion_df.loc[conclusion_df['category']==category]
    emails[category] = template_email
    emails[category] = emails[category].replace('[Value]', value.capitalize())
    emails[category] = emails[category].replace('[value]', value)
    emails[category] = emails[category].replace('[Business Unit]', category)
    emails[category] = emails[category].replace('[Results Analysis]', conclusions['result_analysis'].iloc[0])
    emails[category] = emails[category].replace('[Drivers Analysis]', conclusions['driver_analysis'].iloc[0])
    emails[category] = emails[category].replace('[Value Projection]', conclusions['prediction_analysis'].iloc[0])
    emails[category] = emails[category].replace('[Drivers Assumptions]', conclusions['drivers_assumptions'].iloc[0])
    emails[category] = emails[category].replace('[Conclusion]', conclusions['llm_output'].iloc[0])
    emails[category] = emails[category].replace('[Historical Dashboard]', historical_dashboard_url)
    emails[category] = emails[category].replace('[Forecast Dashboard]', forecast_dashboard_url)

for category in categories:
    with reports.get_writer(category + '_email.html') as f:
        f.write(emails[category].encode())