# How to use this script:
#
# Run Python:
#
#   import  pcost  as  p  # It will NOT run main() !!!
#   >>> p.main()
#   >>> p.portfolio_cost('Data/portfolio.csv')
#
# pcost.py
#
# Exercise 2.16

# *************************************************************************
# Instead of portfolio_cost() being hardcoded to read a single 
# fixed file format, the new version reads any CSV file and 
# ***picks the values of interest*** out of it. 
#
# So as long as the file has the required columns, the code will work !!
# *************************************************************************

def portfolio_cost(filename):
    with open(filename, 'rt') as inpFile:
        headers = next(inpFile).strip().split(",");
        print(headers)
        print(type(headers))
    
    
        total_cost = 0
    
        for rowNo, line in enumerate(inpFile):
            row = line.strip().split(",")
            print(rowNo, " >> ", row)

            record = dict(zip(headers, row))
            print(record, "\n")
    
            try:
                nshares = int(record['shares'])
                price = float(record['price'])
                total_cost += nshares * price
                print("Cum cost = ", total_cost)
            # This catches errors in int() and float() conversions above
            except ValueError:
                print(f'Row {rowno}: Bad row: {row}') 

    return total_cost

def main():
    cost = portfolio_cost('Data/portfolio.csv')
    print('Total cost:', cost)

    print("------------------------------------------------")

    cost = portfolio_cost('Data/portfoliodate.csv')
    print('Total cost:', cost)

# *******************************************
# ONLY run main() when executed as a SCRIPT
# Will NOT run main() if IMPORTED !!!
# *******************************************
if __name__ == "__main__":
    main()

