# Path: dhis2_core/src/dhis2/code_list/models/svcm.py
# class CodeList(BaseEntity):
#     type: Literal["optionSets", "categories"] = "optionSets"
#     version: Union[str, int] = "1"
#     codes: List[Code] = []
# 
# class SVCMConfig(BaseModel):
#     id: str = Field(default_factory=lambda: str(uuid4()))
#     source: SVCMSource
#     target: SVCMTarget
# 
# Path: dhis2_core/src/dhis2/code_list/svcm_resources.py
# def build_bundle(code_lists: List[CodeList], base_url: str) -> Bundle:
#     bundle = Bundle()
#     bundle.type = "transaction"
#     bundle.entry = []
# 
#     log.info(f"Building FHIR bundle from '{len(code_lists)}' DHIS2 code lists")
# 
#     for code_list in code_lists:
#         bundle.entry.append(build_value_set_bundle_entry(code_list, base_url))
#         bundle.entry.append(build_code_system_bundle_entry(code_list, base_url))
# 
#     return bundle


import json
import logging
import sys
from typing import Any, Callable, Dict, List
from dhis2.core.http import BaseHttpRequest
from dhis2.core.inventory import HostResolved, Inventory, resolve_one
from fhir.resources.bundle import Bundle
from .models.svcm import CodeList, SVCMConfig
from .svcm_resources import build_bundle



log = logging.getLogger(__name__)


def get_source(config: SVCMConfig, inventory: Inventory) -> Callable[[Any], Any]:
    host = resolve_one(config.source.id, inventory)

    if "dhis2" not in host.type:
        log.error("Only 'dhis2' source type is currently supported")
        sys.exit(-1)

    log.info(f"Creating source from '{host.key}' with base url '{host.baseUrl}'")

    def fn():
        filters = []

        # https://docs.dhis2.org/2.35/en/developer/html/webapi_metadata_object_filter.html
        if config.source.lastUpdated:
            filters.append(f"lastUpdated:ge:{config.source.lastUpdated}")

        option_sets_filter = list(map(lambda x: f"id:eq:{x}", config.source.filters.optionSets))
        option_sets_filter.extend(filters)

        option_sets = BaseHttpRequest(host).get(
            "api/optionSets",
            params={

# Path: dhis2_core/src/dhis2/code_list/models/svcm.py
# class CodeList(BaseEntity):
#     type: Literal["optionSets", "categories"] = "optionSets"
#     version: Union[str, int] = "1"
#     codes: List[Code] = []
# 
# class SVCMConfig(BaseModel):
#     id: str = Field(default_factory=lambda: str(uuid4()))
#     source: SVCMSource
#     target: SVCMTarget
# 
# Path: dhis2_core/src/dhis2/code_list/svcm_resources.py
# def build_bundle(code_lists: List[CodeList], base_url: str) -> Bundle:
#     bundle = Bundle()
#     bundle.type = "transaction"
#     bundle.entry = []
# 
#     log.info(f"Building FHIR bundle from '{len(code_lists)}' DHIS2 code lists")
# 
#     for code_list in code_lists:
#         bundle.entry.append(build_value_set_bundle_entry(code_list, base_url))
#         bundle.entry.append(build_code_system_bundle_entry(code_list, base_url))
# 
#     return bundle


# Path: dhis2_core/src/dhis2/code_list/svcm.py
import json
import logging
import sys
from typing import Any, Callable, Dict, List
from dhis2.core.http import BaseHttpRequest
from dhis2.core.inventory import HostResolved, Inventory, resolve_one
from fhir.resources.bundle import Bundle
from .models.svcm import CodeList, SVCMConfig
from .svcm_resources import build_bundle




log = logging.getLogger(__name__)


def get_source(config: SVCMConfig, inventory: Inventory) -> Callable[[Any], Any]:
    host = resolve_one(config.source.id, inventory)

    if "dhis2" not in host.type:
        log.error("Only 'dhis2' source type is currently supported")
        sys.exit(-1)

    log.info(f"Creating source from '{host.key}' with base url '{host.baseUrl}'")

    def fn():
        filters = []

        # https://docs.dhis2.org/2.35/en/developer/html/webapi_metadata_object_filter.html
        if config.source.lastUpdated:
            filters.append(f"lastUpdated:ge:{config.source.lastUpdated}")

        option_sets_filter = list(map(lambda x: f"id:eq:{x}", config.source.filters.optionSets))
        option_sets_filter.extend(filters)

        option_sets = BaseHttpRequest(host).get(
            "api/optionSets",
            params={

                "fields": "id,code,name,version,translations,options[id,code,name,translations]",