#!/usr/bin/env python3
"""
patch_telegram_tiers_fix2.py
============================
Wires format_tier_lots() into the ORDER PLACED message. Previous fix falsely
detected the helper DEFINITION as the call. This checks the call site properly.
"""
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: not found"); sys.exit(1)
print(f"Target: {target}")

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

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

if "def format_tier_lots" not in src:
    print("ERROR: helper missing. Run first patcher."); sys.exit(2)

# Proper check: is the call already wired into the MESSAGE? Look for the
# distinctive insertion line, NOT the function definition.
if '+ format_tier_lots(lot_size)' in src or '+ "\\n" + format_tier_lots' in src.replace('\n','NL'):
    # be precise: check for the call appended after Ticket line
    if 'format_tier_lots(lot_size)\n              )' in src or \
       'format_tier_lots(lot_size)\r\n              )' in src:
        print("Call already wired. Nothing to do."); sys.exit(0)

# Match exact Ticket line + closing paren. From the grep, indent on message
# string lines is 18 spaces; the closing ) is at 14 spaces.
target_block='                  f"Ticket: {ticket}"\n              )'
cnt=src.count(target_block)
print(f"Exact Ticket+paren matches: {cnt}")

if cnt==1:
    repl='                  f"Ticket: {ticket}"\n                  + "\\n" + format_tier_lots(lot_size)\n              )'
    src=src.replace(target_block, repl, 1)
    ok=True
else:
    # Try CRLF variant
    target_crlf=target_block.replace('\n','\r\n')
    if src.count(target_crlf)==1:
        repl='                  f"Ticket: {ticket}"\r\n                  + "\\n" + format_tier_lots(lot_size)\r\n              )'
        src=src.replace(target_crlf, repl, 1)
        ok=True
    else:
        print(f"ERROR: could not uniquely match (LF={cnt}, CRLF={src.count(target_crlf)}).")
        print("No change made. Backup safe.")
        sys.exit(3)

try:
    ast.parse(src); print("Syntax: 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("Verify with the grep, then restart the monitor.")
