import os
import yaml
import logging

from videos_to_frames_file_rename import convert_video_to_frames,rename_files_in_folder

# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def run_yolov7_processor(source, weights, imgsz, trace, target_dir):
    try:
        detect = YoloV7Processor(source=source, weights=weights, imgsz=imgsz, trace=trace, target_dir=target_dir)
        detect.detect()
    except Exception as e:
        logger.error(f"Error: {e}")
        return None

if __name__ == '__main__':
    # Load configuration from YAML file
    with open('config.yaml', 'r') as f:
        config = yaml.safe_load(f)

    # Extract parameters from configuration
    video_path = config['video_path']
    frame_skip = config['frame_skip']
    output_path = config.get('output_path')
    string_to_add = config['string_to_add']
    source = config['source']
    weights = config['weights']
    imgsz = config['imgsz']
    trace = config['trace']
    target_dir = config['target_dir']

     # Convert video to frames
    logger.info("Converting to frames...") 
    output_directory = convert_video_to_frames(video_path, frame_skip, output_path)
    logging.info("Videos to frames conversion complete!")


    if output_directory:
        # Rename files in output directory    
        logger.info("Renaming Files...")    
        rename_files_in_folder(output_directory, string_to_add)
        logging.info("Files renaming complete!")

    # Run YoloV7Processor
    logger.info("Running YoloV7Processor...")
    run_yolov7_processor(source=source, weights=weights, imgsz=imgsz, trace=trace, target_dir=target_dir)
    logger.info("YoloV7Processor finished.")
