import re
try:
    from .config import Config as cfg
except ImportError:
    from config import Config as cfg


special_symbol_map = {
    "*": "স্টার",
    "#": "হ্যাশ",
    ",": "কমা",
    "-": "ড্যাশ",
    ".": "ডট",
    "!": "এক্সক্লামেশন",
    "?": "কোশ্চেন",
    ":": "কোলন"
}
class number_dialer_normalizer:
    def __init__(self):
        self.pattern = r'\*[\s*]*[\d০-৯]+(?:[\s*]*\*[\s*]*[\d০-৯]+)*[\s*]*#'
        self.split_pattern = r'[\*#]|[\d০-৯]+'
        self.pattern = r'\*\d+(?:\*\d+)*#'
    def contains_only_english(self, input_string):
        # Check if all characters in the string are English (ASCII) characters
        return all(ord(char) < 128 for char in input_string)
    def label_repeats(self, number, lang="en", helpine=False):
        is_english_digit_string = self.contains_only_english(number)
        # print("is_english_digit_string : ", is_english_digit_string, number)
        result = []
        digit_map = cfg.data["en"]["number_mapping"]
        if is_english_digit_string == False and helpine == True:
            for n in number:
                if n in digit_map:
                    result.append(digit_map[n])
                elif n == "-":
                    result.append(", ")
                elif n in special_symbol_map:
                    result.append(special_symbol_map[n])
            return " ".join(result)

        c_number = []
        for i in number:
            status = self.contains_only_english(i)
            if status == False:
                if i in cfg._bangla2english_digits_mapping:
                    c_n = cfg._bangla2english_digits_mapping[i]
                    c_number.append(c_n)
                else:
                    c_number.append(i)
            else:
                c_number.append(i)
        number = c_number
        i = 0
        n = len(number)
        while i < n:
            if i + 2 < n and number[i] == number[i + 1] == number[i + 2]:
                result.append(cfg.special_map[number[i] * 3])
                i += 3
            elif i + 1 < n and number[i] == number[i + 1]:
                result.append(cfg.special_map[number[i] * 2])
                i += 2
            else:
                if number[i] in digit_map:
                    # print("number[i] : ", number[i], type(number[i]))
                    result.append(digit_map[number[i]])
                elif number[i] == "-":
                    result.append(" ")
                elif number[i] in special_symbol_map:
                    result.append(special_symbol_map[number[i]])
                i += 1

        return " ".join(result)

    def number_dial(self, text):
        matches = re.findall(self.pattern, text)
        for match in matches:
            # Remove spaces from matched code before processing
            clean_match = match.replace(" ", "")
            result = self.label_repeats(clean_match)
            text = text.replace(match, result)
        return text




if __name__ == "__main__":

    test_cases = [
        # (input_text, expected_matches, description)
        # --- Basic patterns ---
        ("*123#", ["*123#"], "Single segment"),
        ("*222*666#", ["*222*666#"], "Two segments"),
        ("*123*456*789#", ["*123*456*789#"], "Three segments"),
        ("*1*2#", ["*1*2#"], "Single digit segments"),
        ("*123456*789012#", ["*123456*789012#"], "Long digit segments"),
        ("*8999*20#", ["*8999*20#"], "Migration code"),
        # --- Bangla digits ---
        ("*১২৩#", ["*১২৩#"], "Bangla single segment"),
        ("*১২৩*৪৫৬#", ["*১২৩*৪৫৬#"], "Bangla two segments"),
        ("*১২৩*456#", ["*১২৩*456#"], "Mixed Bangla and English digits"),
        # --- Double star ---
        ("**123#", ["**123#"], "Double star prefix"),
        ("**123*456#", ["**123*456#"], "Double star with two segments"),
        # --- Spaces inside ---
        ("* 123 #", ["* 123 #"], "Spaces around digits"),
        ("* 123 * 456 #", ["* 123 * 456 #"], "Spaces everywhere"),
        ("*123 *456#", ["*123 *456#"], "Space before second *"),
        # --- Surrounded by text ---
        ("Dial *123# for info.", ["*123#"], "Code mid-sentence English"),
        ("*8999*90# ডায়াল করুন", ["*8999*90#"], "Code at start Bengali"),
        ("ডায়াল করুন *8999*90#", ["*8999*90#"], "Code at end Bengali"),
        ("কোড: *8999*20#।", ["*8999*20#"], "Followed by Bengali punctuation ।"),
        ("*8999*39# (ফ্রি)।", ["*8999*39#"], "Followed by parenthesis"),
        # --- Multiple codes ---
        ("Dial *222*666# and *123#", ["*222*666#", "*123#"], "Two codes in one text"),
        ("*123# and *123#", ["*123#", "*123#"], "Duplicate codes"),
        (
        "*8999*20#। *8999*21#। *8999*37#। *8999*32#।",
        ["*8999*20#", "*8999*21#", "*8999*37#", "*8999*32#"],
        "Four migration codes"
        ),
        # --- Negative cases (should NOT match) ---
        ("123*456#", ["123*456#"], "No leading *"),
        ("*123*456", ["*123*456"], "No trailing #"),
        ("#123#", [], "Starts with #"),
        ("01712345678", [], "Plain phone number"),
        ("Hello world", [], "No code at all"),
        ("*abc*123#", [], "Letters mixed in"),
        # --- Edge cases ---
        ("*0#", ["*0#"], "Single zero"),
        ("*000*000#", ["*000*000#"], "All zeros"),
        ("*9999999#", ["*9999999#"], "Many same digits"),
        ("text *123# middle *456*789# end", ["*123#", "*456*789#"], "Codes scattered in text"),
    ]

    # --- Run tests ---
    di = number_dialer_normalizer()
    passed = 0
    failed = 0

    for text, expected, desc in test_cases:

        result = di.number_dial(text[0])
        print(f"Input: '{text}' | Output: '{result}' | Expected: '{expected}'")
        # matches = re.findall(di.pattern, text)
        # status = "✅" if matches == expected else "❌"
        # if matches == expected:
        #     passed += 1
        # else:
        #     failed += 1
        #     print(f"{status} {desc}: input='{text}' expected={expected} got={matches}")
        #     continue
        # print(f"{status} {desc}")

    print(f"\n{'=' * 40}")
    print(f"Results: {passed} passed, {failed} failed out of {len(test_cases)}")