import pandas as pd
import numpy as np
import os
import glob
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from babel.numbers import format_number
# dict_summary={"top3":[],"bottom3":[]}

fig_size_ds_w, fig_size_ds_h = 10, 6 # width and height of distribution graphs 
fig_size_tr_w, fig_size_tr_h = 8, 6 # width and height of trend graphs

# to read all raw data csv files
def read_all_csv(path='./rawdata_csv/', extension='csv'):
    result = glob.glob(path+'SRC_R*.{}'.format(extension))
    df=None
    
    for file in result:
        if(df is None):
            df=pd.read_csv(file)
        else:
            df=pd.concat([df,pd.read_csv(file)], ignore_index=True)
    
    df_master=pd.read_csv("SRC_MasterData.csv")
    df_master=df_master[['State_Code','State_Name','Total_Population']]
    final_df = pd.merge(df, df_master, on='State_Code', how='inner')
    final_df['total']=final_df[['Primary_Only','Primary_with_Upper_Primary','Primary with_Upper_Primary_Sec_H.Sec','Upper_Primary_Only','Upper_Primary_with_Sec_H.Sec','Primary_with_Upper_Primary_Sec','Upper_Primary_with_Sec']].sum(axis=1)
    final_df['total_by_population']=final_df['total']/final_df['Total_Population']
    final_df=final_df[["Year","State_Name","State_Code","Main_Dimension","Sub_Dimension","Total_Population",'total','total_by_population']]

    return final_df

# to plot statewise distribution graphs
def statewise_distribution(output_filename, input_df, year, ylabel, main_dimension, sub_dimension=''):
    dict_summary={"top3":[],"bottom3":[]}
    if sub_dimension:
        df_filtered = input_df.loc[(input_df['Main_Dimension'] == main_dimension) & ((input_df['Sub_Dimension'] == sub_dimension))]
    else:
        df_filtered = input_df.loc[(input_df['Main_Dimension'] == main_dimension)]
    df_filtered = df_filtered.loc[df_filtered['Year'] == year]
    df_filtered = df_filtered[['Year','State_Name','total','total_by_population']]
    df_sum = df_filtered.groupby(['State_Name','Year'],as_index = False).sum().sort_values("total_by_population",ascending=False)
    
    fig = plt.figure(figsize=(fig_size_ds_w,fig_size_ds_h))
    if 'Facilities' in main_dimension:
        dim = 'Dimension'
    elif 'Qualification' in main_dimension:
        dim = 'Educational Qualification'
    elif 'Classroom' in main_dimension:
        dim = 'Condition'
    else:
        dim = 'Category'
    label='Year: ' + str(year) + ', ' + dim + ': ' + sub_dimension
    plt.title(label=label, fontweight='bold', fontsize=10, fontstyle='italic')
    # plt.xticks(rotation=90, ha="right", fontsize=10)
    plt.yticks(fontsize=7)
    # plt.bar(df_sum['State_Name'],df_sum['total_by_population'], align='center')
    plt.barh(df_sum['State_Name'], df_sum['total_by_population'],align='center')
    # plt.ylabel(ylabel)
    plt.xlabel(ylabel)
    list_states=list(df_sum['State_Name'])
    dict_summary['top3']=[list_states[0],list_states[1],list_states[2]]
    dict_summary['bottom3']=[list_states[-1],list_states[-2],list_states[-3]]
    plt.savefig(output_filename)
    plt.close(fig)
    
    return dict_summary

# to plot trend graph for enrolments
def total_enrolment_by_category(output_filename, input_df, main_dimension, state_code, ylabel):
    fig = plt.figure(figsize=(fig_size_tr_w,fig_size_tr_h))
    df_fil = input_df.loc[input_df['Main_Dimension'] == main_dimension]
    df_fil = df_fil.loc[(df_fil['State_Code'] == state_code)]
    state_name = list(set(df_fil['State_Name']))[0]
    min_year, max_year = min(df_fil['Year']), max(df_fil['Year'])
    df_sum = df_fil.groupby(['Sub_Dimension','State_Code','Year'],as_index = False).sum()
    df_sum = df_sum[['Sub_Dimension','State_Code','Year','total']]
    
    df_govt=df_sum.loc[(df_sum['Sub_Dimension'] == "Government")]
    df_pvt=df_sum.loc[(df_sum['Sub_Dimension'] == "Private")]
    plt.plot(df_govt['Year'],df_govt['total'],marker='o',color='r', label='Goverment')
    for x, y in zip(df_govt['Year'],df_govt['total']):
        plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='r', rotation=15, fontsize=7, weight='bold')
    plt.plot(df_pvt['Year'],df_pvt['total'],marker='+',color='g', label='Private')
    for x, y in zip(df_pvt['Year'],df_pvt['total']):
        plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='g', rotation=15, fontsize=7, weight='bold')
    
    if not 'Rural' in main_dimension:
        df_madr=df_sum.loc[(df_sum['Sub_Dimension'] == "Madrasas & Unrecognised")]
        plt.plot(df_madr['Year'],df_madr['total'],marker='*',color='b', label='Madrasas')
        for x, y in zip(df_madr['Year'],df_madr['total']):
            plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='b', rotation=15, fontsize=7, weight='bold')
    
    plt.legend()
    plt.title(label='State: ' + state_name + ', Type: ' + main_dimension, fontweight='bold', fontsize=10, fontstyle='italic')
    plt.xticks(np.arange(min_year, max_year+1, 1.0))
    plt.ylabel(ylabel)
    plt.xlabel('Year')
    plt.savefig(output_filename)
    plt.close(fig)

# to plot trend graph for teachers
def total_teachers_by_main_dimension(output_filename, input_df, main_dimension, state_code):
    fig = plt.figure(figsize=(fig_size_tr_w,fig_size_tr_h))
    df_fil = input_df.loc[input_df['Main_Dimension'] == main_dimension]
    df_fil = df_fil.loc[(df_fil['State_Code'] == state_code)]
    state_name = list(set(df_fil['State_Name']))[0]
    min_year, max_year = min(df_fil['Year']), max(df_fil['Year'])
    df_sum = df_fil.groupby(['Sub_Dimension','State_Code','Year'],as_index = False).sum()
    df_sum = df_sum[['Sub_Dimension','State_Code','Year','total']]
    
    if 'Category' in main_dimension:
        df_govt = df_sum.loc[(df_sum['Sub_Dimension'] == "Government")]
        df_pvt = df_sum.loc[(df_sum['Sub_Dimension'] == "Private")]
        df_madr = df_sum.loc[(df_sum['Sub_Dimension'] == "Madrasas & Unrecognised")]
        
        plt.plot(df_govt['Year'],df_govt['total'],marker='o',color='r', label='Goverment')
        for x, y in zip(df_govt['Year'],df_govt['total']):
            plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='r', rotation=15, fontsize=7, weight='bold')
        plt.plot(df_pvt['Year'],df_pvt['total'],marker='+',color='g', label='Private')
        for x, y in zip(df_pvt['Year'],df_pvt['total']):
            plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='g', rotation=15, fontsize=7, weight='bold')
        plt.plot(df_madr['Year'],df_madr['total'],marker='*',color='b', label='Madrasas')
        for x, y in zip(df_madr['Year'],df_madr['total']):
            plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='b', rotation=15, fontsize=7, weight='bold')
    else:
        df_bel_sec = df_sum.loc[(df_sum['Sub_Dimension'] == "Below Secondary")]
        df_sec = df_sum.loc[(df_sum['Sub_Dimension'] == "Secondary")]
        df_hs = df_sum.loc[(df_sum['Sub_Dimension'] == "Higher Secondary")]
        df_grad = df_sum.loc[(df_sum['Sub_Dimension'] == "Graduate")]
        df_pg = df_sum.loc[(df_sum['Sub_Dimension'] == "Post Graduate")]
        df_phd = df_sum.loc[(df_sum['Sub_Dimension'] == "M.Phil / Ph.D")]

        plt.plot(df_bel_sec['Year'],df_bel_sec['total'], marker='o', color='r', label='Below Secondary')
        for x, y in zip(df_bel_sec['Year'],df_bel_sec['total']):
            plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='r', rotation=15, fontsize=7, weight='bold')
        plt.plot(df_sec['Year'],df_sec['total'], marker='+', color='g', label='Secondary')
        for x, y in zip(df_sec['Year'],df_sec['total']):
            plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='g', rotation=15, fontsize=7, weight='bold')
        plt.plot(df_hs['Year'],df_hs['total'], marker='*', color='b', label='Higher Secondary')
        for x, y in zip(df_hs['Year'],df_hs['total']):
            plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='b', rotation=15, fontsize=7, weight='bold')
        plt.plot(df_grad['Year'],df_grad['total'], marker='d', color='y', label='Graduate')
        for x, y in zip(df_grad['Year'],df_grad['total']):
            plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='y', rotation=15, fontsize=7, weight='bold')
        plt.plot(df_pg['Year'],df_pg['total'], marker='s', color='c', label='Post Graduate')
        for x, y in zip(df_pg['Year'],df_pg['total']):
            plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='c', rotation=15, fontsize=7, weight='bold')
        plt.plot(df_phd['Year'],df_phd['total'], marker='x', color='m', label='M.Phil / Ph.D')
        for x, y in zip(df_phd['Year'],df_phd['total']):
            plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='m', rotation=15, fontsize=7, weight='bold')

    plt.legend()
    plt.title(label='State: ' + state_name + ', Type: ' + main_dimension, fontweight='bold', fontsize=10, fontstyle='italic')
    plt.xticks(np.arange(min_year, max_year+1, 1.0))
    plt.ylabel('Number of Teachers')
    plt.xlabel('Year')
    plt.savefig(output_filename)
    plt.close(fig)

# to plot trend graph for classrooms
def total_classrooms_by_trend(output_filename, input_df, state_code):
    fig = plt.figure(figsize=(fig_size_tr_w,fig_size_tr_h))
    df_fil=input_df.loc[input_df['Main_Dimension'] == "Total Classrooms"]
    df_fil=df_fil.loc[(df_fil['State_Code'] == state_code)]
    state_name = list(set(df_fil['State_Name']))[0]
    min_year, max_year = min(df_fil['Year']), max(df_fil['Year'])
    df_sum = df_fil.groupby(['Sub_Dimension','State_Code','Year'],as_index = False).sum()
    df_sum = df_sum[['Sub_Dimension','State_Code','Year','total']]

    df_good_cond = df_sum.loc[(df_sum['Sub_Dimension'] == "Good Condition")]
    df_minor_repair = df_sum.loc[(df_sum['Sub_Dimension'] == "Need Minor Repair")]
    df_major_repair = df_sum.loc[(df_sum['Sub_Dimension'] == "Need Major Repair")]
    
    plt.plot(df_good_cond['Year'],df_good_cond['total'],marker='o',color='r', label='Good Condition')
    for x, y in zip(df_good_cond['Year'],df_good_cond['total']):
        plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='r', rotation=15, fontsize=7, weight='bold')
    plt.plot(df_minor_repair['Year'],df_minor_repair['total'],marker='+',color='g', label='Need Minor Repair')
    for x, y in zip(df_minor_repair['Year'],df_minor_repair['total']):
        plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='g', rotation=15, fontsize=7, weight='bold')
    plt.plot(df_major_repair['Year'],df_major_repair['total'],marker='*',color='b', label='Need Major Repair')
    for x, y in zip(df_major_repair['Year'],df_major_repair['total']):
        plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='b', rotation=15, fontsize=7, weight='bold')

    plt.legend()
    plt.title(label='State: ' + state_name, fontweight='bold', fontsize=10, fontstyle='italic')
    plt.xticks(np.arange(min_year, max_year+1, 1.0))
    plt.ylabel('Number of Classrooms')
    plt.xlabel('Year')
    plt.savefig(output_filename)
    plt.close(fig)

# to plot trend graph for facilities
def total_schools_for_facilities(output_filename, input_df, state_code):
    fig = plt.figure(figsize=(fig_size_tr_w,fig_size_tr_h))
    df_fil=input_df.loc[input_df['Main_Dimension'] == "School Facilities"]
    df_fil=df_fil.loc[(df_fil['State_Code'] == state_code)]
    state_name = list(set(df_fil['State_Name']))[0]
    min_year, max_year = min(df_fil['Year']), max(df_fil['Year'])
    df_sum = df_fil.groupby(['Sub_Dimension','State_Code','Year'],as_index = False).sum()
    df_sum = df_sum[['Sub_Dimension','State_Code','Year','total']]
    
    # df_enrolment_lt_50 = df_sum.loc[(df_sum['Sub_Dimension'] == "Enrolment <= 50")]
    df_drinking_water = df_sum.loc[(df_sum['Sub_Dimension'] == "Schools with Drinking Water")]
    df_girls_toilet = df_sum.loc[(df_sum['Sub_Dimension'] == "Schools with Girls' Toilet")]
    # df_ramp = df_sum.loc[(df_sum['Sub_Dimension'] == "Schools with Ramp")]
    df_single_classroom = df_sum.loc[(df_sum['Sub_Dimension'] == "Single Classroom Schools")]
    df_single_teacher = df_sum.loc[(df_sum['Sub_Dimension'] == "Single Teacher Schools")]
    
    # plt.plot(df_enrolment_lt_50['Year'], df_enrolment_lt_50['total'], marker='o', color='r', label='Enrolment <= 50')
    # for x, y in zip(df_enrolment_lt_50['Year'],df_enrolment_lt_50['total']):
    #     plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='r', rotation=15, fontsize=7, weight='bold')
    plt.plot(df_drinking_water['Year'], df_drinking_water['total'], marker='+', color='g', label='Schools with Drinking Water')
    for x, y in zip(df_drinking_water['Year'],df_drinking_water['total']):
        plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='g', rotation=15, fontsize=7, weight='bold')
    plt.plot(df_girls_toilet['Year'], df_girls_toilet['total'], marker='*', color='b', label='Schools with Girls\' Toilet')
    for x, y in zip(df_girls_toilet['Year'],df_girls_toilet['total']):
        plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='b', rotation=15, fontsize=7, weight='bold')
    # plt.plot(df_ramp['Year'], df_ramp['total'], marker='d', color='y', label='Schools with Ramp')
    # for x, y in zip(df_ramp['Year'],df_ramp['total']):
    #     plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='y', rotation=15, fontsize=7, weight='bold')
    plt.plot(df_single_classroom['Year'], df_single_classroom['total'], marker='s', color='c', label='Single Classroom Schools')
    for x, y in zip(df_single_classroom['Year'],df_single_classroom['total']):
        plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='c', rotation=15, fontsize=7, weight='bold')
    plt.plot(df_single_teacher['Year'], df_single_teacher['total'], marker='x', color='m', label='Single Teacher Schools')
    for x, y in zip(df_single_teacher['Year'],df_single_teacher['total']):
        plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='m', rotation=15, fontsize=7, weight='bold')

    plt.legend()
    plt.title(label='State: ' + state_name, fontweight='bold', fontsize=10, fontstyle='italic')
    plt.xticks(np.arange(min_year, max_year+1, 1.0))
    plt.ylabel('Number of Schools')
    plt.xlabel('Year')
    plt.savefig(output_filename)
    plt.close(fig)

# to plot trend graph by main_dimension for index page
def main_dimension_overall(output_filename, input_df, main_dimension, ylabel):
    fig = plt.figure(figsize=(fig_size_tr_w,fig_size_tr_h))
    df_fil=input_df.loc[input_df['Main_Dimension'] == main_dimension]
    min_year, max_year = min(df_fil['Year']), max(df_fil['Year'])
    df_sum = df_fil.groupby(['Sub_Dimension','Year'],as_index = False).sum()
    df_sum = df_sum[['Sub_Dimension','Year','total']]

    if 'Classrooms' not in main_dimension:
        df_govt=df_sum.loc[(df_sum['Sub_Dimension'] == "Government")]
        df_pvt=df_sum.loc[(df_sum['Sub_Dimension'] == "Private")]
        df_madr=df_sum.loc[(df_sum['Sub_Dimension'] == "Madrasas & Unrecognised")]
        plt.plot(df_govt['Year'],df_govt['total'],marker='o',color='r', label='Goverment')
        for x, y in zip(df_govt['Year'],df_govt['total']):
            plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='r', rotation=15, fontsize=7, weight='bold')
        plt.plot(df_pvt['Year'],df_pvt['total'],marker='+',color='g', label='Private')
        for x, y in zip(df_pvt['Year'],df_pvt['total']):
            plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='g', rotation=15, fontsize=7, weight='bold')
        plt.plot(df_madr['Year'],df_madr['total'],marker='*',color='b', label='Madrasas')
        for x, y in zip(df_madr['Year'],df_madr['total']):
            plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='b', rotation=15, fontsize=7, weight='bold')
    else:
        df_good_cond = df_sum.loc[(df_sum['Sub_Dimension'] == "Good Condition")]
        df_minor_repair = df_sum.loc[(df_sum['Sub_Dimension'] == "Need Minor Repair")]
        df_major_repair = df_sum.loc[(df_sum['Sub_Dimension'] == "Need Major Repair")]
        plt.plot(df_good_cond['Year'],df_good_cond['total'],marker='o',color='r', label='Good Condition')
        for x, y in zip(df_good_cond['Year'],df_good_cond['total']):
            plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='r', rotation=15, fontsize=7, weight='bold')
        plt.plot(df_minor_repair['Year'],df_minor_repair['total'],marker='+',color='g', label='Need Minor Repair')
        for x, y in zip(df_minor_repair['Year'],df_minor_repair['total']):
            plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='g', rotation=15, fontsize=7, weight='bold')
        plt.plot(df_major_repair['Year'],df_major_repair['total'],marker='*',color='b', label='Need Major Repair')
        for x, y in zip(df_major_repair['Year'],df_major_repair['total']):
            plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='b', rotation=15, fontsize=7, weight='bold')
    
    plt.legend()
    plt.title(label='KPI: ' + ylabel, fontweight='bold', fontsize=10, fontstyle='italic')
    plt.xticks(np.arange(min_year, max_year+1, 1.0))
    plt.ylabel(ylabel)
    plt.xlabel('Year')
    plt.savefig(output_filename)
    plt.close(fig)

# to plot trend graph by school facilities for index page
def total_schools_for_facilities_overall(output_filename, input_df):
    fig = plt.figure(figsize=(fig_size_tr_w,fig_size_tr_h))
    df_fil=input_df.loc[input_df['Main_Dimension'] == "School Facilities"]
    min_year, max_year = min(df_fil['Year']), max(df_fil['Year'])
    df_sum = df_fil.groupby(['Sub_Dimension','Year'],as_index = False).sum()
    df_sum = df_sum[['Sub_Dimension','Year','total']]
    
    # df_enrolment_lt_50 = df_sum.loc[(df_sum['Sub_Dimension'] == "Enrolment <= 50")]
    df_drinking_water = df_sum.loc[(df_sum['Sub_Dimension'] == "Schools with Drinking Water")]
    df_girls_toilet = df_sum.loc[(df_sum['Sub_Dimension'] == "Schools with Girls' Toilet")]
    # df_ramp = df_sum.loc[(df_sum['Sub_Dimension'] == "Schools with Ramp")]
    df_single_classroom = df_sum.loc[(df_sum['Sub_Dimension'] == "Single Classroom Schools")]
    df_single_teacher = df_sum.loc[(df_sum['Sub_Dimension'] == "Single Teacher Schools")]

    # plt.plot(df_enrolment_lt_50['Year'], df_enrolment_lt_50['total'], marker='o', color='r', label='Enrolment <= 50')
    # for x, y in zip(df_enrolment_lt_50['Year'],df_enrolment_lt_50['total']):
    #     plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='r', rotation=15, fontsize=7, weight='bold')
    plt.plot(df_drinking_water['Year'], df_drinking_water['total'], marker='+', color='g', label='Schools with Drinking Water')
    for x, y in zip(df_drinking_water['Year'],df_drinking_water['total']):
        plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='g', rotation=15, fontsize=7, weight='bold')
    plt.plot(df_girls_toilet['Year'], df_girls_toilet['total'], marker='*', color='b', label='Schools with Girls\' Toilet')
    for x, y in zip(df_girls_toilet['Year'],df_girls_toilet['total']):
        plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='b', rotation=15, fontsize=7, weight='bold')
    # plt.plot(df_ramp['Year'], df_ramp['total'], marker='d', color='y', label='Schools with Ramp')
    # for x, y in zip(df_ramp['Year'],df_ramp['total']):
    #     plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='y', rotation=15, fontsize=7, weight='bold')
    plt.plot(df_single_classroom['Year'], df_single_classroom['total'], marker='s', color='c', label='Single Classroom Schools')
    for x, y in zip(df_single_classroom['Year'],df_single_classroom['total']):
        plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='c', rotation=15, fontsize=7, weight='bold')
    plt.plot(df_single_teacher['Year'], df_single_teacher['total'], marker='x', color='m', label='Single Teacher Schools')
    for x, y in zip(df_single_teacher['Year'],df_single_teacher['total']):
        plt.text(x = x, y = y, s = '{:.0f}'.format(y), color='m', rotation=15, fontsize=7, weight='bold')

    plt.legend()
    plt.title(label='KPI: Number of Schools', fontweight='bold', fontsize=10, fontstyle='italic')
    plt.xticks(np.arange(min_year, max_year+1, 1.0))
    plt.ylabel('Number of Schools')
    plt.xlabel('Year')
    plt.savefig(output_filename)
    plt.close(fig)

# to get overall card values for index page
def get_index_summary(input_df):
    latest_year = max(input_df['Year'])
    students = sum(input_df[(input_df['Main_Dimension']=='Elementary Enrolment by School Category') & (input_df['Year']==latest_year)]['total'])
    teachers = sum(input_df[(input_df['Main_Dimension']=='Teachers by School Category') & (input_df['Year']==latest_year)]['total'])
    schools = sum(input_df[(input_df['Main_Dimension']=='School by Category') & (input_df['Year']==latest_year)]['total'])
    classrooms = sum(input_df[(input_df['Main_Dimension']=='Total Classrooms') & (input_df['Year']==latest_year)]['total'])
    return {
        'students': format_number(int(students), locale='en_IN'),
        'teachers': format_number(int(teachers), locale='en_IN'),
        'schools': format_number(int(schools), locale='en_IN'),
        'classrooms': format_number(int(classrooms), locale='en_IN')
    }

# to get dimension wise card values for details page
def get_dimension_wise_summary(input_df, state_code, main_dimension):
    latest_year = max(input_df['Year'])
    df_fil = input_df[(input_df['State_Code']==state_code) & (input_df['Year']==latest_year)]
    total = sum(df_fil[df_fil['Main_Dimension']==main_dimension]['total'])
    if main_dimension in ['Elementary Enrolment by School Category','Teachers by School Category','School by Category']:
        govt = sum(df_fil[(df_fil['Main_Dimension']==main_dimension) & (df_fil['Sub_Dimension']=='Government')]['total'])
        private = sum(df_fil[(df_fil['Main_Dimension']==main_dimension) & (df_fil['Sub_Dimension']=='Private')]['total'])
        others = sum(df_fil[(df_fil['Main_Dimension']==main_dimension) & (df_fil['Sub_Dimension']=='Madrasas & Unrecognised')]['total'])
        return {
            'total': format_number(int(total), locale='en_IN'),
            'govt': format_number(int(govt), locale='en_IN'),
            'private': format_number(int(private), locale='en_IN'),
            'others': format_number(int(others), locale='en_IN')
        }
    elif main_dimension=='Total Classrooms':
        good = sum(df_fil[(df_fil['Main_Dimension']==main_dimension) & (df_fil['Sub_Dimension']=='Good Condition')]['total'])
        minor_repair = sum(df_fil[(df_fil['Main_Dimension']==main_dimension) & (df_fil['Sub_Dimension']=='Need Minor Repair')]['total'])
        major_repair = sum(df_fil[(df_fil['Main_Dimension']==main_dimension) & (df_fil['Sub_Dimension']=='Need Major Repair')]['total'])
        return {
            'total': format_number(int(total), locale='en_IN'),
            'good': format_number(int(good), locale='en_IN'),
            'minor_repair': format_number(int(minor_repair), locale='en_IN'),
            'major_repair': format_number(int(major_repair), locale='en_IN')
        }
    else:
        enrolment_lt_50 = sum(df_fil[(df_fil['Main_Dimension']==main_dimension) & (df_fil['Sub_Dimension']=='Enrolment <= 50')]['total'])
        drinking_water = sum(df_fil[(df_fil['Main_Dimension']==main_dimension) & (df_fil['Sub_Dimension']=='Schools with Drinking Water')]['total'])
        girls_toilet = sum(df_fil[(df_fil['Main_Dimension']==main_dimension) & (df_fil['Sub_Dimension']=='Schools with Girls\' Toilet')]['total'])
        ramp = sum(df_fil[(df_fil['Main_Dimension']==main_dimension) & (df_fil['Sub_Dimension']=='Schools with Ramp')]['total'])
        single_classroom = sum(df_fil[(df_fil['Main_Dimension']==main_dimension) & (df_fil['Sub_Dimension']=='Single Classroom Schools')]['total'])
        single_teacher = sum(df_fil[(df_fil['Main_Dimension']==main_dimension) & (df_fil['Sub_Dimension']=='Single Teacher Schools')]['total'])
        return {
            'enrolment_lt_50': format_number(int(enrolment_lt_50), locale='en_IN'),
            'drinking_water': format_number(int(drinking_water), locale='en_IN'),
            'girls_toilet': format_number(int(girls_toilet), locale='en_IN'),
            'ramp': format_number(int(ramp), locale='en_IN'),
            'single_classroom': format_number(int(single_classroom), locale='en_IN'),
            'single_teacher': format_number(int(single_teacher), locale='en_IN')
        }