import os
from pathlib import Path
from typing import Set, Union, List

from clarabot_nano.common.i18n import LOCALIZATION
from clarabot_nano.resource import get_resource_path


def get_index_supported_languages() -> Set[str]:
    languages = set()
    for item in get_resource_path("template", "solr", "configsets", "nano", "lang").iterdir():
        if not item.name.islower() or not item.name.isalpha() or not item.is_dir():
            continue
        if not (item / "snippet.xml").is_file():
            continue
        languages.add(item.name)
    return languages


def get_effective_languages_by_config(
    supported_languages: Set[str], indexed_languages: Union[List[str], str, None]
) -> List[str]:
    if indexed_languages == "all":
        effective_config_languages = sorted(supported_languages)
    elif isinstance(indexed_languages, list) and indexed_languages:
        # select supported languages from an explicit list
        selected_languages = set(lang.lower() for lang in indexed_languages)
        selected_languages.intersection_update(supported_languages)
        effective_config_languages = sorted(selected_languages)
    else:  # empty list or "false" value
        effective_config_languages = {"en"}
        if LOCALIZATION.DETECTED_SYSTEM_LANGUAGE in supported_languages:
            effective_config_languages.add(LOCALIZATION.DETECTED_SYSTEM_LANGUAGE)
        effective_config_languages = sorted(effective_config_languages)
    return effective_config_languages


def get_compiled_core_config(index_languages: List[str]) -> dict:
    """
    Create the new schema and configuration for the core.
    """
    nano_template_dir = get_resource_path("template", "solr", "configsets", "nano")
    schema = (nano_template_dir / "conf" / "managed-schema").read_text(encoding="utf-8")
    pre_ins_point, tip, post_ins_point = schema.rpartition("<!-- TEMPLATE INSERTION POINT -->")
    if not tip:
        raise Exception("Nano index schema base is missing the insertion point for dynamic languages")
    snippets = []
    for lang in index_languages:
        snippets.append((nano_template_dir / "lang" / lang / "snippet.xml").read_text(encoding="utf-8"))
    schema = "".join([pre_ins_point, tip, *snippets, post_ins_point])
    files = {
        "conf/managed-schema": schema,
        "conf/solrconfig.xml": (nano_template_dir / "conf" / "solrconfig.xml").read_text(encoding="utf-8"),
    }
    for lang in index_languages:
        for parent_path, _, file_names in os.walk(nano_template_dir / "lang" / lang):
            for file_name in file_names:
                if file_name == "snippet.xml":
                    continue
                file_path = Path(parent_path) / file_name
                files[file_path.relative_to(nano_template_dir).as_posix()] = file_path.read_text(encoding="utf-8")
    return files
