from pymongo import MongoClient
import pandas as pd
import re  # Import `re` for regex escaping

# Connect to MongoDB
client = MongoClient("mongodb://192.168.31.176:27017/?directConnection=true&tls=false")
db = client["zerodha_2025"]
nse_collection = db["nse_data1"]
bse_collection = db["bse_data1"]

# Read the CSV file
df = pd.read_csv(r"C:\Users\user\Downloads\Equity (19).csv")

# Ensure column names are correctly stripped of leading/trailing spaces
df.columns = df.columns.str.strip()

# Initialize a counter if needed (optional based on your logic)
count = 0

# Iterate over each row in the DataFrame
for i, row in df.iterrows():
    symbol = row["Security Id"]
    isin = row["ISIN No"]
    issuer_name = row["Issuer Name"]
    security_name = row["Security Name"]
    status = row["Status"]
    group = row["Group"]
    face_value = row["Face Value"]
    industry = row["Industry"]
    instrument = row["Instrument"]
    sector_name = row["Sector Name"]
    industry_new_name = row["Industry New Name"]
    igroup_name = row["Igroup Name"]
    isubgroup_name = row["ISubgroup Name"]

    print(symbol, isin)

    if count == 0:
        # Escape the `symbol` value to ensure safe use in regex
        escaped_symbol = re.escape(symbol)

        # Perform the update operation
        bse_collection.update_one(
            {
                "symbol": {
                    "$regex": f"^{escaped_symbol}"  # Use escaped `symbol`
                }
            },
            {
                "$set": {
                    "Issuer Name": issuer_name,
                    "Security Id": symbol,
                    "Security Name": security_name,
                    "Status": status,
                    "Group": group,
                    "Face Value": face_value,  # Ensure numeric type
                    "ISIN No": isin,
                    "Industry": industry,
                    "Instrument": instrument,
                    "Sector Name": sector_name,
                    "Industry New Name": industry_new_name,
                    "Igroup Name": igroup_name,
                    "ISubgroup Name": isubgroup_name
                },
            }
        )
        # count += 1  # Uncomment if you intend to update only once
    else:
        break  # Exit after the first update (if that's intended)
