"""
对比两台机器的日志文件，标记第一个差异点。
用法: runtime\python\python.exe scripts\diagnose_compare.py log_a.txt log_b.txt
"""
import sys, re

# Pattern for log timestamps: [2026-07-14 20:00:00,123]
_TS_PATTERN = re.compile(r'^\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}\]')

def strip_timestamp(line):
    """Remove leading timestamp from a log line for comparison."""
    return _TS_PATTERN.sub('', line, count=1).strip()

def extract_key(line):
    """Extract [TAG] key=value from a log line for comparison."""
    m = re.match(r'\[(\w+)\]', line)
    if m:
        return m.group(0)  # return the [TAG]
    return line[:50]

def main():
    if len(sys.argv) < 3:
        print('用法: diagnose_compare.py <机器A日志> <机器B日志>')
        sys.exit(1)
    
    with open(sys.argv[1], 'r', encoding='utf-8') as f:
        lines_a = f.readlines()
    with open(sys.argv[2], 'r', encoding='utf-8') as f:
        lines_b = f.readlines()
    
    max_lines = min(len(lines_a), len(lines_b))
    first_diff = None
    
    for i in range(max_lines):
        a_stripped = strip_timestamp(lines_a[i])
        b_stripped = strip_timestamp(lines_b[i])
        
        if a_stripped != b_stripped:
            if first_diff is None:
                first_diff = i
    
    if first_diff is None:
        if len(lines_a) != len(lines_b):
            print(f'[MATCH] 前 {max_lines} 行一致, 但行数不同 (A={len(lines_a)}, B={len(lines_b)})')
        else:
            print('[MATCH] 两份日志完全一致')
    else:
        start = max(0, first_diff - 3)
        print(f'[DIFF] 首个差异在行 {first_diff + 1}:')
        print('--- 机器A ---')
        print(''.join(lines_a[start:first_diff + 3]))
        print('--- 机器B ---')
        print(''.join(lines_b[start:first_diff + 3]))

if __name__ == '__main__':
    main()
