import time
import platform
import shutil

from typing import Dict
from fastapi import APIRouter
from fastapi.responses import FileResponse

from scripts.constants.app_constants import Build_engine_api
from scripts.core.build_engine_handler import build
from scripts.utils.logger import logger
from scripts.config.json_reader import git_config

build_engine_router = APIRouter()


@build_engine_router.post(f"{Build_engine_api.engine_endpoint}")
def build_engine(git_data: Dict):
    logger.info('POST: build_engine')

    # POST method
    channel_data = dict()

    # channel data for build
    channel_data['timestamp'] = int(time.time()) * 1000
    channel_data['repository'] = git_data['repository']
    channel_data['branch'] = git_data['branch']

    # Build
    build(channel_data=channel_data)

    return 'received', 200


@build_engine_router.get(f"{Build_engine_api.download}")
def build_engine(repository: str):
    logger.info('GET: download')

    file_path = git_config[repository]['directory'][platform.system().lower()] + repository + '/' + git_config[
        repository]['build'] + git_config[repository]['branch']

    shutil.make_archive('zips/acquisition_engine', 'zip', file_path)
    # make_zip = f"tar.exe -a -c -f {} {}"

    return FileResponse(path=f"zips/acquisition_engine.zip")
