import argparse
from datetime import datetime, timedelta
import subprocess

def main():
    """
    Main function to parse arguments and iterate through dates.
    """
    parser = argparse.ArgumentParser(description='Iterate over a date range.')

    # Define a custom date type for argparse
    def parse_date(date_string):
        try:
            return datetime.strptime(date_string, '%Y %m %d').date()
        except ValueError:
            raise argparse.ArgumentTypeError('Invalid date format. Expected YYYY MM DD.')

    # Add the date arguments
    parser.add_argument('start_date', type=parse_date, help='The start date in "YYYY MM DD" format.')
    parser.add_argument('end_date', type=parse_date, help='The end date in "YYYY MM DD" format.')

    args = parser.parse_args()

    # Get the dates from the parsed arguments
    start_date = args.start_date
    end_date = args.end_date

    # Validate the date range
    if start_date > end_date:
        print("Error: The start date must be before or equal to the end date.")
        return

    # Iterate from the start date to the end date, inclusive
    current_date = start_date
    while current_date <= end_date:
        print(current_date.strftime("%Y %m %d"))
        # Split the date into its components
        year = current_date.strftime("%Y")
        month = current_date.strftime("%m")
        day = current_date.strftime("%d")

        # Pass each component as a separate argument
        command = ["python3", "getGDrive_mswep_id.py", year, month, day]
        try:
            # Run the command
            # check=True will raise an exception if the command fails
            subprocess.run(command, check=True, capture_output=True, text=True)
            print("Command executed successfully! 🎉")
        except subprocess.CalledProcessError as e:
            print(f"Error executing command for {current_date}: {e}")
            print("STDOUT:", e.stdout)
            print("STDERR:", e.stderr)
        except FileNotFoundError:
            print("Error: The 'python3' command or 'teste.py' script was not found.")
        current_date += timedelta(days=1)

if __name__ == '__main__':
    main()
