'''
Created on 12-Jul-2021

@author: bthakur
'''
import random
import inspect
import traceback   #        {inspect.stack()[0][3]}




import re
from sympy import (Eq, symbols, sqrt, latex,
                   Rational, solve, log, nsimplify, E, exp,  
                   sin, cos, I, series, pi)
from sympy.abc import theta
import sympy


from xv.km.util import latex_fraction
from sympy.core.expr import UnevaluatedExpr as ueval

from xv.util import list_to_str, toIntOrFloat, html_list

# _modelling_juice_business_helper
# ModellingJuiceBusinessHelper

from xv.util import UtilClass

class ModellingJuiceBusinessHelper(UtilClass):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        pass



    def get_random_model(self, **kwargs):
        methods = [self.model_juice_business,
                   ]
        
        method = random.choice(methods)
        model_data = method()
        return self.convert_juice_business_data_to_prob_data(model_data)
        pass

    def model_juice_business(self):
        p_names = [
            ['Likhith', 'he'],
            ['Rishitha', 'she']
            ]
        p_name, p_pron = random.choice(p_names)
        
        comp_product = random.choice(["lemonade", "juice"])
        comp_items = ['lemon', 'water', 'sugar']
        comp_unit_qtys = [random.randint(2, 5),
                         random.randint(1, 5) * 100,
                         random.randint(1, 4) * 10,
                         ]
        comp_units = ['piece', 'ml', 'gm']
        comp_rate_units = ['piece', 'litre', 'kg']
        
        unit_conversions = [(1, 1), (1000, 1), (1000, 1)]
        
        
        comp_rate_qtys = [random.choice([1, 2, 6, 10, 12]),
                          random.choice([1, 2, 6, 10, 12]),
                          1
                         ]
        comp_rate_vals = [comp_rate_qtys[0] * random.choice([0.5, 1, 1.5, 2]),
                          comp_rate_qtys[1] * random.choice([1, 2, 3, 4, 5]),
                          random.randint(1, 5),
                         ]
        
        
        currency = random.choice([r"\$"])
        sell_qty = random.choice([random.randint(1, 5) * 100,
                                  random.randint(10, 99) * 10,
                                  ])
        
        model_data = {
            'p_name': p_name,
            'p_pron': p_pron,
            'comp_product': comp_product,
            'comp_items': comp_items,
            'comp_unit_qtys': comp_unit_qtys,
            'comp_rate_qtys': comp_rate_qtys,
            'comp_rate_vals': comp_rate_vals,
            'comp_rate_units': comp_rate_units,
            'comp_units': comp_units,
            'unit_conversions': unit_conversions,
            'currency': currency,
            'sell_qty': sell_qty,
            }
        
        
        cost_data = self.convert_juice_business_data_to_cost_data(model_data)
        model_data.update(cost_data)


        comp_costs = model_data['comp_costs']

        cost_price = toIntOrFloat(sum(comp_costs), roundoff = 2)
        sell_price = cost_price + random.choice([1, 1.5, 2, 2.5, 3, 3,5, 4])
        sell_price = int(round(sell_price, 0))
        
        profit_price = toIntOrFloat(sell_price - cost_price, roundoff = 2)

        profit = toIntOrFloat(sell_qty * profit_price, roundoff = 2)
        
        model_data['cost_price'] = cost_price
        model_data['sell_price'] = sell_price
        model_data['profit_price'] = profit_price
        model_data['profit'] = profit
        
        prob_data = self.convert_juice_business_data_to_prob_data(model_data)
        model_data.update(prob_data)

        return model_data 
        pass
    

    def convert_juice_business_data_to_prob_data(self, model_data):
        p_name = model_data['p_name']
        p_pron = model_data['p_pron']
        comp_product = model_data['comp_product']
        comp_qtys_str = model_data['comp_qtys_str']
        comp_rates_str = model_data['comp_rates_str']
        currency = model_data['currency']
        sell_price = model_data['sell_price']
        sell_qty = model_data['sell_qty']
        profit = model_data['profit']
        sell_qty = model_data['sell_qty']
        comp_costs_str_0 = model_data['comp_costs_str_0']
        comp_costs_str_1 = model_data['comp_costs_str_1']
        comp_costs_str_2 = model_data['comp_costs_str_2']
        comp_costs_str_3 = model_data['comp_costs_str_3']
        comp_costs_str_4 = model_data['comp_costs_str_4']
        comp_costs_str_5 = model_data['comp_costs_str_5']
        cost_price = model_data['cost_price']
        profit_price = model_data['profit_price']
        comp_items = model_data['comp_items']
        comp_costs = model_data['comp_costs']
        
        
        prob_items = []
        
        prob_item = f"""
        {p_name} started a business. 
        {p_pron.capitalize()} sells {comp_product} and for each {comp_product}, 
        {p_pron} uses {comp_qtys_str}. 
        The cost of items are: {comp_rates_str}.
        The sell price of each ${comp_product}$ is ${currency}{sell_price}$. 
        {p_pron.capitalize()} sells ${sell_qty}$ {comp_product} daily.
        """
        prob_items.append(prob_item.replace("\n", " ").strip().strip())

       

        soln_items = []

        soln_item = f"""
        <h3>Let us do some calculation first:</h3>
        Cost per {comp_product}
        
        = {comp_costs_str_0}

        = {comp_costs_str_1}

        = {comp_costs_str_2}

        = {comp_costs_str_3}
        
        = {comp_costs_str_4}
        
        = {comp_costs_str_5}
        
        = $\\displaystyle {currency} {cost_price}$
        """
        soln_items.append(soln_item.strip())
        

        cost_price_latex = latex_fraction(f"{currency}{cost_price}",
                                          f"{comp_product}")

        sell_price_latex = latex_fraction(f"{currency}{sell_price}",
                                          f"{comp_product}")

        profit_price_latex = latex_fraction(f"{currency}{profit_price}",
                                          f"{comp_product}")


        
        soln_item = f"""
        Profit 

        = (sell price) - (cost price)
        
        = $\\displaystyle {sell_price_latex} - {cost_price_latex}$

        = $\\displaystyle {profit_price_latex}$

        = $\\displaystyle {profit_price_latex} * {sell_qty} \\; {comp_product}$

        = $\\displaystyle {currency} {profit}$

        """
        soln_items.append(soln_item.strip())
        
        
        qas = []

        for idx, comp_item in enumerate(comp_items):
            cost_item_latex = latex_fraction(f"{currency}{comp_costs[idx]}",
                                              f"{comp_product}")

            qa = [f"What is cost of {comp_item} per {comp_product}?",
                  f"$\\displaystyle {cost_item_latex}$"
                  ]
            qas.append(qa)
            
            
            tot_item_cost = toIntOrFloat(comp_costs[idx] * sell_qty, roundoff = 2)

            qa = [f"What is the total cost of {comp_item}?",
                  f"""$\\displaystyle 
                  {sell_qty} \\; {comp_product} * {cost_item_latex}  
                  = {currency}{tot_item_cost}
                  $""",
                  f"$\\displaystyle {currency}{tot_item_cost}$",
                  ]
            qas.append(qa)
            pass



        qa = [f"What is cost per {comp_product}?",
              f"$\\displaystyle {cost_price_latex}$"
              ]
        qas.append(qa)


        tot_cost = toIntOrFloat(cost_price * sell_qty, roundoff = 2)
        qa = [f"What is the total cost?",
              f"""$\\displaystyle 
              {sell_qty} \\; {comp_product} * {cost_price_latex} 
              = {currency}{tot_cost}
              $""",
              f"$\\displaystyle {currency}{tot_cost}$",
              ]
        qas.append(qa)

        
        tot_sales = toIntOrFloat(sell_price * sell_qty, roundoff = 2)
        qa = [f"What is the total sales value?",
              f"""$\\displaystyle 
              {sell_qty} \\; {comp_product} * {sell_price_latex}
              = {currency}{tot_sales}
              $""",
              f"$\\displaystyle {currency}{tot_sales}$",
              ]
        qas.append(qa)

        
        qa = [f"What is profit per {comp_product}?",
              f"$\\displaystyle {profit_price_latex}$"
              ]
        qas.append(qa)

        
        qa = [f"What is total profit?",
              f"$\\displaystyle {currency} {profit}$"
              ]
        qas.append(qa)
        
        for qa_idx, qa in enumerate(qas):
            if len(qa) == 2:
                qas[qa_idx].append(qa[1])
            pass
        
        q_html_list = html_list([f"{qa[0]}<br/>" for qa in qas], 
                                list_type = "ol")
        
        a_html_list = html_list([f"{qa[2]}<br/><br/>" for qa in qas], 
                                list_type = "ol")
        
        qa_html_list = html_list([f"{qa[0]}<br/>Answer: {qa[1]}<br/><br/>" for qa in qas], 
                                 list_type = "ol")

        prob_item = f"""
        Answer the following questions:
        {q_html_list}
        """
        prob_items.append(prob_item.strip())

        
        soln_item = f"""
        <h3>Now, we can answer the questions:</h3>
        {qa_html_list}
        """
        soln_items.append(soln_item)
        
        prob_s = "\n".join(prob_items)
        soln_s = "\n\n".join(soln_items)
        
        answer_s = f"{a_html_list}"

        random_model = {
            'prob_s': prob_s,
            'soln_s': soln_s,
            'answer_s': answer_s,
            }
        
        return random_model
        pass

    def convert_juice_business_data_to_cost_data(self, model_data):
        
        comp_items = model_data['comp_items']
        comp_unit_qtys = model_data['comp_unit_qtys']
        comp_rate_qtys = model_data['comp_rate_qtys']
        comp_rate_vals = model_data['comp_rate_vals']
        comp_rate_units = model_data['comp_rate_units']
        comp_units = model_data['comp_units']
        unit_conversions = model_data['unit_conversions']
        currency = model_data['currency']
        
        
        comp_qtys_str = []
        comp_rates_str = []
        
        comp_costs = []
        comp_costs_str_0 = []
        comp_costs_str_1 = []
        comp_costs_str_2 = []
        comp_costs_str_3 = []
        comp_costs_str_4 = []
        
        for idx, comp_item in enumerate(comp_items):
            qty_unit = f""" {comp_unit_qtys[idx]} \\; {comp_units[idx]}  """
            rate_unit = f""" {comp_rate_qtys[idx]} \\; {comp_rate_units[idx]}  """
            rate_val = f""" {currency}{comp_rate_vals[idx]}  """
            
            u_conv = unit_conversions[idx]
            
            cost_num = comp_unit_qtys[idx] * comp_rate_vals[idx]
            cost_den = comp_rate_qtys[idx]

            temp_num = f"{comp_unit_qtys[idx]} * {comp_rate_vals[idx]}"
            temp_den = f"{comp_rate_qtys[idx]}"
            
            if comp_rate_units[idx] != comp_units[idx]:
                comp_cost = (cost_num / cost_den) * (u_conv[1] / u_conv[0])
                comp_cost_latex = latex_fraction(f"{temp_num} * {u_conv[1]}", 
                                                 f"{temp_den} * {u_conv[0]}")
            else:
                comp_cost = (cost_num / cost_den)
                comp_cost_latex = latex_fraction(f"{temp_num}", 
                                                 f"{temp_den}")
                pass
            
            comp_costs.append(toIntOrFloat(comp_cost, roundoff = 2))
            
            comp_qty_str = f"""$ {qty_unit} \\; {comp_item} $ """
            comp_qtys_str.append(comp_qty_str.strip())
                          
            term1 = f""" {qty_unit} \\;{comp_item} """
            
            comp_rate_str = f""" 
                          {rate_unit} \\; {comp_item}
                          \\text{{ for }}
                          {rate_val}
                        """
            comp_rates_str.append(f"${comp_rate_str.strip()}$")
                          
            comp_cost_str_0 = f""" 
                          \\left(
                          {term1}  
                          \\right)
                           """
            comp_costs_str_0.append(f"$\\displaystyle {comp_cost_str_0.strip()} $")
                          
            
            comp_cost_str_1 = f""" 
                          \\left(
                          {term1}  
                          \\right)
                          * 
                          \\left(
                          {comp_rate_str}
                          \\right)
                           """
            comp_costs_str_1.append(f"$\\displaystyle {comp_cost_str_1.strip()} $")
                          
            
            comp_rate_latex = latex_fraction(f"{currency}{comp_rate_vals[idx]}", 
                                             f"""
                                             {comp_rate_qtys[idx]} \\; 
                                              {comp_rate_units[idx]} \\;
                                              {comp_item}   
                                             """)
            
            comp_cost_str_2 = f"""
                          \\left(
                          {term1}  
                          \\right)
                          * 
                          \\left(
                          {comp_rate_latex}
                          \\right)
                          """
            comp_costs_str_2.append(f"""$\\displaystyle {comp_cost_str_2}$ """.strip())
            
            
            comp_cost_str_3 = comp_cost_str_2
            if comp_rate_units[idx] != comp_units[idx]:
                u_conv_latex = latex_fraction(f"""
                                                 {u_conv[1]} \\; 
                                                 {comp_rate_units[idx]} 
                                                 """,
                                                 f"""
                                                 {u_conv[0]} \\; 
                                                 {comp_units[idx]}
                                                 """
                                              )
                
                comp_cost_str_3 = f"""{comp_cost_str_3}
                              * \\left({u_conv_latex}  \\right)"""
                pass
                          
            comp_costs_str_3.append(f"""$\\displaystyle {comp_cost_str_3}$ """.strip())
            
            
            comp_cost_str_4 = f"{comp_cost_latex}"
            comp_costs_str_4.append(f"""{comp_cost_str_4} """.strip())
            
            pass
        
        comp_qtys_str = list_to_str(comp_qtys_str, last_sep = 'and ')
        comp_rates_str = list_to_str(comp_rates_str, last_sep = 'and ')
        comp_costs_str_0 = list_to_str(comp_costs_str_0, sep = ' + ')
        comp_costs_str_1 = list_to_str(comp_costs_str_1, sep = '<br/> + ')
        comp_costs_str_2 = list_to_str(comp_costs_str_2, sep = '<br/> + ')
        comp_costs_str_3 = list_to_str(comp_costs_str_3, sep = '<br/> + ')
        
        comp_costs_str_4 = list_to_str(comp_costs_str_4, sep = ' + ')
        comp_costs_str_4 = f"""
                            $\\displaystyle 
                            {currency} \\left( 
                            {comp_costs_str_4}
                            \\right)
                            $ 
                            """.strip()
        
        comp_costs_str_5 = list_to_str(comp_costs, sep = ' + ')
        comp_costs_str_5 = f"""
                            $\\displaystyle 
                            {currency} \\left( 
                            {comp_costs_str_5}
                            \\right)
                            $ 
                            """.strip()
                            
        cost_data = {
            'comp_qtys_str': comp_qtys_str,
            'comp_rates_str': comp_rates_str,

            'comp_costs': comp_costs,

            'comp_costs_str_0': comp_costs_str_0,
            'comp_costs_str_1': comp_costs_str_1,
            'comp_costs_str_2': comp_costs_str_2,
            'comp_costs_str_3': comp_costs_str_3,
            'comp_costs_str_4': comp_costs_str_4,
            'comp_costs_str_5': comp_costs_str_5,
            }
        
        return cost_data
        pass
    
    
    pass
#class ModellingJuiceBusinessHelper:
