import os
import shutil
from datetime import datetime

def backup_and_empty_logs():
    # Configuration
    base_path = "/var/www/html"
    archive_dir = "/archive"
    
    # List of relative log paths
    log_paths = [
        "Strategy1_Short_Strangle_Without_SR-Daily/report.log",
        "Strategy2_Short_Straddle-Daily/report.log",
        "Strategy3_Short_Straddle-Weekly/report.log"
    ]

    # Create archive directory if it doesn't exist
    archive_folder = base_path + archive_dir
    if not os.path.exists(archive_folder):
        try:
            os.makedirs(archive_folder)
            print(f"Created directory: {archive_dir}")
        except PermissionError:
            print(f"Error: No permission to create {archive_dir}. Try running with sudo.")
            return

    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

    for relative_path in log_paths:
        full_log_path = os.path.join(base_path, relative_path)
        
        # Check if log file exists
        if os.path.exists(full_log_path):
            # Define backup filename (e.g., Strategy2_Short_Straddle-Daily_report_20231027.log)
            folder_name = relative_path.split('/')[0]
            backup_filename = f"{folder_name}_log_{timestamp}.log"
            backup_path = os.path.join(archive_folder, backup_filename)

            try:
                # 1. Copy file to /archive
                shutil.copy2(full_log_path, backup_path)
                print(f"Backed up: {full_log_path} {folder_name} -> {backup_filename}")

                # 2. Empty (truncate) the original log file
                with open(full_log_path, 'w') as f:
                    f.truncate(0)
                print(f"Emptied: {full_log_path}")

            except Exception as e:
                print(f"Failed to process {folder_name}: {e}")
        else:
            print(f"File not found, skipping: {full_log_path}")

if __name__ == "__main__":
    backup_and_empty_logs()
