# coding: utf-8
import os
from typing import Dict, List, Union, Any  # noqa: F401

from aiofiles.os import listdir
from fastapi import (  # noqa: F401
    APIRouter,
    Body,
    Cookie,
    Depends,
    Form,
    Header,
    Path,
    Query,
    Response,
    Security,
    status,
    HTTPException,
)
from fastapi.responses import FileResponse
from starlette.background import BackgroundTasks

from server.data.definitions import Groups, API_SUB_PATH, ECP_APP_FILES_DIR, Paths
from server.models.error import Error
from server.models.extra_models import TokenModel  # noqa: F401
from server.models.file import File
from server.security_api import get_token_ApiKeyAuth, checkTokenCapabilities
from server.utils.files import buildArchive
from . import appData

router = APIRouter(prefix=API_SUB_PATH)


# Get from environment variable the value, otherwise it takes the default value
PATH_ECP_APP_DIR = f"{os.environ.get(ECP_APP_FILES_DIR, Paths.DEFAULT_ECP_APP_DIR.value)}"
PATH_ECP_BASE_CONFIGS_DIR = f"{PATH_ECP_APP_DIR}/{Paths.ECP_BASE_CONFIGS_SUBDIR.value}"


@router.get(
    "/baseconfigs",
    responses={
        200: {"model": List[File], "description": "Gets all base config files."},
        400: {"model": Error, "description": "Bad request."},
        401: {"model": Error, "description": "Unauthorized."},
    },
    tags=["baseConfig"],
    response_model_by_alias=True,
)
async def baseconfigs_get(
    background_tasks: BackgroundTasks,
    onlyList: bool = Query(False, description="The boolean for activating only list mode."),
    token_ApiKeyAuth: TokenModel = Security(get_token_ApiKeyAuth),
) -> Union[List, Any]:
    """Get all the available base config files."""
    # ------------------------------------------- Check token capabilities -------------------------------------------

    isTokenGranted = await checkTokenCapabilities(token=token_ApiKeyAuth, group=Groups.EDIT_CONFIG.value)

    # ------------------------------------- return the content -------------------------------------

    files = await listdir(PATH_ECP_BASE_CONFIGS_DIR)
    if onlyList:
        return [{"id": file_name} for file_name in files]
    else:

        zipPath, zipName = await buildArchive(
            serial=appData.serial,
            ecpVersion=appData.ecpVersion,
            fileName="logs",
            filePaths=[PATH_ECP_BASE_CONFIGS_DIR],
            files=files,
        )

        background_tasks.add_task(os.unlink, zipPath)

        return FileResponse(
            zipPath,
            media_type="application/x-zip-compressed",
            headers={"Content-Disposition": f'attachment; filename="{zipName}.zip"'},
        )
