"""
fix_trade_407.py
Directly corrects the net_pnl for trade #1675593149 in the EU trade history
JSON, reading the true value from MT5's position-specific deal query.

Safe: makes a backup, verifies the value from MT5 before writing, prints
before/after. Only touches the one ticket.
"""
import json
import shutil
from pathlib import Path
import MetaTrader5 as mt5

TICKET = 1675593149
jpath = Path(r"C:\Users\Administrator\OneDrive\fx_macro_intraday\data\logs\trade_history_eurusd.json")

# 1. Get the real P&L from MT5 (position-specific query — the reliable one)
mt5.initialize()
deals = mt5.history_deals_get(position=TICKET)
mt5.shutdown()

if not deals:
    print(f"ERROR: MT5 returned no deals for position {TICKET}. Aborting.")
    raise SystemExit(1)

real_pnl = sum(d.profit + d.swap + d.commission for d in deals)
print(f"MT5 deals for {TICKET}: {len(deals)}")
for d in deals:
    entry = {0:'IN',1:'OUT'}.get(d.entry, d.entry)
    print(f"  entry={entry} profit={d.profit} swap={d.swap} comm={d.commission}")
print(f"Real net P&L: {real_pnl:.2f}")

if abs(real_pnl) < 0.01:
    print("ERROR: computed P&L is ~0. Something's wrong. Aborting, no write.")
    raise SystemExit(2)

# 2. Backup the JSON
backup = jpath.with_suffix(".json.backup_407fix")
shutil.copy2(jpath, backup)
print(f"\nBackup: {backup}")

# 3. Load, find the entry, update only if it's currently 0.0
trades = json.loads(jpath.read_text(encoding="utf-8"))
found = False
for t in trades:
    if t["ticket"] == TICKET:
        found = True
        old = t["net_pnl"]
        if old != 0.0:
            print(f"\nTrade {TICKET} already has net_pnl={old} (not 0.0). "
                  f"No change made to avoid clobbering.")
            raise SystemExit(0)
        t["net_pnl"] = round(real_pnl, 2)
        print(f"\nUpdated {TICKET}: net_pnl {old} -> {t['net_pnl']}")
        break

if not found:
    print(f"ERROR: ticket {TICKET} not found in JSON. Aborting.")
    raise SystemExit(3)

# 4. Write back
jpath.write_text(json.dumps(trades, indent=2), encoding="utf-8")

# 5. Verify
check = json.loads(jpath.read_text(encoding="utf-8"))
new_total = sum(x["net_pnl"] for x in check)
print(f"\nVerified. EU trade count: {len(check)}")
print(f"New EU net P&L sum: {new_total:.2f}")
