#!/usr/bin/env python3
"""
patch_telegram_tiers.py
=======================
Adds a 3-tier lot-size block to the [pair] ORDER PLACED Telegram alert.

Approach: REUSE the system's own computed lot_size (the $300k-equivalent at
0.75% risk) and scale it for the smaller tiers. This guarantees the $300k tier
always matches what the account actually trades.

  $300k notional tier = lot_size        (0.75% risk - current live sizing)
  $150k notional tier = lot_size * 0.5   (0.375% risk)
  $100k notional tier = lot_size * 0.3333 (0.25% risk)

FTMO pass-rate ranges (v4, 2-step swing) shown next to each tier.

Inserts:
  1) a helper format_tier_lots(lot_size) near the other helpers
  2) the helper's output into the ORDER PLACED message (after the Lots: line)

Backs up; tolerant matching; verifies.
"""
import sys, shutil
from pathlib import Path

candidates=[
    Path(r"C:\Users\Administrator\OneDrive\fx_macro_intraday\src\execution\live_signal_monitor_v3.py"),
    Path(r"C:\Users\paul_\OneDrive\fx_macro_intraday\src\execution\live_signal_monitor_v3.py"),
]
target=next((p for p in candidates if p.exists()), None)
if target is None:
    print("ERROR: live_signal_monitor_v3.py not found"); sys.exit(1)
print(f"Target: {target}")

backup=target.with_suffix(".py.backup_tiers")
if not backup.exists():
    shutil.copy2(target, backup); print(f"Backup: {backup}")
else:
    print(f"Backup exists: {backup}")

src=target.read_text(encoding="utf-8")

if "format_tier_lots" in src:
    print("Already applied. Nothing to do."); sys.exit(0)

# ---- 1) Insert helper just before 'def place_order' ----
helper = '''
# --- FTMO notional-tier lot sizes for Telegram followers -------------------
# Reuses the system's own computed lot_size (the $300k-equivalent at 0.75%
# risk) and scales it for smaller tiers. Followers pick ONE tier and stick to
# it. TP/SL are identical across tiers; only lot size differs. Lots are based
# on a fresh $100k USD account.
TIER_SCALES = [
    ("$300k", 1.0,      "73-85%"),
    ("$150k", 0.5,      "91-95%"),
    ("$100k", 0.33333,  "92-97%"),
]
def format_tier_lots(lot_size):
    """Return an HTML block listing lot size per notional tier + FTMO pass range."""
    lines = ["", "<b>\\U0001F4CA LOT SIZE BY NOTIONAL</b> \\u2014 pick one &amp; stick to it",
             "<i>(based on a fresh $100k USD account \\u00b7 TP/SL identical)</i>"]
    for label, scale, passrate in TIER_SCALES:
        lots = lot_size * scale
        lines.append(f"<code>{label} \\u2192 {lots:5.2f} lots</code> \\u00b7 {passrate} FTMO pass")
    return "\\n".join(lines)

'''
anchor="def place_order(pair, signal, entry_price, lot_size, zscore_abs):"
if anchor in src:
    src=src.replace(anchor, helper+anchor, 1)
    ok_helper=True
else:
    ok_helper=False

# ---- 2) Add the tier block to the ORDER PLACED message ----
# The message ends with the Ticket line. We append the tier block to the Lots line.
# Match the existing message's "Lots:" line within the ORDER PLACED send_telegram.
old_msg='''                  f"Lots: {lot_size:.2f}\\n"
                  f"TP: {tp_px:.{dp}f}\\n"
                  f"SL: {sl_px:.{dp}f}\\n"
                  f"Ticket: {ticket}"'''
new_msg='''                  f"Lots: {lot_size:.2f}\\n"
                  f"TP: {tp_px:.{dp}f}\\n"
                  f"SL: {sl_px:.{dp}f}\\n"
                  f"Ticket: {ticket}"
                  + "\\n" + format_tier_lots(lot_size)'''

def try_replace(s, old, new):
    if old in s: return s.replace(old,new,1), True
    # tolerate single vs double backslash-n already being real newlines:
    old2=old.replace('\\n','\n')
    if old2 in s:
        new2=new.replace('\\n','\n')
        return s.replace(old2,new2,1), True
    return s, False

src, ok_msg = try_replace(src, old_msg, new_msg)

target.write_text(src, encoding="utf-8")
print(f"Helper inserted   : {ok_helper}")
print(f"Message patched   : {ok_msg}")
import ast
try:
    ast.parse(src); print("Syntax check      : OK")
except SyntaxError as e:
    print(f"SYNTAX ERROR: {e} -- restoring backup")
    shutil.copy2(backup, target)
    print("Restored backup. No changes applied. Send the exact message block.")
    sys.exit(3)
if ok_helper and ok_msg:
    print("\\nSUCCESS. Restart the monitor for the next signal to include tiers.")
else:
    print("\\nPARTIAL: one anchor not matched. Backup safe. Send the exact block that failed.")
