import json
import logging

import requests
from constance import config

from intranet.femida.src.core.workflow import WorkflowError


logger = logging.getLogger(__name__)


class FrontendManifestError(WorkflowError):
    pass


def get_manifest(version):
    manifest_url = f'https://yastat.net/{config.FRONT_STATIC_PATH}/{version}/manifest.json'

    try:
        response = requests.get(manifest_url)
        response.raise_for_status()
        return response.json()
    except (requests.RequestException, ValueError):
        logger.exception('Failed to change frontend version')
        raise FrontendManifestError('cannot_get_manifest')


def update_manifest(old_version, new_version):
    manifest = get_manifest(new_version)
    config.FRONT_STATIC_ASSETS = json.dumps(manifest)
    logger.info('Frontend version changed from %s to %s', old_version, new_version)
