import json
import pandas as pd
import os
import re
import sys
import requests

# Get the filename from command-line arguments
if len(sys.argv) != 2:
    print("Usage: python data_fetcher.py <filename>")
    sys.exit(1)

csv_file_path = sys.argv[1]

# Check if file exists
if not os.path.isfile(csv_file_path):
    print(f"Error: File {csv_file_path} does not exist.")
    sys.exit(1)

filename = os.path.basename(csv_file_path)

# Format the filename
formatted_filename = re.sub(
    r'([A-Z]+)(\d{2}[A-Z]{3}\d{2})(P|C)(\d+)_([\d]+[a-zA-Z]+)',
    r'\1 \2 \3E \4 \5',
    filename.split('.')[0]  # Remove the file extension
)

# Read the CSV file
df = pd.read_csv(csv_file_path, usecols=['time', 'into', 'intc', 'intv', 'intvwap', 'oi'])

# Convert 'time' to datetime format for sorting
df['time'] = pd.to_datetime(df['time'], format='%d-%m-%Y %H:%M:%S', dayfirst=True)

# Sort by time
df_sorted = df.sort_values(by='time')

# Adjust 'intv' based on 'into' and 'intc' comparison
df_sorted.loc[df_sorted['into'] > df_sorted['intc'], 'intv'] *= -1

# Normalize volume values manually
min_intv = df_sorted['intv'].min()
max_intv = df_sorted['intv'].max()
df_sorted['intv_normalized'] = (df_sorted['intv'] - min_intv) / (max_intv - min_intv)

# Define the threshold as a variable

value_25_M = 25000000
value_20_M = 20000000
value_15_M = 15000000
value_14_M = 14000000
value_10_M = 10000000
value_5_M = 5000000
value_4_M = 4000000
value_3_M = 4000000
value_2_M = 2000000
value_1_M = 1000000
value_850_K = 850000
value_800_K = 800000
value_750_K = 750000
value_650_K = 750000
value_500_K = 500000
value_300_K = 300000
value_250_K = 250000

if filename.startswith("BANKNIFTY"):
    threshold_value = value_5_M
elif filename.startswith("FINNIFTY"):
    threshold_value = value_5_M
elif filename.startswith("NIFTY"):
    threshold_value = value_20_M
elif filename.startswith("MIDCPNIFTY"):
    threshold_value = value_5_M
elif filename.startswith("SENSEX"):
    threshold_value = value_5_M
else:
    threshold_value = value_5_M  # Default quantity or handle as needed


    
  # You can adjust this value as needed

# Absolute values for intv and corresponding color
df_sorted['intv_abs'] = df_sorted['intv'].abs()
df_sorted['intv_color'] = df_sorted['intv'].apply(
    lambda x: 'rgba(255, 0, 0, 0.9)' if x < -threshold_value else  # Thick red for more than threshold and negative
              'rgba(0, 255, 0, 0.9)' if x > threshold_value else   # Thick green for more than threshold and positive
              'rgba(255, 99, 132, 0.5)' if x < 0 else              # Light red for negative
              'rgba(75, 192, 192, 0.5)'                            # Light green for positive
)

# Cumulative volume
df_sorted['tVol'] = df_sorted['intv'].cumsum()

# Track if 'intv' has ever been greater than threshold_value
df_sorted['intv_greater_than_threshold'] = df_sorted['intv'].gt(threshold_value).cummax()

# Convert 'time' column to datetime if it's not already
df_sorted['time'] = pd.to_datetime(df_sorted['time'])

# New column 'databuy':
# Set to 1 if 'tVol' changes from negative to positive AND 'intv_greater_than_threshold' is True
# AND the time is less than 13:30
df_sorted['databuy'] = (
    (df_sorted['tVol'] > 0) &
    (df_sorted['tVol'].shift(1) < 0) &
    df_sorted['intv_greater_than_threshold'] &
    (df_sorted['time'].dt.time < pd.to_datetime('14:29').time())
)
df_sorted['databuy'] = df_sorted['databuy'].astype(int)

url = 'http://139.59.6.25/data_reciever.php'

# Initialize response details
response_details = []

# Iterate through rows where 'databuy' is 1 and call the URL with the specified parameters
for _, row in df_sorted[df_sorted['databuy'] == 1].iterrows():
    # Format 'time' to HH:MM
    formatted_time = row['time'].strftime('%H:%M')  # Convert datetime to HH:MM format
    
    # Prepare parameters to pass to the URL
    params = {
        'time': formatted_time,  # Pass time in HH:MM format
        'open': row['into'],
        'close': row['intc'],
        'script': formatted_filename.split('_')[0]  
    }

    # Make the GET request to the URL with the parameters
    try:
        response = requests.get(url, params=params)
        response_details.append({
            'status_code': response.status_code,
            'response_text': response.text,
            'params': params
        })
    except Exception as e:
        response_details.append({
            'status_code': 'error',
            'response_text': str(e),
            'params': params
        })

# Convert sorted data to JSON-compatible format
data = {
    "labels": df_sorted['time'].dt.strftime('%H:%M').tolist(),
    "dataInto": df_sorted['into'].tolist(),
    "dataIntc": df_sorted['intc'].tolist(),
    "dataIntv": df_sorted['intv_abs'].tolist(),
    "dataVol": df_sorted['tVol'].tolist(),
    "dataIntvColor": df_sorted['intv_color'].tolist(),
    "datavwap": df_sorted['intvwap'].tolist(),
    "dataoi": df_sorted['oi'].tolist(),
    "databuy": df_sorted['databuy'].tolist(),  # Adding databuy column to JSON data
    "filename": formatted_filename,
    "response_details": response_details  # Add response details to JSON data
}

# Print JSON output
print(json.dumps(data, indent=4))
