import logging

from django.conf import settings
from django.template import loader

from intranet.femida.src.notifications.utils import get_base_context
from intranet.femida.src.notifications.vacancies import VacancyCreatedNotification
from intranet.femida.src.staff.helpers import get_hr_analyst_groups
from intranet.femida.src.startrek.utils import add_comment, create_issue, IssueTypeEnum
from intranet.femida.src.utils.ok import create_tracker_approvement_comment
from intranet.femida.src.vacancies.choices import VACANCY_TYPES
from intranet.femida.src.vacancies.startrek.memberships import IssueMembership
from intranet.femida.src.vacancies.startrek.serializers import PRO_LEVELS_MAP, PRO_LEVELS_MAP_EN

logger = logging.getLogger(__name__)


def _get_pro_level(vacancy):
    is_pro_level_single = (
        not vacancy.pro_level_min
        or vacancy.pro_level_min == vacancy.pro_level_max
    )

    if is_pro_level_single:
        return {
            'EN': PRO_LEVELS_MAP_EN[vacancy.pro_level_max],
            'RU': PRO_LEVELS_MAP[vacancy.pro_level_max],
        }
    else:
        return {
            'EN': f'{PRO_LEVELS_MAP_EN[vacancy.pro_level_min]} — {PRO_LEVELS_MAP_EN[vacancy.pro_level_max]}',
            'RU': f'{PRO_LEVELS_MAP[vacancy.pro_level_min]} — {PRO_LEVELS_MAP[vacancy.pro_level_max]}',
        }


def get_job_issue_summary(vacancy):
    prefixes_map = {
        'RU': {
            VACANCY_TYPES.new: 'Новая',
            VACANCY_TYPES.replacement: 'Замена',
            VACANCY_TYPES.internship: 'Стажировка',
        },
        'EN': {
            VACANCY_TYPES.new: 'New',
            VACANCY_TYPES.replacement: 'Replacement',
            VACANCY_TYPES.internship: 'Internship',
        }
    }
    pro_level = _get_pro_level(vacancy)
    return (
        f'{prefixes_map["RU"].get(vacancy.type, prefixes_map["RU"][VACANCY_TYPES.new])} '
        f'({vacancy.profession.name_ru}: {pro_level["RU"]}) '
        f'/ {prefixes_map["EN"].get(vacancy.type, prefixes_map["EN"][VACANCY_TYPES.new])} '
        f'({vacancy.profession.name_en}: {pro_level["EN"]})'
    )


def create_job_issue(vacancy):
    from intranet.femida.src.vacancies.tasks import start_vacancy_approvement_task

    template_name = 'startrek/vacancies/create-job-issue.wiki'
    fields = vacancy.issue_data.get('fields', {})

    issue_membership = IssueMembership.from_vacancy(vacancy)
    access = [u.username for u in issue_membership.access]

    # Note: наблюдатели (followers) трансформировались в доступы (access),
    # но я бы не спешил с переименованием.
    # Как-то не похоже, что тут всё решилось окончательно.
    access.extend(fields.pop('followers', []))

    issue = create_issue(
        queue=settings.STARTREK_JOB_QUEUE,
        summary=get_job_issue_summary(vacancy),
        description=loader.render_to_string(template_name, vacancy.issue_data.get('context', {})),
        author=vacancy.created_by.username,
        access=access,
        **fields
    )
    vacancy.startrek_key = issue.key
    vacancy.save()

    if vacancy.type != VACANCY_TYPES.autohire:
        start_vacancy_approvement_task.delay(
            vacancy_id=vacancy.id,
            author=fields.get('analyst'),
            approvers=[u.username for u in issue_membership.chiefs],
        )

    notification = VacancyCreatedNotification(vacancy, vacancy.created_by)
    notification.send()

    return issue


def start_vacancy_approvement(vacancy, author, approvers, uid):
    """
    Инициирует согласование вакансии в JOB-тикете через OK
    """
    comment = create_tracker_approvement_comment(
        issue_key=vacancy.startrek_key,
        author=author,
        approvers=approvers,
        text='Привет!\nПодтверждаешь открытие вакансии?\nСпасибо!',
        uid=uid,
        groups=get_hr_analyst_groups(vacancy.department),
    )
    add_comment(vacancy.startrek_key, comment)


def create_vacancy_edit_issue(vacancy, submission_form, uid):
    template_name = 'startrek/vacancies/submission-form-unused.wiki'
    context = get_base_context()
    context['vacancy'] = vacancy
    context['submission_form'] = submission_form

    create_issue(
        queue=settings.STARTREK_VACEDIT_QUEUE,
        # используется для ретраев, но позволяет создать тикет повторно для одной submission_form
        unique=uid,
        summary=f'[Снять вакансию с публикации] - {submission_form.url}',
        description=loader.render_to_string(template_name, context),
        type=IssueTypeEnum.remove_process,
        rekrutery=[r.username for r in vacancy.recruiters],
        tags=['авто_снятие'],
    )
