import httpx
from aext_panels_server.api import PythonAnywhereAPI
from aext_panels_server.const import ACCESS_LOG, ERROR_LOG, PROJECT_LOG_PATH, SERVER_LOG
from aext_panels_server.schemas import MetaResponse, RequestError, ServiceResponse
from aext_panels_server.utils import call_api


class PanelService:
    async def get_app_log(self, api: PythonAnywhereAPI, domain: str, log_type: str) -> ServiceResponse:
        """
        Panel app custom_logger. This function will fetch log file for a Panel app.
        Parameters
        ----------
        api: PythonAnywhereAPI
        domain: Project domain
        log_type: [access_log|error_log]

        Returns
        -------
        ServiceResponse
        """
        if log_type not in [ACCESS_LOG, ERROR_LOG, SERVER_LOG]:
            return ServiceResponse(
                meta=MetaResponse(
                    error=RequestError(
                        status=True,
                        message="Project log does not exit",
                    )
                ),
                content=None,
            )

        log_file_name = {
            ACCESS_LOG: f"{domain}.access.log",
            SERVER_LOG: f"{domain}.server.log",
            ERROR_LOG: f"{domain}.error.log",
        }

        log_path = f"{PROJECT_LOG_PATH}/{log_file_name[log_type]}"

        err, response = await call_api(
            api.download_file(log_path, include_root_path=False),
            always_return_response=True,
        )

        if not err.status:
            return ServiceResponse(
                meta=MetaResponse(error=RequestError(status=False)),
                content=response.text,
            )

        if not response:
            return ServiceResponse(
                meta=MetaResponse(
                    error=RequestError(
                        status=True,
                        message="Unexpected error while fetching project log",
                    )
                ),
                content=None,
            )

        if err.status:
            err_resp = ServiceResponse(
                meta=MetaResponse(
                    error=RequestError(
                        status=True,
                    )
                ),
                content=None,
            )
            if response.status_code == httpx.codes.NOT_FOUND:
                err_resp.set_error_message("Index file not found")
            elif response.status_code == httpx.codes.UNAUTHORIZED:
                err_resp.set_error_message("Failed to fetch index - Unauthorized")
            else:
                err_resp.set_error_message(f"Failed to fetch index - {err.message}")
            return err_resp
        return ServiceResponse(meta=MetaResponse(error=RequestError(status=False)), content=response.text)


panel_service = PanelService()
