import os
import zipfile
import shutil

from ..config import load_and_validate_config
from ..repos import APIRepo


def create_zip_from_folders(folders, files, zip_path, root):
    parent_root = os.path.dirname(root)
    with zipfile.ZipFile(zip_path, "w") as zipf:
        for folder in folders:
            for folderName, subfolders, filenames in os.walk(folder):
                for filename in filenames:
                    filePath = os.path.join(folderName, filename)
                    zipf.write(filePath, os.path.relpath(filePath, parent_root))
        for file in files:
            zipf.write(file, os.path.relpath(file, parent_root))


def deploy_folder(user, path, typer, verbose=False):
    config = load_and_validate_config(path, typer, verbose=verbose)
    typer.echo(f"Deploying...")
    # zip the folder
    folders, files = [], []
    for script in config.scripts:
        folders.append(f"{path}/scripts/{script.name}")
    for api in config.apis:
        folders.append(f"{path}/apis/{api.name}")
    files.append(f"{path}/spai.config.yaml")
    dst_path = f"/tmp/spai"
    os.makedirs(dst_path, exist_ok=True)
    zip_path = f"{dst_path}/{config.project}.zip"
    create_zip_from_folders(folders, files, zip_path, root=config.project)
    # send to api for deployment
    repo = APIRepo()
    data, error = repo.deploy_folder(user, zip_path)
    # clean up
    shutil.rmtree(dst_path)
    if data:
        typer.echo(
            # f"Check status at {os.getenv('SPAI_UI_URL', 'https://spai.earthpulse.ai')}/dashboard/{data}"
            f"Check status at {os.getenv('SPAI_UI_URL', 'https://localhost:5173')}/dashboard/{data}"
        )
    raise Exception(f"Error: {error}")
