import sys
import re
import difflib
from collections import Counter

def read_file(path):
    with open(path, 'r', encoding='utf-8') as f:
        return f.read()

def filter_myanmar_only(text):
    # Lọc chỉ lấy chữ Myanmar
    return ''.join(re.findall(r'[\u1000-\u109F]+', text))

extracted_raw = read_file("./An Duc Tam Bao/tam_bao_061_070.md")
standard_raw = read_file("./An Duc Tam Bao/Tam_Bao_061_070_standard.txt")

ex_myanmar = filter_myanmar_only(extracted_raw)
std_myanmar = filter_myanmar_only(standard_raw)

matcher = difflib.SequenceMatcher(None, std_myanmar, ex_myanmar)
opcodes = matcher.get_opcodes()

missing_blocks = []
replaced_blocks = []
hallucinated_blocks = []

chars_missing = 0
chars_replaced_std = 0
chars_replaced_ex = 0
chars_hallucinated = 0

for tag, i1, i2, j1, j2 in opcodes:
    if tag == 'delete':
        missing_text = std_myanmar[i1:i2]
        missing_blocks.append((missing_text, i1))
        chars_missing += (i2 - i1)
    elif tag == 'replace':
        std_text = std_myanmar[i1:i2]
        ex_text = ex_myanmar[j1:j2]
        replaced_blocks.append((std_text, ex_text))
        chars_replaced_std += (i2 - i1)
        chars_replaced_ex += (j2 - j1)
    elif tag == 'insert':
        extra_text = ex_myanmar[j1:j2]
        hallucinated_blocks.append(extra_text)
        chars_hallucinated += (j2 - j1)

print(f"--- TỔNG QUAN LỖI ---")
print(f"1. Số ký tự bị thiếu (có trong chuẩn, mất ở trích xuất): {chars_missing}")
print(f"2. Số ký tự bị sai/thay thế (từ {chars_replaced_std} ký tự gốc biến thành {chars_replaced_ex} ký tự sai)")
print(f"3. Số ký tự bị dư/tự thêm (không có trong chuẩn nhưng lại xuất hiện): {chars_hallucinated}")

print("\n--- PHÂN TÍCH THIẾU ĐOẠN/CÂU DÀI ---")
# Lọc ra các đoạn bị thiếu dài hơn 30 ký tự (thường là một câu dài hoặc một đoạn)
large_missing = [b for b, idx in missing_blocks if len(b) >= 30]
print(f"Số lượng khối văn bản bị thiếu dài >= 30 ký tự: {len(large_missing)}")
for idx, b in enumerate(large_missing[:5]):
    print(f"  + Đoạn thiếu dài {len(b)} ký tự: {b}")

print("\n--- CÁC LỖI THAY THẾ PHỔ BIẾN NHẤT (Top 10) ---")
# Phân tích các cặp thay thế phổ biến
replace_counter = Counter()
for s_txt, e_txt in replaced_blocks:
    if len(s_txt) < 10 and len(e_txt) < 10: # Tập trung vào các cụm từ/ký tự nhỏ
        replace_counter[(s_txt, e_txt)] += 1

for (s, e), count in replace_counter.most_common(10):
    print(f"  + Lỗi: '{s}' -> '{e}' (xuất hiện {count} lần)")
