import logging
from typing import Any

from fastapi import APIRouter, Request, Depends

from intranet.trip.src.api.auth import get_tvm_service_ticket
from intranet.trip.src.api.auth.permissions import is_yandex_coordinator
from intranet.trip.src.api.depends import get_unit_of_work
from intranet.trip.src.config import settings
from intranet.trip.src.lib.isearch.api import IntrasearchClient
from intranet.trip.src.models.person import Person, User
from intranet.trip.src.unit_of_work import UnitOfWork


logger = logging.getLogger(__name__)
router = APIRouter()


def get_isearch_style_response(
        user: User,
        persons: list[Person],
        limit: int,
) -> dict:
    result = []
    for person in persons:
        if user.language == 'en':
            first_name = person.first_name_en
            last_name = person.last_name_en
            middle_name = person.middle_name_en
            position = 'Employee'
        else:
            first_name = person.first_name
            last_name = person.last_name
            middle_name = person.middle_name
            position = 'Сотрудник'
        result.append({
            'name': {
                'first': first_name,
                'last': last_name,
                'middle': middle_name,
            },
            'login': person.login,
            'position': position,
            'staff_id': person.person_id,
            'person_id': person.person_id,
            'uid': str(person.person_id),
            'is_dismissed': person.is_dismissed,
        })
    return {
        'people': {
            'result': result,
            'pagination': {
                'page': 0,
                'per_page': limit,
                'pages': 1,
                'count': len(persons),
            },
        }
    }


@router.get('/persons', response_model=dict[str, Any])
async def persons_suggest(
    request: Request,
    text: str = '',
    uow: UnitOfWork = Depends(get_unit_of_work(read_only=True)),
):
    limit = 8
    if settings.IS_YA_TEAM:
        isearch = IntrasearchClient(
            host=settings.search_url,
            timeout=2,
            service_ticket=await get_tvm_service_ticket('intrasearch'),
            user_ticket=request.state.user.user_ticket,
        )
        data = await isearch.suggest(text, limit=limit)
        for item in data['people']['result']:
            item['person_id'] = item['staff_id']
            item['uid'] = str(item['staff_id'])
        return data
    else:
        user = request.state.user
        person = await uow.persons.get_person(user.person_id)
        holding_id = None if is_yandex_coordinator(user) else person.company.holding_id
        persons = await uow.persons.search_persons(
            text=text,
            limit=limit,
            holding_id=holding_id,
            person_id=user.person_id,  # FIXME: remove this in B2B release
        )
        return get_isearch_style_response(
            user=user,
            persons=persons,
            limit=limit,
        )
