import sys, os
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
rep = chr(0xfffd)
base = 'D:\\Code\\DTU 程序\\STM32F4-Base\\'

all_fixes = [
    # (filename, pattern_to_match, replacement_full_line_fragment)
    
    # ch395f.c
    ('ch395f.c', 'rx_buf[' + rep + '? *          阻塞', 'rx_buf] *          阻塞'),
    ('ch395f.c', '默认值10' + rep + '?秒）', '默认值10 秒）'),
    ('ch395f.c', '默认值3' + rep + '?  uint8_t', '默认值3  uint8_t'),
    
    # ch395f_test.c
    ('ch395f_test.c', '回显' + rep + '? \ufffd?PING', '回显，PING'),
    ('ch395f_test.c', '创建' + rep + '? UDP', '创建 UDP'),
    ('ch395f_test.c', 'IP，打印结果 ' + rep + '?广播', 'IP，打印结果，广播'),
    
    # gd5f2gq5ue.c
    ('gd5f2gq5ue.c', '块对' + rep + '? *           size', '块对齐 *           size'),
    
    # sd2506.c
    ('sd2506.c', '个位存入' + rep + '4 ）', '个位存入低 4 ）'),
    
    # tpafe5160.c
    ('tpafe5160.c', '6位数据总线' + rep + '?GPIOG', '16位数据总线（GPIOG'),
    ('tpafe5160.c', '滞后约 18-24ns' + rep + '? *', '滞后约 18-24ns，*'),
    ('tpafe5160.c', '电压' + rep + '? float', '电压值 float'),
    ('tpafe5160.c', 'IDR ' + rep + '?6位', 'IDR 16位'),
    ('tpafe5160.c', '~18ns ' + rep + '?RD 引脚', '~18ns，RD 引脚'),
]

# Additional generic cleanups for things our fixes missed
# These handle cases where ? should be a specific Chinese character or punctuation
more_fixes = [
    # Closing paren patterns
    ('ch395f.c', rep + '?\ufffd?' + u'10\ufffd?' + u'\u79d2', ' '),
    ('tpafe5160.c', u'\ufffd?' + u'HELLO', ''),
]

# Remaining problematic patterns from output
specific = [
    # ch395f_test.c - the ?HELLO issue
    ('Drivers\\BSP\\CH395F\\ch395f_test.c', u'结果 ' + rep + '?' + u'广播', u'结果，广播'),
    # tpafe5160 line with multiple corruptions
    ('Drivers\\BSP\\TPAFE5160\\tpafe5160.c', u'总线' + rep + '?GPIOG', u'总线（GPIOG'),
]

total_fixed = 0
for fname, needle, replacement in all_fixes:
    path = None
    for f in ['Drivers\\BSP\\CH395F\\ch395f.c', 'Drivers\\BSP\\CH395F\\ch395f_test.c',
              'Drivers\\BSP\\GD5F2GQ5UE\\gd5f2gq5ue.c', 'Drivers\\BSP\\NET\\net_select.c',
              'Drivers\\BSP\\SD2506\\sd2506.c', 'Drivers\\BSP\\TPAFE5160\\tpafe5160.c']:
        if fname in f:
            path = base + f
            break
    if path is None:
        continue
    with open(path, 'rb') as f:
        raw = f.read()
    text = raw.decode('utf-8', errors='replace')
    before = text.count(rep)
    
    if needle in text:
        text = text.replace(needle, replacement)
        after = text.count(rep)
        fixed = before - after
        total_fixed += fixed
        print('{}: fixed ({} -> {})'.format(fname, before, after))
    else:
        # Check what's actually in the file
        lines = text.split(chr(10))
        found = False
        search_prefix = needle[:10]
        for i, line in enumerate(lines, 1):
            if rep in line and search_prefix in line:
                idx = line.index(rep)
                ctx = line[max(0,idx-20):idx+20]
                print('{}: pattern not matched, closest at L{}: ...{}...'.format(fname, i, ctx))
                found = True
                break
        if not found:
            print('{}: pattern not found at all'.format(fname))
    
    with open(path, 'wb') as f:
        f.write(text.encode('utf-8'))

print('\nTotal fixed this pass: {}'.format(total_fixed))

# Show remaining
print('\n=== REMAINING ===')
for fname in ['Drivers\\BSP\\CH395F\\ch395f.c', 'Drivers\\BSP\\CH395F\\ch395f_test.c',
              'Drivers\\BSP\\GD5F2GQ5UE\\gd5f2gq5ue.c', 'Drivers\\BSP\\NET\\net_select.c',
              'Drivers\\BSP\\SD2506\\sd2506.c', 'Drivers\\BSP\\TPAFE5160\\tpafe5160.c']:
    path = base + fname
    with open(path, 'rb') as f:
        text = f.read().decode('utf-8', errors='replace')
    remaining = text.count(rep)
    if remaining > 0:
        print('\n--- {} remaining in {} ---'.format(remaining, fname))
        for i, line in enumerate(text.split(chr(10)), 1):
            if rep in line:
                idx = line.index(rep)
                left = line[max(0,idx-40):idx]
                right = line[idx+2:idx+40]
                print('L{}: ...{}[?]{}...'.format(i, left, right))
