'''This updates listing date in NSE collection'''
import pandas as pd
from pymongo import MongoClient
from datetime import datetime

def parse_listing_date(date_str):
    """Convert date string from CSV to ISO format"""
    try:
        # Parse date in format 'DD-Mon-YY'
        date_obj = datetime.strptime(date_str, '%d-%b-%y')
        return date_obj.strftime('%Y-%m-%d')
    except ValueError:
        print(f"Error parsing date: {date_str}")
        return None

def update_listing_dates(mongo_uri, database_name, collection_name, csv_file):
    """Update listing dates in MongoDB collection using CSV data"""

    # Connect to MongoDB
    client = MongoClient(mongo_uri)
    db = client[database_name]
    collection = db[collection_name]

    # Read CSV file
    df = pd.read_csv(csv_file)

    # Create a dictionary mapping symbols to listing dates
    symbol_to_date = {}
    for _, row in df.iterrows():
        listing_date = parse_listing_date(row[' DATE OF LISTING'])
        if listing_date:
            symbol_to_date[row['SYMBOL']] = listing_date

    # Update documents in MongoDB
    updated_count = 0
    errors = []

    for symbol, listing_date in symbol_to_date.items():
        try:
            result = collection.update_many(
                {"symbol": symbol},
                {"$set": {"listing_date": listing_date}}
            )
            if result.modified_count > 0:
                updated_count += result.modified_count
                print(f"Updated {symbol}: {listing_date}")
        except Exception as e:
            errors.append(f"Error updating {symbol}: {str(e)}")

    # Print summary
    print(f"\nUpdate Summary:")
    print(f"Total documents updated: {updated_count}")
    if errors:
        print("\nErrors encountered:")
        for error in errors:
            print(error)

    client.close()

# Example usage
if __name__ == "__main__":
    # Replace these with your actual MongoDB connection details
    MONGO_URI = "mongodb://192.168.31.175:27017"
    DATABASE_NAME = "zerodha_test"
    COLLECTION_NAME = "nse_data1"
    CSV_FILE = "SybolByListing.csv"

    update_listing_dates(MONGO_URI, DATABASE_NAME, COLLECTION_NAME, CSV_FILE)