import argparse
import textwrap
import pyfiglet
import random
import os
import subprocess
from termcolor import colored
from tqdm import tqdm
import time


class CommandLine: 
    """
    Execute scripts on the CLI.
    """

    def __init__(self):
        self.folder = None 
        self.lib = []
        self.tests_to_execute = None
        
    def execute(self, tests):
        print("--------------------------------------------------------------")
        test_file = input(colored("Enter the name of the test project file: ", "cyan"))
        total_tests = len(tests)
        print(colored(f"Preparing to execute {total_tests} test(s)...\n", "yellow"))
        for i, test in enumerate(tests, 1):
            print(colored(f"🚀 Starting test: {test} ({i}/{total_tests})", "blue"))
            try:
                result = subprocess.run(
                        ["robot", f"tests/{test_file}/{test}"],
                        capture_output=True,
                        text=True,
                    )

                print(colored(f"\n✅ Test {test} executed successfully. Check the report below !", "green"))
                print(colored(f"\n--- Output for {test} ---", "yellow"))
                print(result.stdout)


            except subprocess.CalledProcessError as e:
                print(colored(f"❌ Test {test} failed with return code {e.returncode}", "red"))
            except Exception as ex:
                print(colored(f"❌ An error occurred during {test}: {ex}", "red"))
                
            print("--------------------------------------------------------------")



    def initialisation(self): 
        print("--------------------------------------------------------------")
        print("Initialise un projet de test")
        print("--------------------------------------------------------------")


def main(): 

    fond = pyfiglet.FigletFont.getFonts()
    colors = ["red", "green", "yellow", "blue", "magenta", "cyan", "white"]
    choix_fond = random.choice(fond)
    choix_couleur = random.choice(colors)
    banner = pyfiglet.figlet_format("DTEP TEST", font=choix_fond)
    final_banner = colored(banner,color=choix_couleur)
    print(final_banner)  
    
    
    robotisation = CommandLine()
    parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
        description=textwrap.dedent('''\
            dtep-test simplifies your test execution with robotFramework in the ICDC context
            --------------------------------------------------------------------------------
            The files generated by the script are located in the current directory
            For more, see the help function
            Install the tool with the command : pip install dtep-test
        '''))
    
    
    parser.add_argument("-lib", required=False,help="Specify the libraries you want to use by giving its path if you have created it")
    parser.add_argument("-execute", required=True,nargs='+',dest="tests_to_execute",help="Specify the test you want to execute")
    parser.add_argument("-init", required=False,help="Initialize a test project")
    parser.add_argument("-output",required=False, help="Give an output folder to save the reports")

    args = parser.parse_args()
    try: 
        print("ok*****************************************************************************************************************************************************")
        robotisation.folder = args.output
        robotisation.tests_to_execute = args.tests_to_execute
        robotisation.lib = args.lib
        print("ok*****************************************************************************************************************************************************")
        try : 
            tests_to_execute = robotisation.tests_to_execute
            robotisation.execute(tests_to_execute)
        except Exception as e :
            print(e)
            print("Check the existence of your robot(s) file")
    except Exception as e: 
        print(e)
        print("Please check your parameters")

if __name__ == "__main__": 
    main()
