import json
import sys
import base64
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from __config import CONFIG
from datetime import datetime, timezone, timedelta
import os




class DATAHANDLER():

    def __init__(self):
        self.instruments = []
        self.stockOptionsFolder = CONFIG.stock_options_folder
        self.debug = ''

    def getData(self):
        files = os.listdir(self.stockOptionsFolder)
        instruments_dict = {}

        for file in files:
            if file.endswith('.json'):
                # Remove the .json extension
                filename = os.path.splitext(file)[0]
                
                # Split into date and instrument
                date_part, instrument = filename.split('_', 1)
                
                # Parse date to compare later
                date_obj = datetime.strptime(date_part, '%Y%m%d')

                # Keep only the latest date for each instrument
                if instrument not in instruments_dict or date_obj > instruments_dict[instrument]['date']:
                    instruments_dict[instrument] = {
                        'date': date_obj,
                        'formatted_date': date_obj.strftime('%d%b%Y').upper()
                    }

        # Convert the dictionary to a sorted list of formatted strings
        self.instruments = sorted(
            [f"{instrument} ({data['formatted_date']})" for instrument, data in instruments_dict.items()]
        )

        return self.instruments



    def getDebug(self):
        return str(self.debug)



if __name__== "__main__":

    returnDict = {}
    returnDict['status'] = 'OK'
    returnDict['remarks'] = ''
    returnDict['instruments'] = []

    try:
        handler = DATAHANDLER()
    except Exception as e:
        returnDict['status'] = 'KO'
        returnDict['remarks'] = str(e)
        print (json.dumps(returnDict))
        sys.exit()

    try:
        returnDict['instruments'] = handler.getData()
    except Exception as e:
        returnDict['status'] = 'KO'
        returnDict['remarks'] = str(e) + ' ' + handler.getDebug()

    print (json.dumps(returnDict))


    