import gradio as gr
import pandas as pd

# Define functions for preparing financial statements
def load_gl_data(file):
    # Load the GL data from the uploaded CSV file
    gl_data = pd.read_csv(file.name)
    
    # Ensure correct data types for debit and credit columns
    for col in ['BEGIN_BALANCE_DR', 'BEGIN_BALANCE_CR', 'PERIOD_NET_DR', 'PERIOD_NET_CR', 'YTD_DR', 'YTD_CR']:
        gl_data[col] = pd.to_numeric(gl_data[col], errors='coerce').fillna(0)

    # Calculate net balances
    gl_data['BEGIN_BALANCE'] = gl_data['BEGIN_BALANCE_DR'] - gl_data['BEGIN_BALANCE_CR']
    gl_data['PERIOD_NET'] = gl_data['PERIOD_NET_DR'] - gl_data['PERIOD_NET_CR']
    gl_data['YTD_NET'] = gl_data['YTD_DR'] - gl_data['YTD_CR']

    # Separate Balance Sheet and Income Statement items based on `Level1`
    balance_sheet = gl_data[gl_data['Level1'].isin(['TOTAL ASSETS', 'TOTAL LIABILITIES', 'TOTAL EQUITY'])]
    income_statement = gl_data[gl_data['Level1'].isin(['TOTAL REVENUE', 'TOTAL EXPENSES'])]
    
    # Prepare Balance Sheet: Sum up Assets, Liabilities, and Equity based on Levels
    assets = balance_sheet[balance_sheet['Level1'] == 'TOTAL ASSETS']['YTD_NET'].sum()
    liabilities = balance_sheet[balance_sheet['Level1'] == 'TOTAL LIABILITIES']['YTD_NET'].sum()
    equity = balance_sheet[balance_sheet['Level1'] == 'TOTAL EQUITY']['YTD_NET'].sum()
    
    # Prepare Income Statement Totals: Revenue and Expenses using YTD_NET
    revenue = income_statement[income_statement['Level1'] == 'TOTAL REVENUE']['YTD_NET'].sum()
    expenses = income_statement[income_statement['Level1'] == 'TOTAL EXPENSES']['YTD_NET'].sum()
    net_income = revenue - expenses
    
    # Format Balance Sheet output
    balance_sheet_statement = {
        "Assets": assets,
        "Liabilities": liabilities,
        "Equity": equity,
        "Total Liabilities and Equity": liabilities + equity
    }
    
    # Format Income Statement output
    income_statement_statement = {
        "Revenue": revenue,
        "Expenses": expenses,
        "Net Income": net_income
    }
    
    return balance_sheet_statement, income_statement_statement

# Gradio Interface
def generate_statements(file):
    balance_sheet, income_statement = load_gl_data(file)
    return balance_sheet, income_statement

# Set up Gradio app interface
with gr.Blocks() as demo:
    gr.Markdown("# Financial Statement Generator")
    gr.Markdown("Upload your GL data to generate the Balance Sheet and Income Statement.")
    
    with gr.Row():
        file_input = gr.File(label="Upload GL Data CSV")
        balance_sheet_output = gr.JSON(label="Balance Sheet")
        income_statement_output = gr.JSON(label="Income Statement")
    
    generate_button = gr.Button("Generate Statements")
    generate_button.click(generate_statements, inputs=file_input, outputs=[balance_sheet_output, income_statement_output])

# Launch the app
demo.launch()