# main.py
from flask import Flask, render_template, request, redirect, url_for, Response
from calc import calculate_savings_depletion
from db import init_db, get_finance_data, update_finance
from collections import defaultdict
from datetime import datetime
import csv
import io

app = Flask(__name__)

# Initialize the database
init_db()

@app.route('/')
def index():
    finance_data = get_finance_data()
    depletion_date, savings_per_fortnight, final_savings, TLS, CBA = calculate_savings_depletion(finance_data)
    if depletion_date:
        depletion_date=depletion_date.date(); # just show date

    # annual bills - rates (2.4), electricity (1.5), gas (2), internet (1.6), car insurance (.7), rego (.8), house insurance (2.4), GFC (2.2), phones (.5), melb. pollen (.03), nabu casa (.1), eweka (.1)  --- noting phone is elevated presuming I also go onto Aldi plan, but that there is no family discount
    bills = 14330
    BUDGET=[]
    BUDGET.append( ('Bills', f"${bills:,.2f}") )
    BUDGET.append( ('Buffer', f"${CBA*finance_data['CBA_price']:,.2f}") )
    BUDGET.append( ('Monthly budget', f"${((finance_data['Living_Expenses']-12000) / 12):,.2f}" ) )
    BUDGET.append( ('Weekly budget', f"${((finance_data['Living_Expenses']-12000) / 52):,.2f}" ) )
    return render_template('index.html', finance=finance_data, depletion_date=depletion_date, savings=savings_per_fortnight, TLS=TLS, CBA=CBA, BUDGET=BUDGET)

@app.route('/update', methods=['POST'])
def update():

    finance_data = (
        request.form['D_Salary'],
        request.form['M_salary'],
        request.form['D_Num_fortnights_pay'],
        request.form['M_Num_fortnights_pay'],
        request.form['School_Fees'],
        request.form['Car_loan_via_pay'],
        request.form['Car_loan'],
        request.form['Car_balloon'],
        request.form['Living_Expenses'],
        request.form['Savings'],
        request.form['Interest_Rate'],
        request.form['Inflation'],
        request.form['M_payout'],
        request.form['Mich_present'],
        request.form['Overseas_trip'],
        request.form['Mark_reno'],
        request.form['D_leave_owed_in_days'],
        request.form['D_TLS_shares'],
        request.form['M_TLS_shares'],
        request.form['D_CBA_shares'],
        request.form['TLS_price'],
        request.form['CBA_price'],
        request.form['Overseas_trip_date'],
        request.form['Mark_reno_date'],
        request.form['M_payout_date'],
        request.form['Sell_shares'],
    )

    update_finance(finance_data)

    return redirect(url_for('index'))

@app.route("/download_csv", methods=["GET"])
def download_csv():

    finance_data = get_finance_data()
    depletion_date, savings_per_fortnight, final_savings, TLS, CBA = calculate_savings_depletion(finance_data)

    # Group data by year
    data_by_year = defaultdict(list)
    for date_str, amount in savings_per_fortnight:
        year = date_str.split("-")[0]  # Extract the year from the date
        data_by_year[year].append((date_str, amount))

    # Determine the maximum number of entries for any year
    max_entries_per_year = max(len(entries) for entries in data_by_year.values())

    # Sort years for column ordering
    years = sorted(data_by_year.keys())

    # Create an in-memory output file
    output = io.StringIO()
    
    # Create a CSV writer object
    writer = csv.writer(output)

    # Write header: each year gets two columns (Date, Value)
    header = []
    for year in years:
        header.extend([f"{year}-Date", f"{year}-Value"])
    writer.writerow(header)

    # Write the data rows
    for i in range(max_entries_per_year):
        row = []
        for year in years:
            # Add date and value if they exist for the current index
            if i < len(data_by_year[year]):
                date, value = data_by_year[year][i]
                row.extend([date, value])
            else:
                row.extend(["", ""])  # If no data for this year, leave blank cells
        writer.writerow(row)

    csv_data = output.getvalue()

    # Create a Flask Response object, with CSV mime type and downloadable as a file
    return Response(
        csv_data,
        mimetype="text/csv",
        headers={"Content-disposition": "attachment; filename=finance_data.csv"}
    )

# Main program
if __name__ == '__main__':
    app.run(debug=True)


##########
#
# How to cross-check, so we get paid: 4762.29 + 1962.56 per fortnight or: $174846.1 AFTER TAX
# take $20k for Cam, and $20k for Mich for schools last year, $10k for Cam pres, take $72k for living, take $8k in furniture.
# We went from 250 to 300k (more or less), so about right
# to note: transfers to Cam/Mich - $850
# 
##########
