import os
import sys
import time


from CommonCode import wq, kwq
sys.path.insert(0, "/home/thebears/Source/ml/sources_mltraining/scoring_scheduler")
sys.path.insert(0, "/home/thebears/Source/ml/sources_mltraining/model_runner/")
from purge_without_birds import execute_file_purging

from video_reduce_resolution import convert_file

input_topic = wq.TOPICS.ml_vision_objdet_results_pg_success
output_if_success = wq.TOPICS.ml_vision_objdet_results_purge_success
output_if_fail = wq.TOPICS.ml_vision_objdet_results_purge_failed
output_if_skipped = wq.TOPICS.ml_vision_objdet_results_purge_skipped


topic_if_has_nuggets = kwq.TOPICS.exit_40_videos_with_nuggets
topic_if_no_nuggets = kwq.TOPICS.exit_40_videos_without_nuggets



def perform_loop():
    file_to_score = wq.consume(input_topic)
    if file_to_score is None:
        return

    try:
        purged_result = execute_file_purging(files_to_check=file_to_score)
        did_purge = False
        if purged_result is not None and len(purged_result) > 0:
            did_purge = purged_result[0]
            
        if did_purge:
            wq.publish(output_if_success, file_to_score)
            print(f"File purged {file_to_score}")
            kwq.publish(topic_if_no_nuggets, file_to_score)
        else:
            wq.publish(output_if_skipped, file_to_score)
            print(f"File not purged {file_to_score}")
            kwq.publish(topic_if_has_nuggets, file_to_score)

    except Exception as e:
        wq.publish(output_if_fail, {file_to_score: str(e)})
        print(f"File failed to purge {file_to_score}, {e}")


# %%
while True:
    perform_loop()
    time.sleep(1)
