import sys
import numpy as np
import pandas as pd # to read-write Excel; not used here
from scipy.optimize import minimize
import subprocess
import base64
import os

tst = 0
#=================================Input Begin===========================
if tst: print('%Test len(sys.argv),', str(len(sys.argv))+'; '
  "sys.argv:\n", ' ', *sys.argv)

tex1 = " *** Compound interest ***"
tex2 = '(Aug-2024, MC)'; tex3 = '29_22:01'
print(tex1+(81-len(tex1)-len(tex2))*' '+tex2+'\n'+73*' '+tex3)
user_name = os.getenv("USER")
internetprefix = "file://" if user_name is None else ''
if tst: print ('%Test user_name:', user_name)
#=======================================================================
#file_size, file_tmp, max_file_size, \
#  datatable, hguess, hcomple, modeveropt, toler, ishow = sys.argv[1:]
principal, rate, icofreq, ovtime, ishow = sys.argv[1:]

v = [principal, rate, ovtime]; \
    [principal, rate, ovtime] = [float(i) for i in v]
v = [icofreq, ishow]; \
    [icofreq, ishow] = [int(i) for i in v]

print (' {:<24}{:>12.5g}    |'.format('Principal,', principal))
print (' {:<24}{:>12.2g}    |'.format('Interest rate,', rate))
print (' {:<24}{:>12}    |'.format('Componding frequency,', icofreq))
print (' {:<24}{:>12.4g}    |'.format('Overall time,', ovtime))
print(' '+40*'-'+'+'+39*'-')
#=================================Input End=============================

#==d e f================================================================
def amount(princ, rat, ifreq, t):
    return princ * (1 + rat / ifreq) ** (ifreq * t)

novtime = int(ovtime)
ntimes  = novtime + 1
if tst: print('%Test ntimes,', ntimes)
t_v = np.linspace(0, ntimes-1, ntimes); amount_v = np.full_like(t_v, 0)
if tst: print ('%Test t_v:', *t_v)

for i in range(ntimes):
    amount_v[i] = amount(principal, rate, icofreq, t_v[i])

print (' {:<24}{:>12.5g}    | (A)'.\
  format('Final amount,', amount_v[ntimes-1]))
#================================PLOT===================================
temporary = '/afs/ist.utl.pt/users/3/8/ist11038/web/tmp' # = '/tmp'
basedir = temporary + '/tx' + str(os.getpid())
if tst: print('%Test FILES:')
tmpfilexy_nam = basedir+'tmpfxy.txt'
tmpfilexy_wra = open(tmpfilexy_nam, 'w')
if tst: print("%Test FILE tmpfilexy_nam:\n", '  '+tmpfilexy_nam)

in_file_nam = basedir+'tmp.txt'
in_file_wra = open(in_file_nam, 'w')

imgfile_nam = basedir+'tmp.png'
imgfile_wra = open(imgfile_nam, 'w')
if tst: print("%Test FILE imgfile_nam:\n", '  '+imgfile_nam)

#===============================Display=================================
ncols = 1
fort = ' {:>12.5g}'*(1+ncols)

if tst: print('%Test Print to ', tmpfilexy_wra)
for i in range(ntimes):
    print (fort.format(t_v[i], amount_v[i]), file=tmpfilexy_wra)

tmpfilexy_wra.seek(0)
gnuplot_load = \
f'''wid = 620; set term png font 'Times, 14' size wid, wid/1.618
set output '{imgfile_nam}'
set title 'Amounts (0  to {novtime})' offset 0, -0.4
set key bottom right Left font ', 11'
set timestamp font 'Helvetica-Bold, 9' offset 0, -0.25
set xlabel '{{/Times-Italic t}}' offset +9., 0.75
set ylabel '{{/Times-Italic A}}' rotate by 0 offset 1.5, 0
set xrange [0:*]; set yrange [*:*]
set tics nomirror
# + x +x, (clos/ope) 4 5 sq, 6 7 o, 8 9 tri, 10 11 tri inv
set style line 12 lc rgb '#2E8B57' lw 3 pt 7 ps 1 # SeaGreen (#32CD32LimeGreen)
set style line 13 lc rgb '#A36C' lw 1 pt 5 ps 2 # jade
set style line 14 lc rgb 'red'   lw 3 pt 5 ps 2
set style line 15 lc rgb '#A36C' lw 3 pt 4 ps 1
set style line 16 lc rgb 'orange' lw 2 pt 3 ps 1
set style line 17 lc rgb 'orange' lw 2 pt 4 ps 1
plot '{tmpfilexy_nam}' usi 1:2 title 'A' w linespoints ls 12
'''

if tst: print("\n%Test gnuplot_load:\n"+gnuplot_load)

in_file_wra.seek(0)
with open(in_file_nam, 'w') as pli:
    lines = gnuplot_load.splitlines(True)
    pli.writelines(lines); pli.flush()
    subprocess.call(['/usr/bin/gnuplot', in_file_nam], shell=False)

imgfile_wra.seek(0)
if tst: print ("%Test To copy ... /bin/cp -f\n  " + imgfile_nam + \
  "\n  /afs/ist.utl.pt/users/3/8/ist11038/web/tmp/gnu.png")
os.system("/bin/cp -f " + imgfile_nam + \
  " /afs/ist.utl.pt/users/3/8/ist11038/web/tmp/gnu.png")
if tst: print ("%Test ... From copy\n")

with open(imgfile_nam, 'rb') as image_file:
    encoded = base64.b64encode(image_file.read())
encoded = str(encoded)[2:-1]

print('<center><!--PLOT-->')
print('<img alt="Plot" src="data:image/png; base64, '+encoded+'" />')
print('</center>')

os.remove(in_file_nam); os.remove(imgfile_nam); os.remove(tmpfilexy_nam)

#===============================Display=================================
if ishow==0:
    print(' End of program'); exit ()

from openpyxl import Workbook
workbook = Workbook(); workbook.remove(workbook['Sheet']) # keyword !

import random
mysheet = ''.join(random.sample('BCDFGHJKLMNPQRSTVWXZ', 3)) + '_' + \
          ''.join(random.sample('01234567890', 2))
#sheet = workbook.create_sheet(title=mysheet); sheet = workbook.active
sht = workbook.create_sheet(title=mysheet); sht = workbook.active

print(' Show_i'+'_'*11+'t'+'_'*6+'y calc...')
fort = ' {:>5})' + '{:>12.6g}'*(1+ncols)
for i in range(ntimes):
    print (fort.format(i, t_v[i], amount_v[i]))
    row =             (i, t_v[i], amount_v[i])
    sht.append(row)
excel_file = '/afs/ist.utl.pt/users/3/8/ist11038/web/tmp/output.xlsx'
workbook.save(excel_file)

print ('\n <a href=\n' + \
  ' "http://web.tecnico.ulisboa.pt/ist11038/tmp/output.xlsx"\n>' + \
  '<b>output.xlsx</b></a> -- Your sheetname: "' + mysheet + '" (Verify)')

print('\n End of program')
