import difflib
from collections import Counter

def extract_myanmar(text):
    return ''.join(c for c in text if '\u1000' <= c <= '\u109f')

with open('./An Duc Tam Bao/Tam_Bao_051_060_standard.txt', 'r', encoding='utf-8') as f:
    standard = extract_myanmar(f.read())

with open('./An Duc Tam Bao/tam_bao_051_060.md', 'r', encoding='utf-8') as f:
    extracted = extract_myanmar(f.read())

matcher = difflib.SequenceMatcher(None, standard, extracted)
replacements = Counter()
deletions = Counter()
insertions = Counter()

for tag, i1, i2, j1, j2 in matcher.get_opcodes():
    if tag == 'replace':
        # Để tránh các block quá dài, chỉ lấy các lỗi nhỏ (độ dài <= 5)
        s, e = standard[i1:i2], extracted[j1:j2]
        if len(s) <= 5 and len(e) <= 5:
            replacements[(s, e)] += 1
    elif tag == 'delete':
        s = standard[i1:i2]
        if len(s) <= 5:
            deletions[s] += 1
    elif tag == 'insert':
        e = extracted[j1:j2]
        if len(e) <= 5:
            insertions[e] += 1

print("--- Các lỗi thay thế phổ biến (Bản Chuẩn -> Bản Trích Xuất) ---")
for (s, e), count in replacements.most_common(15):
    print(f"'{s}' bị đổi thành '{e}' : {count} lần")

print("\n--- Các lỗi mất chữ phổ biến (Có trong Bản Chuẩn, bị mất khi trích xuất) ---")
for s, count in deletions.most_common(10):
    print(f"Bị mất '{s}' : {count} lần")

print("\n--- Các lỗi thêm chữ phổ biến (Không có trong Bản Chuẩn, AI tự thêm) ---")
for e, count in insertions.most_common(10):
    print(f"Tự thêm '{e}' : {count} lần")
