import os
import re

languages = ['ar_eg', 'ar_jo', 'ar_sy', 'en', 'de', 'el', 'es', 'fa', 'fr', 'hi', 'it', 'ru', 'tr', 'ur', 'zh']
local_dir = "siro_driver/lib/controller/local"

def parse_dart_map(filepath):
    translations = {}
    if not os.path.exists(filepath):
        print(f"Error: file {filepath} does not exist!")
        return None
    with open(filepath, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Matches: "key": "value"
    pattern = re.compile(r'^\s*([\'"])(.*?)\1\s*:\s*([\'"])(.*?)\3\s*,?\s*$', re.MULTILINE)
    matches = pattern.findall(content)
    for match in matches:
        key = match[1]
        val = match[3]
        # Store raw keys and values to check escaping
        translations[key] = val
    return translations

parsed_data = {}
all_valid = True

for lang in languages:
    filepath = os.path.join(local_dir, f"{lang}.dart")
    trans = parse_dart_map(filepath)
    if trans is None:
        all_valid = False
        continue
    parsed_data[lang] = trans
    print(f"Verified {lang}.dart: parsed {len(trans)} entries.")
    if len(trans) != 2660:
        print(f"  ERROR: Expected 2660 entries, got {len(trans)}")
        all_valid = False

if not all_valid:
    print("Verification FAILED on basic counts.")
    exit(1)

# Check that key sets are identical
ref_lang = languages[0]
ref_keys = set(parsed_data[ref_lang].keys())

for lang in languages[1:]:
    keys = set(parsed_data[lang].keys())
    if keys != ref_keys:
        print(f"ERROR: Key sets differ between {ref_lang} and {lang}!")
        print(f"  Keys in {ref_lang} not in {lang}: {len(ref_keys - keys)}")
        print(f"  Keys in {lang} not in {ref_lang}: {len(keys - ref_keys)}")
        all_valid = False

# Check for escaping errors (e.g. unescaped dollar signs in double-quoted strings in the Dart source code)
# In the raw file content, any dollar sign must be preceded by a backslash unless it is already escaped.
# Let's inspect the files directly for raw '$' characters that are not preceded by '\'
dollar_pattern = re.compile(r'(?<!\\)\$')

for lang in languages:
    filepath = os.path.join(local_dir, f"{lang}.dart")
    with open(filepath, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    for idx, line in enumerate(lines):
        # We search inside map entries
        if ":" in line:
            # check for unescaped dollar signs
            # A dollar sign not preceded by a backslash is a compilation error in Dart double-quoted strings
            # unless it's single quotes or some specific construct, but we used double quotes for all lines.
            unescaped_dollars = dollar_pattern.findall(line)
            if unescaped_dollars:
                print(f"ERROR: Unescaped dollar sign in {filepath} line {idx+1}:")
                print(f"  {line.strip()}")
                all_valid = False

if all_valid:
    print("\nSUCCESS: All files verified! They have identical keys (2660 keys) and correct escaping.")
else:
    print("\nVerification FAILED.")
    exit(1)
