import json
import logging

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

from intranet.femida.src.offers.models import Offer
from intranet.femida.src.staff.bp_registry import (
    BPRegistryAPI,
    BPRegistryError,
    PlacementExistenceRequest,
)
from intranet.femida.src.startrek.operations import (
    IssueCommentOperation,
    IssueUpdateOperation,
)


logger = logging.getLogger(__name__)


def check_placement_existence(offer: Offer, issue):
    if not offer.office or not offer.org:
        return

    issue_fields_for_fail = {settings.STARTREK_JOB_WORKFLOW_INTEGRITY_FIELD: 'placement_err'}

    try:
        placement_exists = BPRegistryAPI.check_placement_exists(PlacementExistenceRequest(
            office_id=offer.office_id,
            organization_id=offer.org_id,
        ))
        if placement_exists:
            operation = IssueUpdateOperation(issue.key)
            issue_fields_for_success = {
                settings.STARTREK_JOB_WORKFLOW_INTEGRITY_FIELD: 'placement_ok'
            }
            operation.delay(**issue_fields_for_success)
            return

    except BPRegistryError:
        logger.exception('Failed to determine placement existence')
        _update_issue_on_fail(
            office_id=str(offer.office_id),
            issue=issue,
            comment_text=loader.render_to_string('startrek/offers/bp-registry-failure.wiki'),
            fields=issue_fields_for_fail,
        )
        raise

    context = {
        'organization': offer.org,
        'office': offer.office,
    }
    # Adding the comment
    _update_issue_on_fail(
        office_id=str(offer.office_id),
        issue=issue,
        comment_text=loader.render_to_string(
            'startrek/offers/placement-doesnt-exist.wiki',
            context,
        ),
        fields=issue_fields_for_fail
    )


def _update_issue_on_fail(office_id, issue, comment_text, fields):
    """
    Creates a comment if there is no placement in an office.

    If an office is included to the OFFICE_HRBP_SUMMON_MAPPING
    additionally summons an HRBP of the office.
    FEMIDA-7194
    """
    operation = IssueUpdateOperation(issue.key)
    # Adding the field
    operation.delay(**fields)

    office_hrbp = json.loads(config.OFFICE_HRBP_SUMMON_MAPPING)

    summonees = office_hrbp[office_id] if (office_id in office_hrbp) else None

    operation = IssueCommentOperation(issue.key)
    # Adding the comment
    operation.delay(
        text=comment_text,
        summonees=summonees,
    )
