import sys, os
import argparse
import pandas as pd
import shutil
import datetime
from PyUtil.PyDate import PyDate

from model.trading.EG import EG
from model.signal.engine import *
from model.signal.interface import *
from model.trading.Simulation import *

import PyUtil.PyRicX as RicX

now = datetime.datetime.now()

parser = argparse.ArgumentParser()
parser.add_argument("-d","--date", default=PyDate.nextWeekday(PyDate.today()).strftime("%Y%m%d"), help='date string YYYYMMDD')
parser.add_argument("-P","--f_PERISCOPE", default='YYYYMMDD.targets.PERISCOPE.csv', help='Persicope targets file')
parser.add_argument("-B","--f_BASE", default='targets.csv', help='BASE targets file')
parser.add_argument("-PROD_OW","--PROD_OW", action='store_true', default=False, help='Really overwrite targets')
parser.add_argument("-FORCE_OW","--FORCE_OW", action='store_true', default=False, help='FORCE overwrite targets even when checks make it look as though script alreay run.. ')
parser.add_argument("-mto", "--mail_to", default='ap-production@greenwichquantitative.com')
args = parser.parse_args()


PROD_OW = bool(args.PROD_OW)
FORCE_OW = bool(args.FORCE_OW)
date = str(args.date)
mail_to=str(args.mail_to)


p = pd.read_csv( args.f_PERISCOPE.replace('YYYYMMDD', date)   )
b = pd.read_csv( args.f_BASE   )

print(f'read ({args.f_PERISCOPE}) ({len(p)})')
print(f'read ({args.f_BASE}) ({len(b)})')

if len(b)*len(p)==0:
    print('Zero size input file..  EXIT')
    exit(0)

### Backup the BASE file to targets.BASE.csv and HHMMSS.YYMMDD.targets.BASE.csv  --> otherwise you can get into a loop of ugly reruns where you lose file #1..
backup_f_BASE = args.f_BASE.replace('.','.BASE.').replace('targets.',f'{date}.targets.')
timed_backup_f_BASE = f'{now.strftime("%H%M.%Y%m%d")}.{backup_f_BASE}'

try:
    shutil.copy(args.f_BASE, backup_f_BASE)
    print(f"File {args.f_BASE} copied to {backup_f_BASE}")
    shutil.copy(args.f_BASE, timed_backup_f_BASE)
    print(f"File {args.f_BASE} copied to {timed_backup_f_BASE}")
except FileNotFoundError:
    print(f"ERR No ({args.f_BASE}) found --> EXIT")
    exit(0)


### Combine the two files into one sheet
print('\n----PERISCOPE')
print(p.head())
print('\n----BASE')
print(b.head())

merg_cols=['ric', 'targetposition']
comb = pd.merge(b[merg_cols], p[merg_cols], on='ric', how='outer', suffixes=('_p', '_b')).fillna(0)
comb['targetposition'] = comb['targetposition_p'] + comb['targetposition_b'] 
comb.drop(['targetposition_p', 'targetposition_b'], axis=1, inplace=True)
comb['targetposition'] = comb['targetposition'].astype(int)


for c in p.columns:
    if c in merg_cols:  continue
    comb[c] = b[c].values[0]
    
fn_o = 'comb.csv'    
comb_pre_existed = os.path.isfile(fn_o)
comb.to_csv(fn_o, index=False)
print(f'wrote ({fn_o}) ({len(comb)})')    
    
print('\n-----comb:')
print(comb.head())



################   Overwrite the prod targets files
if PROD_OW:
    print(f'\n\nPROD_OW{PROD_OW} ---> overwrite({args.f_BASE})  comb_file_pre-existed({comb_pre_existed})')

    ### We want to check that the targets we just read was not actually already the combined output of this script..
    if comb_pre_existed:  #  there was already a combined file before we wrote one..
        posn_rics_p = p[ p['targetposition']!=0  ]['ric']
        posn_rics_b = b[ b['targetposition']!=0  ]['ric']
        rics_in_p_not_b = posn_rics_p[~posn_rics_p.isin(posn_rics_b)]
        print(f'Check :: ({len(rics_in_p_not_b)}) rics in PERISCOPE not seen in BASE (want non-zero!)')
        if len(rics_in_p_not_b)==0:  ### hmmm..  the 'BASE' targets file has all rics in PER.. seems unlikely..
            if not FORCE_OW:
                PROD_OW=False  ## aborting this prod overwrite
                print('Cancelled targets overwrite because we may be in the loop of multiple rewrite of the targets file.  Please check that targets.csv is the true BASE startegy only')


    if PROD_OW:

        ### local targets.csv file
        fn_o = args.f_BASE
        comb.to_csv(fn_o, index=False)
        print(f'wrote ({fn_o}) ({len(comb)})')

        ### targets file in TradeLists to be uploaded. e.g. /mnt/signal/simulation/EGProd1/TradeLists/targets.20251211.csv
        fn_tr_o = f'/mnt/signal/simulation/EGProd1/TradeLists/targets.{date}.csv'
        comb.to_csv(fn_tr_o, index=False)  
        print(f'wrote ({fn_tr_o}) ({len(comb)})')


 
if mail_to !='':
    pfm = SignalMgr.get('price_frame_latest', PyDate.asDate(PyDate.prevWeekday( PyDate.asDate(date))))[['assetKey','priceCloseUSD']]
    subj=f'EOD Portfolio Combination {date} ({"PASS" if PROD_OW else "FAIL/NO COMBINE"})'
    lines=[]
    lines.append(f'Report from Combination of PERISCOPE & BASE targets into combined targets for EG\n\n')
    
    for t,n in [(comb,'COMBINED'), (b,'BASE'), (p, 'PERISCOPE')  ]:
        print(t.head())
        t['internal_ric'] = t["ric"].apply(RicX.externalric_to_ric)
        t = RicX.add_asset_code(t,ric_column='internal_ric')
        t = t.merge(pfm, on='assetKey',how='left').fillna(0)
        lines.append(f'\n{n}\t ({len(t)}) names  (({len(t[t["targetposition"]>0])}) Long\t ({len(t[t["targetposition"]<0])}) Short\t ({len(t[t["targetposition"]==0])}) Zero\t)')
        cut_L = t['targetposition']>0
        cut_S = t['targetposition']<0
        L_USDM = np.sum( t.loc[cut_L, 'targetposition']*t.loc[cut_L, 'priceCloseUSD']   )/1000000
        S_USDM = np.sum( t.loc[cut_S, 'targetposition']*t.loc[cut_S, 'priceCloseUSD']   )/1000000
        lines.append(f'GMV(${L_USDM-S_USDM:.2f}M) \tL(${L_USDM:.2f}M) \tS(${S_USDM:.2f}M) \tD(${L_USDM+S_USDM:.2f}M)')
        
    if PROD_OW:
        lines.append(f'\n\nWrote ({fn_tr_o})')
        lines.append(f'Wrote ({fn_o})')
    else:
        lines.append(f'NO WRITING OF COMBINED PORTFOLIO')

    bdy=''
    for l in lines:
        bdy+=l+'\n'
        print(l)

    if True:
        MailUtil.send(fromAddr = 'ap-production@greenwichquantitative.com',
            toAddr = mail_to,
            subject = subj,
            body = bdy,
            attachments = [])

