#!/usr/bin/env python3
from __future__ import annotations

import json
import subprocess
import sys
from pathlib import Path

WORKDIR = Path('/home/agent/projects/CryptoTradingBot/Crypto_Agent')
CMD = [sys.executable, '-m', 'src.tools.tradingview_paper_bridge', '--runtime-dir', 'runtime', '--json']

proc = subprocess.run(CMD, cwd=WORKDIR, text=True, capture_output=True, timeout=120)
if proc.returncode != 0:
    print('⚠️ TradingView Paper Bridge Fehler')
    print(proc.stderr.strip()[-1000:] or proc.stdout.strip()[-1000:])
    raise SystemExit(proc.returncode)

try:
    data = json.loads(proc.stdout)
except json.JSONDecodeError:
    print('⚠️ TradingView Paper Bridge JSON konnte nicht gelesen werden')
    print(proc.stdout.strip()[-1000:])
    raise SystemExit(1)

processed = int(data.get('processed') or 0)
paper_trades = int(data.get('paper_trades') or 0)
paper_exits = int(data.get('paper_exits') or 0)
blocked = data.get('blocked') or {}
live_allowed = bool(data.get('live_order_allowed'))
signed = bool(data.get('mainnet_signed_action'))

# Watchdog pattern: stay silent when there is nothing new and no danger.
if processed or paper_trades or paper_exits or blocked or live_allowed or signed:
    print('📡 TradingView Paper Bridge')
    print(f'processed={processed}, entries={paper_trades}, exits={paper_exits}, blocked={blocked or "keine"}')
    print(f'live_order_allowed={str(live_allowed).lower()}, mainnet_signed_action={str(signed).lower()}')
    if live_allowed or signed:
        print('🚫 WARNUNG: Unerwartetes Live-Flag erkannt — prüfen!')
