#!/usr/bin/env python3
"""
Script để cải thiện định dạng markdown cho file Tam-Bao-146-170-edited.md
- Thêm newline sau header
- Thêm newline sau dấu câu kết thúc câu
- Sửa blockquote format
"""

import re
import sys

def fix_format(content):
    # Thêm newline sau header ## và ###
    content = re.sub(r'(## [^\n]+)(?! \n)', r'\1\n', content)
    content = re.sub(r'(### [^\n]+)(?! \n)', r'\1\n', content)
    
    # Thêm newline sau dấu chấm câu Myanmar (။) khi không có newline
    content = re.sub(r'။([^\n])', r'။\n\1', content)
    
    # Sửa blockquote: đảm bảo có khoảng trắng sau >
    content = re.sub(r'^>([^ >])', r'> \1', content, flags=re.MULTILINE)
    
    # Thêm newline trước ---
    content = re.sub(r'([^ \n])---', r'\1\n---', content)
    
    # Thêm newline sau ---
    content = re.sub(r'---([^ \n])', r'---\n\1', content)
    
    # Xóa khoảng trắng thừa
    content = re.sub(r'  +', ' ', content)
    
    return content

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("Usage: python fix_format.py <file>")
        sys.exit(1)
    
    filepath = sys.argv[1]
    with open(filepath, 'r', encoding='utf-8') as f:
        content = f.read()
    
    fixed = fix_format(content)
    
    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(fixed)
    
    print(f"✅ Đã sửa định dạng: {filepath}")
