from datetime import datetime, timedelta
import subprocess
import sys # To access sys.executable (the Python interpreter)
import os
from cdo import Cdo

cdo = Cdo()

cdo.debug = True # See the actual CDO commands being executed
cdo.forceOutput = True # Overwrite output files if they exist

def loop_hourly_range(start_str, end_str, dir_in, dir_out, Eta_data, Eta_levs, Typ, fct_int):
    """
    Loops through a time range hourly, given start and end strings in YYYYMMDDHH format.

    Args:
        start_str (str): The start datetime string (e.g., '2025070400').
        end_str (str): The end datetime string (e.g., '2025070500').
    """
    # Define the format of your input strings
    date_format = "%Y%m%d%H"

    try:
        # Convert start and end strings to datetime objects
        start_datetime = datetime.strptime(start_str, date_format)
        end_datetime = datetime.strptime(end_str, date_format)

        # Define the hourly increment
        hourly_interval = timedelta(hours=1)

        print(f"Looping from {start_datetime.strftime(date_format)} to {end_datetime.strftime(date_format)} (hourly):")

        script_to_run = "multiVariable_v4.py"
        current_datetime = start_datetime
        while current_datetime <= end_datetime:
            # You can perform your operations here for each hour
            # For example, print the current hour or process a file related to this time
            print(f"Processing time: {current_datetime.strftime(date_format)}")

            # Define the arguments you want to pass to it
            # These should be replaced with actual variable names or concrete values
            arg1 =  dir_in+"Eta10_C00_"+start_str+"+"+str(current_datetime.strftime(date_format))+"_"+Typ+".bin"
            arg2 = dir_out+"Eta10_C00_"+start_str+"+"+str(current_datetime.strftime(date_format))+"_"+Typ+".nc"
            arg3 = Eta_data
            arg4 = Eta_levs
            arg5 = fct_int
            output_split=dir_out+"Eta10_C00_"+start_str+"+"+str(current_datetime.strftime(date_format))+"_"+Typ+"_"

            # Construct the command list
            # It's good practice to use sys.executable to ensure the correct Python interpreter is used
            command = [sys.executable, script_to_run, arg1, arg2, arg3, arg4, arg5]
            
            try:
                # Execute the command
                # capture_output=True captures stdout and stderr
                # text=True decodes output as text
                result = subprocess.run(command, capture_output=True, text=True, check=True)

                print(f"Successfully executed {script_to_run}")
                print("STDOUT:")
                print(result.stdout)
                if result.stderr:
                    print("STDERR:")
                    print(result.stderr)

            except subprocess.CalledProcessError as e:
                # This exception is raised if check=True and the command returns a non-zero exit code
                print(f"Error executing {script_to_run}:")
                print(f"Command: {' '.join(e.cmd)}")
                print(f"Return Code: {e.returncode}")
                print("STDOUT (if any):")
                print(e.stdout)
                print("STDERR:")
                print(e.stderr)
            except FileNotFoundError:
                print(f"Error: Python interpreter or script '{script_to_run}' not found.")
            except Exception as e:
                print(f"An unexpected error occurred: {e}")

            # Split file into variables 
            subprocess.run(["cdo", "splitname", arg2, output_split], check=True, capture_output=True, text=True)
            # Move to the next hour
            current_datetime += hourly_interval
    except ValueError as e:
        print(f"Error: Invalid date format. Please ensure inputs are in YYYYMMDDHH format. Details: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
# Define your start and end times
start_time_str = '2015020200'
end_time_str = '2015020900'

dir_2d="/share/grpeta/dsk001/dist/users/jorge/cicloneBapo/"+start_time_str+"/Eta10km_Topo1hPa/2D/"
dir_3d="/share/grpeta/dsk001/dist/users/jorge/cicloneBapo/"+start_time_str+"/Eta10km_Topo1hPa/3D/"
dirout_2d="/share/grpeta/dsk001/dist/users/jorge/cicloneBapo/"+start_time_str+"/Eta10km_Topo1hPa/netcdf/2D/"
dirout_3d="/share/grpeta/dsk001/dist/users/jorge/cicloneBapo/"+start_time_str+"/Eta10km_Topo1hPa/netcdf/3D/"
try:
    os.mkdir(dirout_2d)
    print(f"Directory '{dirout_2d}' created successfully.")
except FileExistsError:
    print(f"Directory '{dirout_2d}' already exists.")
except OSError as e:
    print(f"Error creating directory '{dirout_2d}': {e}")
try:
    os.mkdir(dirout_3d)
    print(f"Directory '{dirout_3d}' created successfully.")
except FileExistsError:
    print(f"Directory '{dirout_3d}' already exists.")
except OSError as e:
    print(f"Error creating directory '{dirout_3d}': {e}")
# Call the function to loop
Eta_data="Eta_2D_data"
Eta_levs="Eta_levels_2D"
Typ="2D"
fct_int="1"
loop_hourly_range(start_time_str, end_time_str,dir_2d,dirout_2d,Eta_data,Eta_levs,Typ,fct_int)
Eta_data="Eta_3D_data"
Eta_levs="Eta_levels_3D"
Typ="3D"
fct_int="1"
loop_hourly_range(start_time_str, end_time_str,dir_3d,dirout_3d,Eta_data,Eta_levs,Typ,fct_int)
