from typing import Any, Dict, List

from staff.departments.models import Department
from staff.departments.utils import get_department_chain
from staff.person_profile.controllers.blocks.value_stream_block import get_value_stream_data, get_persons_value_streams


def export_person_value_streams_controller(persons: List[str]) -> Dict[str, List[Dict[str, Any]]]:
    persons_value_streams = get_persons_value_streams(persons)
    abc_service_info = get_value_stream_data(Department.valuestreams.active().values_list('url', flat=True))
    chains: Dict[int, List[Dict[str, Any]]] = {}
    result: Dict[str, List[Dict[str, Any]]] = {}

    for login, value_stream in persons_value_streams.items():
        if not value_stream:
            result[login] = []
            continue

        value_stream_id = value_stream['id']

        if value_stream_id not in chains:
            value_stream_chain = get_department_chain(**value_stream)
            chains[value_stream_id] = [_get_value_stream_info(vs, abc_service_info) for vs in value_stream_chain]

        result[login] = chains[value_stream_id]

    return result


def _get_value_stream_info(value_stream: Dict[str, Any], abc_service_info: Dict[str, Any]) -> Dict[str, Any]:
    value_stream_url = value_stream['url']
    abc_info = abc_service_info.get(value_stream_url, {})

    return {
        'url': value_stream_url,
        'name': value_stream['name'],
        'name_en': value_stream['name_en'],
        'abc_service_id': abc_info.get('service_id'),
        'service_tags': [x for x in abc_info.get('service_tags', '').split(',') if x],
    }
