import os
import glob
import shutil
from datetime import datetime, timedelta

# Search pattern for input files
input_files = glob.glob("Radiometer_*.dat")

for file_path in input_files:
    with open(file_path, "r") as f:
        lines = f.readlines()
        if not lines:
            print(f"Skipping empty file: {file_path}")
            continue
        last_line = lines[-1].strip()

    try:
        # Extract timestamp from the first 20 characters
        timestamp_str = last_line[1:20]  # removes leading quote
        timestamp = datetime.strptime(timestamp_str, "%Y-%m-%d %H:%M:%S")

        # Subtract one hour
        timestamp -= timedelta(hours=1)

        # Build new filename and path
        date_str = timestamp.strftime("%Y%m%d_%H0000")
        new_filename = f"{date_str}_radiometer.dat"
        folder_path = os.path.join(f"Y{timestamp.strftime('%Y')}",
                                   f"M{timestamp.strftime('%m')}",
                                   f"D{timestamp.strftime('%d')}")
        os.makedirs(folder_path, exist_ok=True)

        # Final destination path
        destination = os.path.join(folder_path, new_filename)

        # Move and rename the file
        shutil.move(file_path, destination)
        print(f"Moved '{file_path}' -> '{destination}'")

    except Exception as e:
        print(f"Failed to process {file_path}: {e}")

