"""Nettoie les champs reason corrompus dans trade_history.json"""
import json

with open('trade_history.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

def clean_reason(s):
    if not isinstance(s, str):
        return s
    if any(ord(c) > 127 for c in s):
        clean = ''
        for ch in s:
            if ord(ch) > 127:
                break
            clean += ch
        clean = clean.rstrip(' (').strip()
        if 'ai-strong-sell' in clean:
            return 'ai-strong-sell (LSTM)'
        elif 'ai-sell' in clean:
            return 'ai-sell (LSTM)'
        elif clean:
            return clean
        return 'ai-sell'
    return s

fixed_count = 0
for trade in data:
    val = trade.get('reason', '')
    fixed = clean_reason(val)
    if fixed != val:
        sym = trade.get('symbol', '?')
        print(f"Fixed {sym}: {repr(val[:50])} -> {repr(fixed)}")
        trade['reason'] = fixed
        fixed_count += 1

print(f'Total fixes: {fixed_count}')
with open('trade_history.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, indent=2, ensure_ascii=False)
print('trade_history.json saved OK')
