import os
from pathlib import Path

from speedbuild.utils.exec.sb_exec_utils import install_packages_in_venv
from speedbuild.utils.markdown.yaml import read_yaml 
from speedbuild.agents.break_query.break_prompt import splitPrompt 
from speedbuild.frameworks.django.utils.venv_utils import get_activated_venv 
from speedbuild.frameworks.django.extraction.test_agent import SpeedBuildTestAgent 
from speedbuild.frameworks.django.deployment.move_django_to_target import moveFilesToTargetProject 

def getTemplateFileNames(path):
    file_paths = []
    for root, _, files in os.walk(path):
        if "node_modules" in root:
            continue
        for file in files:
            # Get the absolute path by joining root and file
            absolute_path = os.path.join(root, file)
            file_paths.append(absolute_path)
    return file_paths

def getProjectFiles(path):
    file_paths = []
    for root, _, files in os.walk(path):
        if "node_modules" in root or "__pycache__" in root or "migrations" in root:
            continue
        for file in files:
            # Get the absolute path by joining root and file
            absolute_path = os.path.join(root, file)
            file_name = absolute_path.replace(path,"").lstrip("/")
            if os.path.basename(file_name) not in ["__init__.py","apps.py",".speedbuild","manage.py"] and file_name.endswith("sqlite3")==False:
                file_paths.append(file_name)
    return file_paths


def testCustomizeAndDeployDjangoFeature(feature_template,target_destination,target_app_name,customize=False):
    files = getProjectFiles(target_destination)
    target_project_name = None

    for file in files:
        if os.path.basename(file) == "settings.py":
            target_project_name = os.path.dirname(file)
    
    if target_project_name == None:
        raise ValueError("Could not detect project name, could not locate the settings.py file")
    
    
    test_environment = os.path.join(str(Path.home()),".sb","environment","django","speedbuild_project") 
    djangoAgent = SpeedBuildTestAgent()


    djangoAgent.TestFeature(feature_template) #debug feature

    # ask for customization prompt
    if customize:
        prompt = input("Enter customization prompt, be as detailed as possible : \n")

        # TODO : break prompt into simple steps
        customize_prompts = splitPrompt(prompt)

        for prompt in customize_prompts:
            print("Processing",prompt)
            files = getProjectFiles(test_environment) 
            status = djangoAgent.customize_feature_code(prompt,files,test_environment)

        # TODO : if could not customize break out 

    # move feature code to target destination
    moveFilesToTargetProject(
        test_environment,
        target_destination,
        target_project_name,
        target_app_name
    )

    # install packages in target destination
    # print("Installing Feature dependencies")

    config_name = feature_template.replace("speed_build_","")
    template_root = os.path.join(str(Path.home()),".sb","sb_extracted") #os.path.join(str(Path.home()),".sb_zip")
    venv = get_activated_venv()

    yaml_path = os.path.join(template_root,feature_template,f"sb_{config_name}.yaml")

    # if ":" in feature_template:
    #     template_name, version = feature_template.split(":")

    #     yaml_path = os.path.join(template_root,template_name.strip(),version.strip(),f"sb_{config_name}.yaml")
    # else:
    #     version = "lts"
    #     yaml_path = os.path.join(template_root,feature_template,version,f"sb_{config_name}.yaml")
    
    if not os.path.exists(yaml_path):
        raise ValueError(f"Template {yaml_path} does not exist")
    
    template_yaml = read_yaml(yaml_path)

    print("Installing Feature dependencies")
    install_packages_in_venv(venv,template_yaml['dependencies'])