
import re
from datetime import datetime
from sdsvkie.utils import Word_group


YEAR_START = 2000
def construct_word_groups_to_kie_label(list_word_groups: list):
    kie_dict = dict()

    for wg in list_word_groups:
        if wg.kie_label.lower() in ['other', 'others']:
            continue
        if wg.kie_label not in kie_dict:
            kie_dict[wg.kie_label] = [wg]
        else:
            kie_dict[wg.kie_label].append(wg)

    return kie_dict


def near(word_group1: Word_group, word_group2: Word_group):
    min_height = min(
        word_group1.boundingbox[3] - word_group1.boundingbox[1],
        word_group2.boundingbox[3] - word_group2.boundingbox[1],
    )
    overlap = min(word_group1.boundingbox[3], word_group2.boundingbox[3]) - max(
        word_group1.boundingbox[1], word_group2.boundingbox[1]
    )

    if overlap > 0:
        return True
    if abs(overlap / min_height) < 1.5:
        print("near enough", abs(overlap / min_height), overlap, min_height)
        return True
    return False


def normalize_number(text_str: str,  reserve_dot=False, reserve_plus=False, reserve_minus=False):
    """
    Normalize a string of numbers by removing non-numeric characters

    """
    assert isinstance(text_str, str), "input must be str"
    reserver_chars = ""
    if reserve_dot:
        reserver_chars += ".,"
    if reserve_plus:
        reserver_chars += "+"
    if reserve_minus:
        reserver_chars += "-"
    regex_fomula = "[^0-9{}]".format(reserver_chars)
    normalized_text_str = re.sub(r"{}".format(regex_fomula), "", text_str)
    return normalized_text_str


def normalize_number_wordgroup(word_group, reserve_dot=False, reserve_plus=False, reserve_minus=False):
    word_group.text = normalize_number(word_group.text,  reserve_dot=reserve_dot, reserve_plus=reserve_plus, reserve_minus=reserve_minus)
    return word_group

def tax_code_processing(tax_code_raw: str):    
    """
    
    """
    if len(tax_code_raw.replace(' ', '')) != 13 or (len(tax_code_raw.replace(' ', '')) != 14 and "-" not in tax_code_raw): # to remove the first/last number dupicated
        tax_code_raw = tax_code_raw.split(' ')        
        tax_code_raw = sorted(tax_code_raw, key=lambda x: len(x), reverse=True)[0]
    return tax_code_raw.replace(' ', '')

def normalize_tax_wordgroup(word_group, reserve_dot=False, reserve_plus=False, reserve_minus=False):
    print("before: ", word_group.text)
    word_group.text = tax_code_processing(word_group.text)
    print("after: ", word_group.text)
    word_group.text = normalize_number(word_group.text,  reserve_dot=reserve_dot, reserve_plus=reserve_plus, reserve_minus=reserve_minus)
    return word_group


def _date_format(date_string):
    """Format date string according format dd/MM/yyyy"""
    date_string = (
        date_string.replace("ngay ", "")
        .replace(" thang ", "/")
        .replace(" nam ", "/")
    )
    day, month, year = date_string.split("/")
    day = day.rjust(2, "0")
    month = month.rjust(2, "0")
    year = f"20{year}" if len(year) == 2 else year

    # Check valid year
    try:
        _ = datetime(year=int(year), month=int(month), day=int(day))
        if int(year) > YEAR_START:
            return "/".join([day, month, year])
    except:
        print("Date is invalid", date_string)

    return None

def get_date(list_date):
    """Regex get date"""

    list_date = [
        _date_format(date.group(0))
        for date in list_date
        # if _date_format(date.group(0)) is not None
    ]
    list_date = [
        date for date in list_date if date is not None
    ]
    return list_date


def merge_multi_page_results(result_pages):
    """Merge the result of the multiple pages

    Args:
        results (list[dict]): list of result dict of each page 
    """
    if len(result_pages) == 0:
        return {}

    result = result_pages[0]
    for result_page in result_pages[1:]:
        for field_name, field_value in result_page.items():
            if field_name not in result:
                result[field_name] = field_value

    return result
