import json
import os
import requests
from pathlib import Path

from speedbuild.auth.serverCall import getRequestHeaders, manageServerCall,url_address


"""
    Code to pull template from speedbuild hub. 
"""

def download_file(url, save_folder, filename,data):
    data['download'] = True

    # Ensure the folder exists
    os.makedirs(save_folder, exist_ok=True)
    
    # If no filename provided, extract from URL
    if not filename:
        filename = url.split("/")[-1] or "downloaded_file"
    
    file_path = os.path.join(save_folder, filename)

    # get access_token

    # Stream download to handle large files
    with requests.post(url,data=data,headers=getRequestHeaders(), stream=True) as response:
        response.raise_for_status()  # Raise error for bad responses (4xx, 5xx)
        with open(file_path, "wb") as file:
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:  # Filter out keep-alive chunks
                    file.write(chunk)

    print(f"✅ File saved to: {file_path}")
    return file_path

def pullTemplateFromHub(template_name):
    """
        repo_name
        template_name
        version
    """

    data = {
        "repo_name" : os.path.dirname(template_name),
    }

    template_name = os.path.basename(template_name)
    version = "lts"

    if ":" in template_name:
        template_name,version = template_name.split(":")
        data['version'] = version

    data["template_name"] = os.path.basename(template_name)

    if not template_name.startswith("speed_build_"):
        template_name = "speed_build_"+template_name

    save_path = os.path.join(str(Path.home()),".sb_zip",template_name)

    # TODO get and save template history
    success, res = manageServerCall("POST","api/pull-template/",data,{},True)

    if success:
        # save history file
        if not os.path.exists(save_path):
            os.makedirs(save_path,exist_ok=True)

        with open(os.path.join(save_path,"history.json"),"w") as file:
            json.dump(res,file,indent=4)
    else:
        raise ValueError(res)

    url = url_address + "api/pull-template/"
    
    # download template
    save_full_path = os.path.join(save_path,f"{version}.zip")
    save_folder = os.path.dirname(save_full_path)
    filename = os.path.basename(save_full_path)

    download_file(url,save_folder,filename,data)

    return template_name

