#import libraries
import os
import csv

#join our csv paths
budget_data = os.path.join(r"C:\Users\dougl\OneDrive\Desktop\Homework_03-Python_Instructions_PyBank_Resources_budget_data (2).csv")

# open and read csv
with open(budget_data, newline="") as csvfile:
    csvreader = csv.reader(csvfile, delimiter=",")
    csv_header = next(csvfile)

    #set variables
    months = []
    profits = []
    revenue_change = []

    for rows in csvreader:
        profits.append(int(rows[1]))
        months.append(len(rows[0]))

    for x in range(1, len(profits)):
        revenue_change.append((int(profits[x]) - int(profits[x-1])))
    
    revenue_average = sum(revenue_change) / len(revenue_change)

    # calculate total length of months
    total_months = len(months)

    # greatest increase in revenue
    greatest_increase = max(revenue_change)

    # greatest decrease in revenue
    greatest_decrease = min(revenue_change)
    
     # print the Results
    print("Financial Analysis")
    print("....................................................................................")
    print("total months: " + str(total_months))
    print("Total: " + "$" + str(sum(profits)))
    print("Average change: " + "$" + str(revenue_average))
    print("Greatest Increase in Profits: " + str(months[revenue_change.index(max(revenue_change))+1]) + " " + "$" + str(greatest_increase))
    print("Greatest Decrease in Profits: " + str(months[revenue_change.index(min(revenue_change))+1]) + " " + "$" + str(greatest_decrease))


    # output to a text file

    file = open("output.txt","w")
    file.write("Financial Analysis" + "\n")
    file.write("...................................................................................." + "\n")
    file.write("total months: " + str(total_months) + "\n")
    file.write("Total: " + "$" + str(sum(profits)) + "\n")
    file.write("Average change: " + "$" + str(revenue_average) + "\n")
    file.write("Greatest Increase in Profits: " + str(months[revenue_change.index(max(revenue_change))+1]) + " " + "$" + str(greatest_increase) + "\n")
    file.write("Greatest Decrease in Profits: " + str(months[revenue_change.index(min(revenue_change))+1]) + " " + "$" + str(greatest_decrease) + "\n")
    file.close()