from typing import Dict
from typing import List
from typing import Tuple
from bs4 import BeautifulSoup
from typing import OrderedDict


def load_docs_from_sgml(
    file_path: str, encoding='utf-8'
) -> Dict[str, List[Tuple[str, str]]]:
    """
    Loads documents from given SGML file.

    Returns dict mapping document ids to list of segments [segments].
    Each segment is a tuple (segment id, segment text).
    """
    soup = None

    with open(file_path, encoding=encoding) as _file:
        soup = BeautifulSoup(_file, features='lxml')

    all_docs: Dict[str, List[Tuple[str, str]]] = OrderedDict()
    for curr_doc in soup.find_all('doc'):
        curr_doc_id = curr_doc.attrs['docid']
        if not curr_doc_id in all_docs:
            all_docs[curr_doc_id] = []

        for curr_seg in curr_doc.find_all('seg'):
            curr_seg_id = curr_seg.attrs['id']
            curr_seg_text = curr_seg.get_text()
            all_docs[curr_doc_id].append((curr_seg_id, curr_seg_text))

    return all_docs