#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script so sánh độ chính xác - Loại bỏ header/footer/số trang trước khi so sánh
"""

import re
from difflib import SequenceMatcher

def extract_myanmar_text(text):
    """Trích xuất chỉ văn bản tiếng Myanmar"""
    myanmar_pattern = re.compile(r'[\u1000-\u109F၊။\s]+')
    matches = myanmar_pattern.findall(text)
    result = ''.join(matches)
    result = re.sub(r'\s+', ' ', result).strip()
    return result

def clean_headers_footers(text):
    """
    Loại bỏ header, footer, số trang, và các marker không phải nội dung chính
    """
    # Loại bỏ header kiểu "ရတနာ့ဂုဏ်ရည်"
    text = re.sub(r'ရတနာ့ဂုဏ်ရည်', '', text)
    
    # Loại bỏ header kiểu "သံဃာ့ဂုဏ်တော်ဖွင့်"
    text = re.sub(r'သံဃာ့ဂုဏ်တော်ဖွင့်', '', text)
    
    # Loại bỏ header kiểu "ဩကာသ အဖွင့်"
    text = re.sub(r'ဩကာသ အဖွင့်', '', text)
    
    # Loại bỏ số trang Myanmar (၁၆၂, ၁၆၃, etc.) - thường đứng riêng
    text = re.sub(r'\b[၀-၉]{၃}\b', '', text)
    
    # Loại bỏ marker "(အဋ္ဌမအကြိမ်)"
    text = re.sub(r'\(အဋ္ဌမအကြိမ်\)', '', text)
    
    # Loại bỏ "Trang171", "Trang172" (nếu có)
    text = re.sub(r'Trang\d+', '', text)
    
    # Loại bỏ các dòng chỉ có số trang hoặc header ngắn
    lines = text.split('\n')
    filtered_lines = []
    for line in lines:
        line_stripped = line.strip()
        # Bỏ dòng chỉ có số (1-3 chữ số)
        if re.match(r'^[၀-၉]{1,3}$', line_stripped):
            continue
        # Bỏ dòng chỉ có header ngắn (< 10 ký tự)
        if len(line_stripped) < 10 and re.match(r'^[က-ဪ]+$', line_stripped):
            continue
        filtered_lines.append(line)
    
    return '\n'.join(filtered_lines)

def normalize_for_comparison(text):
    """Chuẩn hóa: bỏ khoảng trắng"""
    return text.replace(' ', '')

def find_differences(standard, extracted):
    """Tìm sự khác biệt sử dụng SequenceMatcher"""
    matcher = SequenceMatcher(None, standard, extracted)
    
    differences = []
    for tag, i1, i2, j1, j2 in matcher.get_opcodes():
        if tag == 'replace':
            differences.append({
                'type': 'replace',
                'std_text': standard[i1:i2],
                'ext_text': extracted[j1:j2]
            })
        elif tag == 'delete':
            differences.append({
                'type': 'delete',
                'std_text': standard[i1:i2]
            })
        elif tag == 'insert':
            differences.append({
                'type': 'insert',
                'ext_text': extracted[j1:j2]
            })
    
    return differences

def calculate_accuracy(standard, extracted):
    """Tính độ chính xác"""
    matcher = SequenceMatcher(None, standard, extracted)
    return matcher.ratio() * 100

def categorize_errors(differences):
    """Phân loại lỗi"""
    categories = {
        'confusable_chars': [],
        'missing_its': [],     # Mất ့်
        'vowel_errors': [],
        'tone_errors': [],
        'word_errors': [],
        'punctuation': [],
        'baw_bawt': [],        # Nhầm ဖ/ဘ
        'pa_na': [],           # Nhầm ပ/န
        'ya_ya': [],           # Nhầm ျ/ြ
    }
    
    confusable_pairs = {
        ('ဖ', 'ဘ'): 'baw_bawt',
        ('ဘ', 'ဖ'): 'baw_bawt',
        ('ပ', 'န'): 'pa_na',
        ('န', 'ပ'): 'pa_na',
        ('ျ', 'ြ'): 'ya_ya',
        ('ြ', 'ျ'): 'ya_ya',
        ('ာ', 'ေ'): 'vowel_errors',
        ('ေ', 'ာ'): 'vowel_errors',
        ('ဝ', '၀'): 'word_errors',
        ('၀', 'ဝ'): 'word_errors',
    }
    
    for diff in differences:
        if diff['type'] == 'replace':
            std = diff['std_text']
            ext = diff['ext_text']
            
            # Dấu câu
            if '၊' in std or '။' in std or '၊' in ext or '။' in ext:
                categories['punctuation'].append(diff)
            # Ký tự đơn
            elif len(std) == 1 and len(ext) == 1:
                pair = (std, ext)
                if pair in confusable_pairs:
                    categories[confusable_pairs[pair]].append(diff)
                elif std in '့်' or ext in '့်':
                    if 'စ်' in std or 'စ်' in ext:
                        categories['missing_its'].append(diff)
                    else:
                        categories['tone_errors'].append(diff)
                elif std in '့း်ံ' or ext in '့း်ံ':
                    categories['tone_errors'].append(diff)
                elif std in 'ာေိီုူဲှ' or ext in 'ာေိီုူဲှ':
                    categories['vowel_errors'].append(diff)
                else:
                    categories['word_errors'].append(diff)
            else:
                # Từ/cụm từ
                if 'စ်' in std and 'စ်' not in ext:
                    categories['missing_its'].append(diff)
                elif len(std) > len(ext) * 1.5:  # Mất nhiều ký tự
                    categories['word_errors'].append(diff)
                else:
                    categories['word_errors'].append(diff)
        elif diff['type'] == 'delete':
            if 'စ်' in diff['std_text']:
                categories['missing_its'].append(diff)
            else:
                categories['word_errors'].append(diff)
        elif diff['type'] == 'insert':
            categories['word_errors'].append(diff)
    
    return categories

def main():
    # Đọc file
    with open('/opt/openclaw/.openclaw/workspace/An Duc Tam Bao/tam_bao_91_95_chuan_muc_standard.txt', 'r', encoding='utf-8') as f:
        standard_text = f.read()
    
    with open('/opt/openclaw/.openclaw/workspace/An Duc Tam Bao/tam_bao_91_95_chuan_muc.md', 'r', encoding='utf-8') as f:
        extracted_text = f.read()
    
    # Trích xuất văn bản Myanmar
    standard_myanmar = extract_myanmar_text(standard_text)
    extracted_myanmar = extract_myanmar_text(extracted_text)
    
    # Làm sạch header/footer
    standard_clean = clean_headers_footers(standard_myanmar)
    extracted_clean = clean_headers_footers(extracted_myanmar)
    
    # Chuẩn hóa
    std_normalized = normalize_for_comparison(standard_clean)
    ext_normalized = normalize_for_comparison(extracted_clean)
    
    print("=" * 80)
    print("PHÂN TÍCH ĐỘ CHÍNH XÁC VĂN BẢN MYANMAR")
    print("(Đã loại bỏ header, footer, số trang)")
    print("=" * 80)
    
    print(f"\n📊 Thống kê tổng quát:")
    print(f"   - Bản chuẩn: {len(std_normalized)} ký tự")
    print(f"   - Bản trích xuất: {len(ext_normalized)} ký tự")
    print(f"   - Chênh lệch: {abs(len(std_normalized) - len(ext_normalized))} ký tự")
    
    # Tính độ chính xác
    accuracy = calculate_accuracy(std_normalized, ext_normalized)
    
    print(f"\n✅ ĐỘ CHÍNH XÁC TỔNG THỂ: {accuracy:.2f}%")
    
    # Tìm sự khác biệt
    differences = find_differences(std_normalized, ext_normalized)
    print(f"   - Tổng số điểm khác biệt: {len(differences)}")
    
    # Phân loại lỗi
    categories = categorize_errors(differences)
    
    print(f"\n📋 PHÂN LOẠI LỖI CHI TIẾT:")
    print(f"   - Nhမ်မ ဖ/ဘ (Bha/Pha): {len(categories['baw_bawt'])} lỗi")
    print(f"   - Nhမ်မ ပ/န (Pa/Na): {len(categories['pa_na'])} lỗi")
    print(f"   - Nhမ်မ ျ/ြ (Ya/Ya): {len(categories['ya_ya'])} lỗi")
    print(f"   - Mất phụ âm ့် (its): {len(categories['missing_its'])} lỗi")
    print(f"   - Sai nguyên âm (ာ/ေ...): {len(categories['vowel_errors'])} lỗi")
    print(f"   - Sai dấu thanh (့/း/်): {len(categories['tone_errors'])} lỗi")
    print(f"   - Sai từ/cụm từ khác: {len(categories['word_errors'])} lỗi")
    print(f"   - Sai dấu câu (၊/။): {len(categories['punctuation'])} lỗi")
    
    total_errors = sum(len(cat) for cat in categories.values())
    
    # Hiển thị lỗi tiêu biểu
    print(f"\n🔍 LỖI TIÊU BIỂU:")
    
    if categories['baw_bawt']:
        print("\n   ❌ NHẦM ဖ/ဘ:")
        shown = set()
        for err in categories['baw_bawt'][:5]:
            key = f"{err['std_text']}→{err['ext_text']}"
            if key not in shown:
                shown.add(key)
                print(f"      '{err['std_text']}' → '{err['ext_text']}'")
    
    if categories['pa_na']:
        print("\n   ❌ NHẦM ပ/န:")
        shown = set()
        for err in categories['pa_na'][:5]:
            key = f"{err['std_text']}→{err['ext_text']}"
            if key not in shown:
                shown.add(key)
                print(f"      '{err['std_text']}' → '{err['ext_text']}'")
    
    if categories['ya_ya']:
        print("\n   ❌ NHẦM ျ/ြ:")
        shown = set()
        for err in categories['ya_ya'][:5]:
            key = f"{err['std_text']}→{err['ext_text']}"
            if key not in shown:
                shown.add(key)
                print(f"      '{err['std_text']}' → '{err['ext_text']}'")
    
    if categories['missing_its']:
        print("\n   ⚠️ MẤT PHỤ ÂM ့်:")
        for err in categories['missing_its'][:5]:
            if err['type'] == 'delete':
                print(f"      Thiếu: '{err['std_text']}'")
            elif err['type'] == 'replace':
                print(f"      '{err['std_text']}' → '{err['ext_text']}'")
    
    if categories['word_errors']:
        print("\n   📝 SAI TỪ/CỤM TỪ:")
        shown = set()
        for err in categories['word_errors'][:10]:
            if err['type'] == 'replace' and len(err['std_text']) <= 15:
                key = f"{err['std_text']}→{err['ext_text']}"
                if key not in shown:
                    shown.add(key)
                    print(f"      '{err['std_text']}' → '{err['ext_text']}'")
    
    print("\n" + "=" * 80)
    print("KẾT LUẬN:")
    print(f"   Tổng số lỗi: {total_errors}")
    print(f"   Độ chính xác: {accuracy:.2f}%")
    
    if accuracy >= 95:
        print(f"   🎉 Xuất sắc! Rất đáng tin cậy")
    elif accuracy >= 90:
        print(f"   ✅ Tốt! Có thể sử dụng được")
    elif accuracy >= 85:
        print(f"   ⚠️ Khá! Cần hiệu chỉnh thêm một chút")
    else:
        print(f"   ❌ Cần cải thiện! Nhiều lỗi cần sửa")
    print("=" * 80)
    
    return accuracy, total_errors, categories

if __name__ == '__main__':
    main()
