'''This script removes false data'''
from pymongo import MongoClient
from datetime import datetime

def cleanup_pre_listing_data(mongodb_uri, database_name, collection_name):
    """
    Cleans up stock price data by removing records that exist before the listing date.

    Args:
        mongodb_uri (str): MongoDB connection URI
        database_name (str): Name of the database
        collection_name (str): Name of the collection
    """
    try:
        # Connect to MongoDB
        client = MongoClient(mongodb_uri)
        db = client[database_name]
        collection = db[collection_name]

        # Get all documents
        stocks = collection.find({})

        for stock in stocks:
            # Check if listing_date exists
            if 'listing_date' not in stock:
                print(f"Skipping {stock['symbol']}: No listing date found")
                continue

            # Convert listing date string to datetime object
            listing_date = datetime.strptime(stock['listing_date'], '%Y-%m-%d')

            # Get prices dictionary
            prices = stock.get('prices', {})

            # Identify dates to remove
            dates_to_remove = []
            for date_str in prices:
                price_date = datetime.strptime(date_str, '%Y-%m-%d')
                if price_date < listing_date:
                    dates_to_remove.append(date_str)

            if dates_to_remove:
                # Create update query to remove specific dates
                update_query = {}
                for date_str in dates_to_remove:
                    update_query[f"prices.{date_str}"] = ""

                # Update document
                collection.update_one(
                    {'_id': stock['_id']},
                    {'$unset': update_query}
                )

                print(f"Cleaned {stock['symbol']}: Removed {len(dates_to_remove)} pre-listing dates")
            else:
                print(f"No cleanup needed for {stock['symbol']}")

        print("Cleanup completed successfully")

    except Exception as e:
        print(f"An error occurred: {str(e)}")

    finally:
        client.close()

# Example usage
if __name__ == "__main__":
    # Replace these with your actual MongoDB connection details
    MONGODB_URI = "mongodb://192.168.31.176:27017"
    DATABASE_NAME = "zerodha_test"
    # COLLECTION_NAME = "nse_data1"
    COLLECTION_NAME = "bse_data1"

    cleanup_pre_listing_data(MONGODB_URI, DATABASE_NAME, COLLECTION_NAME)