from .api_workers.auth import Profile
from .files_workers.downloader import Downloader
from .files_workers.uploader import Loader
from .utils.proxies_getter import load_proxies, ProxiesManager
from .api_workers.auth import Profile
from .api_workers.file_manager_api import get_global_file_info, get_all_batch_files, get_all_global_files, delete_file_api, get_last_batch_id, get_unclose_upload_sessions
from .api_workers.tg_handle import Bot
import threading
from .schema.profile_schema import AuthShema


class FullManager:
    def __init__(self, TOKEN, CHAT_ID, profile: Profile, type_of_init: int = 0):
        self.bot = Bot(TOKEN, CHAT_ID)
        self.profile = profile
        self.want_upload_queue = []

        
        self.best_proxies = load_proxies()[:15]

        if type_of_init == 0:
            threading.Thread(target=self.get_proxies, args=(30,)).start()
        elif type_of_init == 1:
            self.get_proxies(30)

    def get_proxies(self, max_proxies):
        _, self.best_proxies, mean_speed = ProxiesManager(load_proxies()[:100]).get_best_proxies(max_proxies=max_proxies)
        print(f"\nProxies mean speed: {mean_speed:.2f} mb/s")


    def want_upload(self, *args, **kwargs):
        curr_loader, block_size, file_size = self.prepere_to_queue(*args, **kwargs)
        
        self.want_upload_queue.append(lambda: self.upload(curr_loader, *args, **kwargs))
        self.run_queue(True)

        return {
            "upload_session_id": curr_loader.upload_session_id,
            "block_size": block_size,
            "file_size": file_size
        }

    def run_queue(self, isFromClient: bool):
        if isFromClient:
            if len(self.want_upload_queue) == 1:
                pass
            else:
                return
        else:
            if len(self.want_upload_queue) > 0:
                pass
            else:
                return
            
        threading.Thread(target=self.want_upload_queue[0]).start()

    def prepere_to_queue(self, file_path, block_size=10, max_pool_blocks=5, custom_bar_func=None, upload_session=None, start_index=0):
        with open(file_path, "rb") as file:
            l = Loader(file, self.bot, self.profile, proxies=self.best_proxies)
            if upload_session is None:
                l.init_global_file(file_path=file_path)
            else:
                l.upload_session_id = upload_session

            file_size = l.file_size

        return l, block_size, file_size

    def download(self, global_file_id, output_folder: str, max_proxies=15, max_block_pool=10, custom_bar_func=None):
        file_info = get_global_file_info(profile=self.profile, global_file_id=global_file_id)
        files_data = get_all_batch_files(self.profile, global_file_id=global_file_id)["files_data"]

        all_urls = [el["file_tg_hash"] for el in files_data]

        d = Downloader(self.bot, proxies=self.best_proxies)
        d.download(all_urls, f"{output_folder}\\{file_info["file_name"]}", max_blocks_pool=max_block_pool, progress_fun=custom_bar_func)

    def upload(self, l: Loader, file_path, max_proxies=15, block_size=10, max_pool_blocks=5, custom_bar_func=None, start_index=0, upload_session=None):

        with open(file_path, "rb") as file:
            l.file = file
            l.split_info(block_size * 1024 * 1024, max_pool_blocks, progress_fun=custom_bar_func, start_index=start_index)

        self.want_upload_queue.pop(0)
        self.run_queue(False)


        return l.upload_session_id
    

class TgSaver:
    def __init__(self, auth_data: AuthShema):
        self.profile = Profile("")
        status, message = self.profile.login_user(auth_data)

        if status == False:
            raise Exception(f"incorrect auth {message}")
        
        bot_data = self.profile.get_tg_info()
        self.TOKEN, self.CHAT_ID = bot_data["BOT_TOKEN"], bot_data["CHAT_ID"]


        self.manager = FullManager(self.TOKEN, self.CHAT_ID, self.profile, type_of_init=1)
        
    def upload_file(self, path: str):
        base_file_info = self.manager.want_upload(path)
        return base_file_info
    
    def download_file(self, output_path: str, global_file_id: int):
        self.manager.download(global_file_id, output_path)

    def get_all_global_files(self):
        return get_all_global_files(self.profile)
    

if __name__ == "__main__":
    tg_saver = TgSaver(AuthShema(login="test", password="test"))
    print(tg_saver.get_all_global_files())
    tg_saver.upload_file(r"C:\Users\huina\Videos\2025-07-11 14-01-30.mp4")
    # tg_saver.download_file(r"C:\Users\huina\Python Projects\Test Projects\TEST_LIB\test_download", 25)
