from thefirstock import thefirstock
import os
import time
import pandas as pd
import logging
from datetime import datetime, timedelta
import pytz
import stat
import requests
import urllib.parse

# Set IST timezone
ist = pytz.timezone('Asia/Kolkata')

# Custom formatter to convert time to IST
class ISTFormatter(logging.Formatter):
    def formatTime(self, record, datefmt=None):
        # Set timezone to IST
        ist = pytz.timezone('Asia/Kolkata')
        record_time = datetime.fromtimestamp(record.created, tz=ist)
        return record_time.strftime(datefmt or '%Y-%m-%d %H:%M:%S')

# Set up global logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.propagate = False

formatter = ISTFormatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        
# Console handler
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(formatter)  
logger.addHandler(console_handler)


def login(client):
    userId = client[0]
    password = client[1]
    TOTP = client[2]
    vendorCode = client[3]
    apiKey = client[4]

    logger.info("Attempting to login")
    login_response = thefirstock.firstock_login(
        userId=userId,
        password=password,
        TOTP=TOTP,
        vendorCode=vendorCode,
        apiKey=apiKey
    )
    if login_response['status'] == 'success':
        logger.info("Login successful")
    else:
        logger.error("Login failed: %s", login_response)


def adjust_intv(row):
    if row['into'] > row['intc']:
        return -abs(row['intv'])
    elif row['into'] < row['intc']:
        return abs(row['intv'])
    else:
        return 0
    


def fetch_time_price_series(exchange, tradingSymbol, start_time, end_time, userId, interval):

    '''
    exchange='NSE'
    tradingSymbol='Nifty 50'
    '''

    # Tracing: Print all input parameters
    logger.info(f"fetch_time_price_series called with params: exchange={exchange}, tradingSymbol={tradingSymbol}, "
                f"start_time={start_time}, end_time={end_time}, userId={userId}, interval={interval}")
    
    try:
        response = thefirstock.firstock_TimePriceSeries(
            userId=userId,
            exchange=exchange,
            tradingSymbol=tradingSymbol,
            startTime=start_time,
            endTime=end_time,
            interval=interval
        )
        if response.get("status") == "success":
            data = response.get("data", [])
            return pd.DataFrame(data)
        else:
            logger.error(f"Error: {response.get('status')} {response}")
            return pd.DataFrame()
    except Exception as e:
        logger.error(f"Error fetching time price series: {e}")
        return pd.DataFrame()



def main(userId, clientRootFolder):


    # Specify the day, month, and year
    day = 16
    
    month = 10
    year = 2024

    # Create the fixed start time with the specified date and time
    start_time_fixed = datetime(year, month, day, 9, 15, 0, 0, tzinfo=ist)
    trading_end_time = datetime(year, month, day, 15, 30, 0, 0, tzinfo=ist)
    
    symbols = [
        'NFO:BANKNIFTY16OCT24P51300', 'NFO:BANKNIFTY16OCT24P51400', 'NFO:BANKNIFTY16OCT24P51500', 
        'NFO:BANKNIFTY16OCT24P51600', 'NFO:BANKNIFTY16OCT24P51700', 'NFO:BANKNIFTY16OCT24P51800', 
        'NFO:BANKNIFTY16OCT24P51900', 'NFO:BANKNIFTY16OCT24P52000', 'NFO:BANKNIFTY16OCT24P52100',
        'NFO:BANKNIFTY16OCT24C51500', 'NFO:BANKNIFTY16OCT24C51600', 'NFO:BANKNIFTY16OCT24C51700', 
        'NFO:BANKNIFTY16OCT24C51800', 'NFO:BANKNIFTY16OCT24C51900', 'NFO:BANKNIFTY16OCT24C52000', 
        'NFO:BANKNIFTY16OCT24C52100', 'NFO:BANKNIFTY16OCT24C52200', 'NFO:BANKNIFTY16OCT24C52300', 
        'NFO:BANKNIFTY16OCT24C52400',
        
        'NFO:NIFTY17OCT24P24750', 'NFO:NIFTY17OCT24P24800', 'NFO:NIFTY17OCT24P24850', 
        'NFO:NIFTY17OCT24P24900', 'NFO:NIFTY17OCT24P24950', 'NFO:NIFTY17OCT24P25000', 
        'NFO:NIFTY17OCT24P25050', 'NFO:NIFTY17OCT24P25100', 'NFO:NIFTY17OCT24P25150',
        'NFO:NIFTY17OCT24C24850', 'NFO:NIFTY17OCT24C24900', 'NFO:NIFTY17OCT24C24950', 
        'NFO:NIFTY17OCT24C25000', 'NFO:NIFTY17OCT24C25050', 'NFO:NIFTY17OCT24C25100', 
        'NFO:NIFTY17OCT24C25150', 'NFO:NIFTY17OCT24C25200', 'NFO:NIFTY17OCT24C25250', 
        'NFO:NIFTY17OCT24C25300',
        
        'BFO:SENSEX24O1881400PE', 'BFO:SENSEX24O1881500PE', 'BFO:SENSEX24O1881600PE', 
        'BFO:SENSEX24O1881700PE', 'BFO:SENSEX24O1881800PE', 'BFO:SENSEX24O1881900PE', 
        'BFO:SENSEX24O1882000PE', 'BFO:SENSEX24O1882100PE', 'BFO:SENSEX24O1882200PE',
        'BFO:SENSEX24O1881600CE', 'BFO:SENSEX24O1881700CE', 'BFO:SENSEX24O1881800CE', 
        'BFO:SENSEX24O1881900CE', 'BFO:SENSEX24O1882000CE', 'BFO:SENSEX24O1882100CE', 
        'BFO:SENSEX24O1882200CE', 'BFO:SENSEX24O1882300CE', 'BFO:SENSEX24O1882400CE', 
        'BFO:SENSEX24O1882500CE',
        
        'NFO:MIDCPNIFTY21OCT24P13000', 'NFO:MIDCPNIFTY21OCT24P13025', 'NFO:MIDCPNIFTY21OCT24P13050', 
        'NFO:MIDCPNIFTY21OCT24P13075', 'NFO:MIDCPNIFTY21OCT24P13100', 'NFO:MIDCPNIFTY21OCT24P13125', 
        'NFO:MIDCPNIFTY21OCT24P13150', 'NFO:MIDCPNIFTY21OCT24P13175', 'NFO:MIDCPNIFTY21OCT24P13200',
        'NFO:MIDCPNIFTY21OCT24C13050', 'NFO:MIDCPNIFTY21OCT24C13075', 'NFO:MIDCPNIFTY21OCT24C13100', 
        'NFO:MIDCPNIFTY21OCT24C13125', 'NFO:MIDCPNIFTY21OCT24C13150', 'NFO:MIDCPNIFTY21OCT24C13175', 
        'NFO:MIDCPNIFTY21OCT24C13200', 'NFO:MIDCPNIFTY21OCT24C13225', 'NFO:MIDCPNIFTY21OCT24C13250', 
        'NFO:MIDCPNIFTY21OCT24C13275',
        
        'NFO:FINNIFTY22OCT24P23550', 'NFO:FINNIFTY22OCT24P23600', 'NFO:FINNIFTY22OCT24P23650', 
        'NFO:FINNIFTY22OCT24P23700', 'NFO:FINNIFTY22OCT24P23750', 'NFO:FINNIFTY22OCT24P23800', 
        'NFO:FINNIFTY22OCT24P23850', 'NFO:FINNIFTY22OCT24P23900', 'NFO:FINNIFTY22OCT24P23950',
        'NFO:FINNIFTY22OCT24C23650', 'NFO:FINNIFTY22OCT24C23700', 'NFO:FINNIFTY22OCT24C23750', 
        'NFO:FINNIFTY22OCT24C23800', 'NFO:FINNIFTY22OCT24C23850', 'NFO:FINNIFTY22OCT24C23900', 
        'NFO:FINNIFTY22OCT24C23950', 'NFO:FINNIFTY22OCT24C24000', 'NFO:FINNIFTY22OCT24C24050', 
        'NFO:FINNIFTY22OCT24C24100'
    ]



    #symbols = ["NFO:NIFTY05SEP24C25300" ]
    #symbols = ["BFO:SENSEX24AUG81400PE", "NFO:NIFTY05SEP24C25300"]


    intervalList = [ 5 , 10 , 15, 30 ]
    intervalList = [ 5  ]

    for interval in intervalList:
        for symbol in symbols:

            time.sleep(1)
            logger.info(f"symbol = {symbol} ")
            exchange, tradingSymbol = symbol.split(':')
            start_time_str = start_time_fixed.strftime("%d/%m/%Y %H:%M:%S")
            end_time_str = trading_end_time.strftime("%d/%m/%Y %H:%M:%S")
            interval_str = str(interval)

            df = fetch_time_price_series(exchange, tradingSymbol, start_time_str, end_time_str, userId, interval_str)
            if not df.empty:

                srcfolderName = os.path.join( clientRootFolder , 'input' )
                if not os.path.exists(srcfolderName):
                        os.makedirs(srcfolderName)
                os.chmod(srcfolderName, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)

                srcFileName = os.path.join(srcfolderName, f"{tradingSymbol}_{interval_str}.csv")
                df.to_csv(srcFileName, index=False)

                # Logging the filtered and updated DataFrame
                logger.debug(f"{tradingSymbol} {interval_str}  data:\n{df}")

                encoded_file_path = urllib.parse.quote(srcFileName)

                # Construct the URL with the encoded file argument
                url = f"http://143.244.141.41/php/data.php?file={encoded_file_path}"

                # Make the GET request
                try:
                    response = requests.get(url)
                    # Log the status code or response
                    logger.debug(f"Request made to {url} - Status Code: {response.status_code}")
                except requests.exceptions.RequestException as e:
                    logger.error(f"Failed to make request to {url} - Error: {e}")


            time.sleep(1)




if __name__ == "__main__":
    #clientDetails = ['RA1383', 'O9i8u7y6##', '13061983', 'RA1383_API', '491bf9166cfe0e7c419ac071f3fca6e1']
    #clientDetails = ['DB1485', '$L10n-one', '14121985', 'DB1485_API', 'e64881301306ce087b1108a74e174e82']
    clientDetails = ['TT1582', 'O9i8u7y6##', '15111982', 'TT1582_API', 'ed87fa73888bc882c5d79bf832c0f9eb']
    userId = clientDetails[0]
    clientRootFolder = f"/var/www/html/clientData/{userId}"
    os.chdir(clientRootFolder)
    login(clientDetails)

    main(userId, clientRootFolder)
