import os
import sys
from pathlib import Path

from speedbuild.experimentation.v2.agent import SpeedBuildAgentV2
from speedbuild.utils.cleanup.template.clear_folder import clear_folder 
from speedbuild.utils.exec.runCommand import PythonExecutor 
from speedbuild.agents.debugCustomizer.agent import SpeedBuildWorkflow 
from speedbuild.utils.exec.sb_exec_utils import create_virtual_environment, install_packages_in_venv 

from ..deployment.deploy_features import implementFeature

class SpeedBuildTestAgent():
    def __init__(self):
        self.home = str(Path.home())
        self.environment_sb_path = os.path.join(self.home,".sb","environment")
        self.executor = PythonExecutor()
        venv_path = os.path.join(self.home,".sb","environment","django","venv")

        if sys.platform == "win32":
            python_path =  os.path.join(venv_path, "Scripts", "python.exe")
        else:
            python_path = os.path.join(venv_path, "bin", "python")

        # Modify environment to use the venv
        self.env = os.environ.copy()
        self.env['VIRTUAL_ENV'] = venv_path
        
        if sys.platform == "win32":
            self.env['PATH'] = f"{os.path.join(venv_path, 'Scripts')};{self.env['PATH']}"
        else:
            self.env['PATH'] = f"{os.path.join(venv_path, 'bin')}:{self.env['PATH']}"


    def installAndCreateDjangoProject(self,venv):
        res = create_virtual_environment(venv)
        installation_successful = install_packages_in_venv(os.path.join(venv,"venv"),["django"])
        # print("## virtual environment is ",self.env)
        if installation_successful:

            self.venv_path = os.path.join(venv,"venv")
            # print("### here")
            # create django project
            res = self.executor.runCommand(
                ["django-admin","startproject","speedbuild_project"],
                True,
                env=self.env,
                cwd=os.path.join(self.home,".sb","environment","django")
            )

            # TODO : scheck response to see if it was succesful

            # create django app
            res = self.executor.runCommand(
                ["python","manage.py","startapp","speedbuild_app"],
                True,
                env=self.env,
                cwd=os.path.join(self.home,".sb","environment","django","speedbuild_project")
            )

            # print(res)

            # add urls.py file
            with open(os.path.join(self.home,".sb","environment","django","speedbuild_project","speedbuild_app","urls.py"),"w") as app_url:
                app_url.write("""from django.urls import path\n\n# speedbuild_app\nurlpatterns = [\n\n]""".strip())

            # shutil.copy("/home/attah/Documents/sb_final/speedbuild/exec/app_urls.py", "/home/attah/.sb/environment/django/speedbuild_project/speedbuild_app/urls.py")

            # include new urls file in main urls file
            with open(os.path.join(self.home,".sb","environment","django","speedbuild_project","speedbuild_project","urls.py"),"w") as main_url:
                main_url.write("""from django.contrib import admin\nfrom django.urls import path, include\n\nurlpatterns = [\n\tpath('admin/', admin.site.urls),\n\tpath('speedbuild/',include("speedbuild_app.urls"))\n]""".strip())
            
            # shutil.copy("/home/attah/Documents/sb_final/speedbuild/exec/main_urls.py", "/home/attah/.sb/environment/django/speedbuild_project/speedbuild_project/urls.py")


    def createTestEnvironment(self,framework):
        environment_path = os.path.join(self.environment_sb_path,framework)

        # clear out existing project
        clear_folder(environment_path)

        if not os.path.exists(environment_path):
            os.makedirs(environment_path,exist_ok=True)

        action = self.installAndCreateDjangoProject(environment_path)

        return os.path.join(environment_path,"speedbuild_project")


    def testAndFixErrors(self):
        # run server -- check for error / test feature, troubleshoot and fix issues
        pass


    def deployFeatureInTestEnvironment(self,template_path,project_path):
        """Call speedbuild function to deploy code in test environment and also add speedbuild_app to installed apps"""

        implementFeature(template_path,project_path,"speedbuild_app",None,True,self.venv_path)


    def migrateTestAndFixErrors(self,max_debugger_count=3):
        commands = [
            "python manage.py makemigrations",
            "python manage.py migrate",
            "python manage.py runserver"
        ]

        speedbuild_agent = SpeedBuildAgentV2("django",True)

        # if prompt == None: # normal debugging
        
        # Create workflow for debugging a specific command
        llm_agent = SpeedBuildWorkflow("django")
        llm_agent.create_debugger_workflow() # remove this
            
        # # Run the initial failing command to get the first error
        # llm_agent.run(context)

        ran_debug = False
        
        for command in commands:
           # Get initial error and command output
            no_errors,stdout,stderr = llm_agent.run_shell_command(command)

            if not no_errors:
                ran_debug = True
                # llm_agent.last_error = stderr 
                # llm_agent.last_command_output = stdout
                # llm_agent.original_command = command

                command_info = f"""
                command : {command}
                --------------------------------

                stdout : {stdout}
                --------------------------------

                error : {stderr}
                """

                speedbuild_agent.run(command_info)
        
        return ran_debug

    def getPackagesinVenv(self):
        collected_packages = set()
        res,err = self.executor.runCommand(
            ["pip","list"],
            False,
            env=self.env,
            cwd=os.path.join(self.home,".sb","environment","django")
        )
        
        for i in res[2:]:
            pac = [x.strip() for x in i.split(" ") if len(x)>0]
            if(len(pac)==2):
                collected_packages.add(f"{pac[0]}=={pac[1]}")

        return collected_packages

    def TestFeature(self,template_path):
        project_path = self.createTestEnvironment("django")
 
        # deploy template [add speedbuild_app to INSTALLED_APPS settings file]
        self.deployFeatureInTestEnvironment(template_path,project_path)

        packages = self.getPackagesinVenv()

        # raise ValueError("error")

        # fix error
        ran_debug = self.migrateTestAndFixErrors()

        return [ran_debug,packages]


    def customize_feature_code(self,prompt,files,root_path):

        speedbuild_agent = SpeedBuildAgentV2("django")

        # llm_agent = SpeedBuildWorkflow("django")
        # if prompt == None: # normal debugging
        
        # Create workflow for debugging a specific command
        # llm_agent.create_debugger_workflow("customization")

        # llm_agent.last_command_output = f"""
        # customization prompt : **{prompt}**
        # project root path : **{root_path}***
        # project files : {files}
        # """

        # llm_agent.run()
        speedbuild_agent.run(prompt)

        # if llm_agent.success:
        #     print("Customization successful")
        #     return True
        # else:
        #     print("workflow ended without resolution")
        #     return False
