import os
import uuid
import json
import time
import requests
import datetime
import dicttoxml
from loguru import logger
from urllib.parse import urlparse
from moviepy.editor import VideoFileClip


#🚀 working good
def execute_time(func):
    def wrapper(*args, **kwargs):
        start_time = datetime.datetime.now()
        result = func(*args, **kwargs)
        end_time = datetime.datetime.now()
        logger.debug(f"Function '{func.__name__}' called with arguments: {args} {kwargs}")
        logger.debug(f'Time taken by {func.__name__}: {(end_time - start_time).total_seconds()} seconds')
        return result
    return wrapper

#🚀 working good
# @execute_time
def find_static_folder_path():
    current_dir = os.getcwd()

    while True:
        static_folder_path = os.path.join(current_dir, "static")
        if os.path.isdir(static_folder_path):
            return static_folder_path
        
        parent_dir = os.path.dirname(current_dir)
        if parent_dir == current_dir:
            break
        
        current_dir = parent_dir

    return None

#🚀 working good
@execute_time
def generate_unique_filename(extension):
    unique_id = uuid.uuid4().hex
    current_date = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
    return f"{unique_id}_{current_date}{extension}"

#🚀 working good
@execute_time
def extract_title_and_duration(url):
    response = requests.head(url)
    content_type = response.headers.get("content-type")

    if "video" not in content_type:
        raise ValueError("The provided URL does not point to a video")

    filename = urlparse(url).path.split("/")[-1]
    duration = get_file_duration(url)
    return filename, duration

#🚀 working good
@execute_time
def get_file_duration(file_path):
    clip = VideoFileClip(file_path)
    duration = clip.duration
    clip.close()
    return duration

#🚀 working good
# @execute_time
def seconds_to_hhmmss(seconds):
    return (datetime.datetime(1,1,1) + datetime.timedelta(seconds=seconds)).strftime("%H:%M:%S.%f")[:-3]

#🚀 working good
# @execute_time
def combine_json_files(folder_path, total_frames, interval, save_xml):
    while True:
        # initialize an empty list to store the contents of the JSON files
        json_files = []
        # loop through all files in the folder
        for filename in os.listdir(folder_path):
            # print(filename)
            # check if the file is a JSON file
            if filename.endswith(".json"):
                # read the contents of the file
                with open(os.path.join(folder_path, filename), "r") as file:
                    json_files.append(json.load(file))
        # check if the number of JSON files is equal to (total_frames/interval)
        if [len(json_files) == ((total_frames//interval)+1)]:

            file_name = "_".join((folder_path.split("/"))[-2:])
            json_files = sorted(json_files, key=lambda x: x["frame_id"])
            # combine the contents of the JSON files into a single dictionary
            # write the combined JSON to a file
            final_file = f'{find_static_folder_path()}/{file_name}.json'
            with open(final_file, "w") as file:
                json.dump(json_files, file)

            if save_xml :
                xml = dicttoxml.dicttoxml(json_files)
                with open(file_name + ".xml", "wb") as file:
                    file.write(xml) 
            break
        else:
            # wait for 10 mili-second before checking again
            time.sleep(0.001)
    
    return final_file