# coding: utf-8

from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

from cachetools import cached, LRUCache

from saas.library.python.nanny_rest.recipe import AlemateRecipe
from saas.library.python.nanny_rest.tickets_integration.tickets_integration_rule import SimpleTicketIntegrationRule
from saas.library.python.nanny_rest.tickets_integration import (
    TicketsIntegration, ReleaseType, InstancectlReleaseRule, AutocommitSettings
)
from saas.library.python.nanny_rest.resource import StaticFile


@cached(cache=LRUCache(maxsize=None))
def _get_proxy_service_recipes(loc):
    common_context = {
        'manual_confirm': True,
        'stop_degrade_level': '0.02',
        'operating_degrade_level': 0.08,
        'activate_sas_no_confirm': True,
        'max_degrade_speed': '0.0022',
        'geo': loc
    }

    activate = AlemateRecipe(
        id='common',
        name='deploy_saas_by_loc.yaml',
        desc='Common deploy script',
        context=common_context
    )

    no_confirm_activate = AlemateRecipe(
        id='common_no_confirm',
        name=activate.name,
        desc='Common deploy script [no confirm]',
        context=common_context
    )

    prepare = AlemateRecipe(
        id='prepare',
        name='_prepare_service_configuration.yaml',
        desc='Common prepare script',
        context={
            'prepare_operating_degrade_level': 0.3
        }
    )

    return activate, no_confirm_activate, prepare


def proxy_service(ctype, loc, sandbox_files, infra_notifications_settings=None, abc_service_id=664):
    release_type = ReleaseType.stable
    tickets_integration = TicketsIntegration(
        service_release_tickets_enabled=True,
        service_release_rules=[
            SimpleTicketIntegrationRule('BUILD_RTYSERVER', 'RTYSERVER_SEARCHPROXY', 'binary', release_type),
            SimpleTicketIntegrationRule('BUILD_RTYSERVER_CONFIG', None, 'loop_conf + loop_data', release_type),
            SimpleTicketIntegrationRule('BUILD_STATBOX_PUSHCLIENT', 'STATBOX_PUSHCLIENT', 'push-client', ReleaseType.stable)
        ],
        instancectl_release_rule=InstancectlReleaseRule(
            match_release_type=ReleaseType.stable, auto_commit_settings=AutocommitSettings(True, mark_as_disposable=True)
        )
    )
    infra_notifications_settings = infra_notifications_settings if infra_notifications_settings is not None else {}
    info_attrs = {
        'category': '/saas/{}'.format(ctype),
        'recipes': {
            'content': [recipe.dict() for recipe in _get_proxy_service_recipes(loc)]
        },
        'labels': AlemateRecipe.dict_to_list({
            'ctype': 'prod',
            'itype': 'searchproxy',
            'prj': ctype.yasm_prj_prefix,
            'geo': loc
        }),
        'infra_notifications': infra_notifications_settings,
        'tickets_integration': tickets_integration.dict(),
        'abc_group': abc_service_id,
        'queue_id': 'SAAS',
        'desc': '{ctype} {loc}'.format(ctype=ctype, loc=loc)
    }
    runtime_attrs = {
        'resources': {
            'static_files': [StaticFile('saas_ctype', content=ctype.name).dict()],
            'sandbox_files': [f.dict() for f in sandbox_files]
        },
        'engines': {'engine_type': 'YP_LITE'},
        'instances': {
            'chosen_type': 'YP_POD_IDS',
            'yp_pod_ids': {
                'orthogonal_tags': {
                    'metaprj': 'saas',
                    'itype': 'searchproxy',
                    'ctype': str(ctype.kind),
                    'prj': ctype.yasm_prj_prefix
                }
            }
        },
        'instance_spec': {
            'auxDaemons': [{
                'type': 'LOGROTATE'
            }],
            'containers': [{
                'name': 'saas_daemon',
                'restartPolicy': {
                    'maxPeriodSeconds': 60,
                    'type': 'ALWAYS',
                    'periodBackoff': 2,
                    'minPeriodSeconds': 1,
                    'periodJitterSeconds': 20
                },
                'command': [],
                'env': [
                    {
                        'valueFrom': {'literalEnv': {'value': ctype.name}, 'type': 'LITERAL_ENV'},
                        'name': 'CUSTOM_CTYPE'
                    },
                ],
                'readinessProbe': {
                    'periodBackoff': 2,
                    'handlers': [],
                    'initialDelaySeconds': 5,
                    'successThreshold': 0,
                    'maxPeriodSeconds': 60,
                    'minPeriodSeconds': 5,
                    'failureThreshold': 0
                },
                'coredumpPolicy': {
                    'coredumpProcessor': {
                        'totalSizeLimit': 10240,
                        'probability': 100,
                        'aggregator': {
                            'type': 'DISABLED',
                            'saas': {
                                'url': 'http://cores.n.yandex-team.ru/corecomes',
                                'gdb': {
                                    'type': 'LITERAL',
                                    'execPath': '/usr/bin/gdb'
                                },
                                'serviceName': ''
                            }
                        },
                        'cleanupPolicy': {
                            'type': 'DISABLED',
                            'ttl': {
                                'seconds': 3600
                            }
                        },
                        'countLimit': 3,
                        'path': '/cores'
                    },
                    'customProcessor': {
                        'command': ''
                    },
                    'type': 'COREDUMP'
                }
            }],
            'instanceAccess': {'skynetSsh': 'ENABLED'},
            'layersConfig': {
                'layer': [{
                    'url': [
                        'rbtorrent:29f1d6043cff0ae62f2bc876dcfe39fecf72c16a'
                    ],
                    'fetchableMeta': {
                        'type': 'SANDBOX_RESOURCE',
                        'sandboxResource': {
                            'resourceType': 'PORTO_LAYER_SEARCH_UBUNTU_PRECISE_APP',
                            'resourceId': '779126510',
                            'taskId': '350509985',
                            'taskType': 'BUILD_PORTO_LAYER'
                        }
                    }
                }]
            },
            'type': 'SANDBOX_LAYERS'
        }
    }
    auth_attrs = {
        "observers": {"logins": [], "groups": []},
        "owners": {"logins": ["saku", "salmin", "i024", "coffeeman", "vbushev"], "groups": ["29985"]},
        "conf_managers": {"logins": ["nanny-robot"], "groups": []},
        "ops_managers": {"logins": [], "groups": []}
    }
    return info_attrs, runtime_attrs, auth_attrs
