#!/usr/bin/env python3
"""
patch_telegram_tiers_fix.py
===========================
Finishes the tier patch: the helper format_tier_lots() is already inserted;
this just wires it into the ORDER PLACED message.

Matches the exact Ticket line + closing paren (18-space indent) and inserts
the tier block call before the closing paren.
"""
import sys, shutil, ast
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: monitor not found"); sys.exit(1)
print(f"Target: {target}")

backup=target.with_suffix(".py.backup_tiers2")
shutil.copy2(target, backup); print(f"Backup: {backup}")

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

if "format_tier_lots(lot_size)" in src:
    print("Tier call already present. Nothing to do."); sys.exit(0)
if "def format_tier_lots" not in src:
    print("ERROR: helper not found - run the first patcher first."); sys.exit(2)

# Match the exact Ticket line + the closing paren on its own line (18-sp indent).
old='''                  f"Ticket: {ticket}"
              )'''
new='''                  f"Ticket: {ticket}"
                  + "\\n" + format_tier_lots(lot_size)
              )'''

cnt=src.count(old)
if cnt==1:
    src=src.replace(old,new,1)
    ok=True
elif cnt==0:
    # try a more tolerant match: just the Ticket line, insert after it
    alt='                  f"Ticket: {ticket}"\n'
    if src.count(alt)==1:
        src=src.replace(alt, alt+'                  + "\\n" + format_tier_lots(lot_size)\n',1)
        ok=True
    else:
        print(f"ERROR: could not match (Ticket-line count={src.count(alt)}). No change.")
        sys.exit(3)
else:
    print(f"ERROR: ambiguous, Ticket+paren found {cnt} times. No change.")
    sys.exit(3)

try:
    ast.parse(src); print("Syntax check: OK")
except SyntaxError as e:
    print(f"SYNTAX ERROR: {e} -- not writing."); sys.exit(4)

target.write_text(src, encoding="utf-8")
print("Message patched: True")
print("\\nSUCCESS. Restart the monitor; next ORDER PLACED alert includes the tier block.")
