#!/usr/bin/env python3
"""
pivot.py

Tiingo WebSocket pivot daemon with Telegram alerts and H1 EMA20/EMA50 context.
The trading pair is configurable via the TRADING_PAIR environment variable (default: eurusd).

Features:
- One Tiingo Forex WebSocket connection for live bid/ask/mid.
- Tiingo REST daily OHLC for classic pivots: PP, R1/R2/R3, S1/S2/S3.
- Tiingo REST H1 candles for EMA20/EMA50.
- Session high/low tracking.
- Detects pivot breakouts, PP acceptance, support/resistance rejection.
- Sends Telegram alerts for:
  * daemon started
  * daemon stopped gracefully
  * pivot breakout / acceptance / rejection
  * H1 EMA20/EMA50 bullish/bearish cross with nearest pivot context
- Writes dashboard JSON to PIVOT_OUTPUT_JSON.

Required packages:
  pip install websocket-client requests python-dotenv

Environment variables:
  TRADING_PAIR              Forex pair ticker, e.g. eurusd, xauusd, gbpusd (default: eurusd)
  TIINGO_TOKEN              Tiingo API token (required)
  TELEGRAM_ENABLED          Set to 1 to enable Telegram alerts
  TELEGRAM_BOT_TOKEN        Telegram bot token
  TELEGRAM_CHAT_ID          Telegram chat ID
  PIVOT_OUTPUT_JSON         Path for dashboard JSON output (default: ./pivot.json)
  LOG_LEVEL                 Logging level: DEBUG, INFO, WARNING (default: INFO)
"""

import argparse
import json
import logging
import os
import signal
import time
from dataclasses import asdict, dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Dict, Optional
from zoneinfo import ZoneInfo

import requests
from websocket import create_connection, WebSocketConnectionClosedException, WebSocketTimeoutException

try:
    from dotenv import load_dotenv
    load_dotenv(Path(__file__).resolve().parent / ".env", override=False)
except ImportError:
    pass

TIINGO_WS_URL = "wss://api.tiingo.com/fx"
TIINGO_REST_URL = "https://api.tiingo.com/tiingo/fx/{ticker}/prices"
TELEGRAM_API_URL = "https://api.telegram.org/bot{token}/sendMessage"

# Configurable via TRADING_PAIR env var (e.g. eurusd, xauusd, gbpusd).
# Stored lowercase to match Tiingo's ticker format; use PAIR.upper() for display.
PAIR = os.environ.get("TRADING_PAIR", "eurusd").strip().lower()

STOP = False
STOP_REASON = "normal shutdown"


def signal_handler(signum, frame):
    global STOP, STOP_REASON
    STOP = True
    if signum == signal.SIGTERM:
        STOP_REASON = "SIGTERM received"
    elif signum == signal.SIGINT:
        STOP_REASON = "SIGINT / CTRL+C received"
    else:
        STOP_REASON = f"Signal {signum} received"
    raise SystemExit(0)


signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)


@dataclass
class OHLC:
    date: str
    open: float
    high: float
    low: float
    close: float


@dataclass
class Tick:
    ts_utc: str
    bid: float
    ask: float
    mid: float


@dataclass
class EMAContext:
    timeframe: str
    ema20: float
    ema50: float
    last_close: float
    last_bar_time_utc: str
    bias: str
    price_position: str


def parse_iso(ts: str) -> datetime:
    """Parse an ISO-8601 timestamp robustly, handling Z, +00:00, and bare offsets."""
    ts = ts.strip()
    # Normalise the various UTC suffix forms to +00:00 for fromisoformat
    if ts.endswith("Z"):
        ts = ts[:-1] + "+00:00"
    elif ts.endswith("+0000") or ts.endswith("-0000"):
        ts = ts[:-5] + "+00:00"
    return datetime.fromisoformat(ts)


def env_float(name: str, default: float, minimum: Optional[float] = None) -> float:
    raw = os.environ.get(name, "").strip()
    if not raw:
        return default
    try:
        value = float(raw)
        if minimum is not None and value < minimum:
            raise ValueError
        return value
    except ValueError:
        logging.warning("Invalid %s=%r, using default %.6f", name, raw, default)
        return default


def env_int(name: str, default: int, minimum: Optional[int] = None) -> int:
    raw = os.environ.get(name, "").strip()
    if not raw:
        return default
    try:
        value = int(raw)
        if minimum is not None and value < minimum:
            raise ValueError
        return value
    except ValueError:
        logging.warning("Invalid %s=%r, using default %d", name, raw, default)
        return default


def telegram_enabled() -> bool:
    return os.environ.get("TELEGRAM_ENABLED", "0").strip() == "1"


def send_telegram_alert(text: str) -> None:
    if not telegram_enabled():
        return
    bot_token = os.environ.get("TELEGRAM_BOT_TOKEN", "").strip()
    chat_id = os.environ.get("TELEGRAM_CHAT_ID", "").strip()
    if not bot_token or not chat_id:
        logging.warning("Telegram enabled but TELEGRAM_BOT_TOKEN or TELEGRAM_CHAT_ID is missing")
        return
    try:
        response = requests.post(
            TELEGRAM_API_URL.format(token=bot_token),
            json={
                "chat_id": chat_id,
                "text": text,
                "parse_mode": "HTML",
                "disable_web_page_preview": True,
            },
            timeout=10,
        )
        if response.status_code != 200:
            logging.warning("Telegram send failed HTTP %s: %s", response.status_code, response.text[:300])
    except Exception as exc:
        logging.warning("Telegram alert error: %s", exc)


def send_startup_telegram_message() -> None:
    send_telegram_alert(
        f"✅ <b>{PAIR.upper()} Pivot Daemon Started</b>\n\n"
        f"Source: Tiingo WebSocket\n"
        f"Pair: {PAIR.upper()}\n"
        f"Mode: Pivot + H1 EMA20/EMA50 monitor"
    )


def send_stop_telegram_message(reason: str = "stopped") -> None:
    send_telegram_alert(
        f"🛑 <b>{PAIR.upper()} Pivot Daemon Stopped</b>\n\n"
        f"<b>Reason:</b> {reason}\n"
        f"Source: Tiingo WebSocket\n"
        f"Pair: {PAIR.upper()}\n"
        f"Mode: Pivot + H1 EMA20/EMA50 monitor\n\n"
        f"<b>Stopped UTC:</b> {datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')}"
    )


def send_crash_telegram_message(error: Exception) -> None:
    send_telegram_alert(
        f"❌ <b>{PAIR.upper()} Pivot Daemon Crashed</b>\n\n"
        f"<b>Error:</b> {str(error)[:500]}\n"
        f"<b>Time UTC:</b> {datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')}"
    )


class PivotEngine:
    def __init__(
        self,
        break_tol: float,
        balance_band: float,
        accept_seconds: int,
        session_tz: str,
        reset_hour: int,
        alert_cooldown_seconds: int,
    ):
        self.break_tol = break_tol
        self.balance_band = balance_band
        self.accept_seconds = accept_seconds
        self.session_zone = ZoneInfo(session_tz)
        self.reset_hour = reset_hour
        self.alert_cooldown_seconds = alert_cooldown_seconds

        self.ohlc: Optional[OHLC] = None
        self.pivots: Dict[str, float] = {}
        self.ema_context: Optional[EMAContext] = None

        self.session_key: Optional[str] = None
        self.session_high: Optional[float] = None
        self.session_low: Optional[float] = None
        self.accept_above_since: Optional[float] = None
        self.accept_below_since: Optional[float] = None

        self.last_alert_signature = ""
        self.last_alert_time = 0.0
        self.last_ema_cross_signature = ""

    @staticmethod
    def daily_pivots(ohlc: OHLC) -> Dict[str, float]:
        high, low, close = float(ohlc.high), float(ohlc.low), float(ohlc.close)
        price_range = high - low
        pp = (high + low + close) / 3.0
        r1 = 2 * pp - low
        s1 = 2 * pp - high
        r2 = pp + price_range
        s2 = pp - price_range
        r3 = high + 2 * (pp - low)
        s3 = low - 2 * (high - pp)
        return {
            "PP": round(pp, 5), "R1": round(r1, 5), "R2": round(r2, 5), "R3": round(r3, 5),
            "S1": round(s1, 5), "S2": round(s2, 5), "S3": round(s3, 5),
            "range": round(price_range, 5), "close": round(close, 5),
        }

    def set_ohlc(self, ohlc: OHLC) -> None:
        self.ohlc = ohlc
        self.pivots = self.daily_pivots(ohlc)
        price_range = float(ohlc.high) - float(ohlc.low)
        close_ref = float(ohlc.close) or 1.0
        logging.info(
            "Loaded OHLC %s O=%.5f H=%.5f L=%.5f C=%.5f range=%.5f (%.4f%%)",
            ohlc.date, ohlc.open, ohlc.high, ohlc.low, ohlc.close, price_range, price_range / close_ref * 100,
        )
        if price_range / close_ref < 0.0005:  # less than 0.05% of price – likely a stub candle
            logging.warning(
                "OHLC range is very small (%.5f, %.4f%%) – pivot levels may be compressed. "
                "Check Tiingo data quality for %s.",
                price_range, price_range / close_ref * 100, ohlc.date,
            )
        logging.info(
            "Pivots PP=%.5f R1=%.5f R2=%.5f R3=%.5f S1=%.5f S2=%.5f S3=%.5f",
            self.pivots["PP"], self.pivots["R1"], self.pivots["R2"], self.pivots["R3"],
            self.pivots["S1"], self.pivots["S2"], self.pivots["S3"],
        )

    def set_ema_context(self, ema: EMAContext) -> Optional[str]:
        previous_bias = self.ema_context.bias if self.ema_context else None
        self.ema_context = ema
        logging.info(
            "Hourly EMA loaded EMA20=%.2f EMA50=%.2f close=%.2f bias=%s position=%s",
            ema.ema20, ema.ema50, ema.last_close, ema.bias, ema.price_position,
        )
        if previous_bias is None or previous_bias == ema.bias:
            return None
        signature = f"{ema.last_bar_time_utc}:{previous_bias}->{ema.bias}"
        if signature == self.last_ema_cross_signature:
            return None
        self.last_ema_cross_signature = signature
        if previous_bias in {"bearish", "neutral"} and ema.bias == "bullish":
            return "ema20_cross_above_ema50"
        if previous_bias in {"bullish", "neutral"} and ema.bias == "bearish":
            return "ema20_cross_below_ema50"
        return None

    def session_key_for_tick(self, tick_iso: str) -> str:
        dt = parse_iso(tick_iso).astimezone(self.session_zone)
        if dt.hour < self.reset_hour:
            dt -= timedelta(days=1)
        return dt.date().isoformat()

    def update_session(self, tick: Tick) -> None:
        key = self.session_key_for_tick(tick.ts_utc)
        if self.session_key != key:
            self.session_key = key
            self.session_high = tick.mid
            self.session_low = tick.mid
            self.accept_above_since = None
            self.accept_below_since = None
            self.last_alert_signature = ""
            logging.info("New session %s reset high/low at %.2f", key, tick.mid)
            return
        self.session_high = tick.mid if self.session_high is None else max(self.session_high, tick.mid)
        self.session_low = tick.mid if self.session_low is None else min(self.session_low, tick.mid)

    def should_alert(self, state: str, level: str) -> bool:
        actionable = {
            "breakout_up", "breakout_down", "accept_above_pp", "accept_below_pp",
            "rejection_down_from_resistance", "rejection_up_from_support",
        }
        if state not in actionable:
            if state in {"balance", "testing_above_pp", "testing_below_pp"}:
                self.last_alert_signature = ""
            return False
        now = time.time()
        signature = f"{self.session_key}:{state}:{level}"
        if signature == self.last_alert_signature:
            return False
        if now - self.last_alert_time < self.alert_cooldown_seconds:
            return False
        self.last_alert_signature = signature
        self.last_alert_time = now
        return True

    def classify(self, tick: Tick) -> Dict[str, Any]:
        if not self.pivots:
            return {"state": "no_pivots", "level": "", "event": False}

        price = tick.mid
        pp = self.pivots["PP"]
        prior_range = max(self.pivots["range"], 0.00010)  # floor at 1 pip; avoids div-by-zero on bad data
        breakout_tolerance = prior_range * self.break_tol
        balance_band_points = prior_range * self.balance_band
        now = time.time()

        state = "balance"
        level = "PP"
        rejection_level = ""

        for lvl in ("R3", "R2", "R1"):
            if price > self.pivots[lvl] + breakout_tolerance:
                state, level = "breakout_up", lvl
                break

        if state == "balance":
            for lvl in ("S3", "S2", "S1"):
                if price < self.pivots[lvl] - breakout_tolerance:
                    state, level = "breakout_down", lvl
                    break

        if state == "balance":
            sh, sl = self.session_high, self.session_low
            if sh is not None:
                if sh >= self.pivots["R3"] and self.pivots["R2"] < price < self.pivots["R3"]:
                    state, level, rejection_level = "rejection_down_from_resistance", "R3", "R3"
                elif sh >= self.pivots["R2"] and self.pivots["R1"] < price < self.pivots["R2"]:
                    state, level, rejection_level = "rejection_down_from_resistance", "R2", "R2"
                elif sh >= self.pivots["R1"] and pp < price < self.pivots["R1"]:
                    state, level, rejection_level = "rejection_down_from_resistance", "R1", "R1"
            if state == "balance" and sl is not None:
                if sl <= self.pivots["S3"] and self.pivots["S3"] < price < self.pivots["S2"]:
                    state, level, rejection_level = "rejection_up_from_support", "S3", "S3"
                elif sl <= self.pivots["S2"] and self.pivots["S2"] < price < self.pivots["S1"]:
                    state, level, rejection_level = "rejection_up_from_support", "S2", "S2"
                elif sl <= self.pivots["S1"] and self.pivots["S1"] < price < pp:
                    state, level, rejection_level = "rejection_up_from_support", "S1", "S1"

        if state == "balance":
            if price > pp + balance_band_points:
                if self.accept_above_since is None:
                    self.accept_above_since = now
                self.accept_below_since = None
                state, level = ("accept_above_pp", "PP") if now - self.accept_above_since >= self.accept_seconds else ("testing_above_pp", "PP")
            elif price < pp - balance_band_points:
                if self.accept_below_since is None:
                    self.accept_below_since = now
                self.accept_above_since = None
                state, level = ("accept_below_pp", "PP") if now - self.accept_below_since >= self.accept_seconds else ("testing_below_pp", "PP")
            else:
                self.accept_above_since = None
                self.accept_below_since = None
                state, level = "balance", "PP"

        nearest = min(["PP", "R1", "R2", "R3", "S1", "S2", "S3"], key=lambda x: abs(price - self.pivots[x]))
        return {
            "pair": PAIR,
            "timestamp_utc": tick.ts_utc,
            "price": round(price, 5),
            "bid": round(tick.bid, 5),
            "ask": round(tick.ask, 5),
            "spread": round(tick.ask - tick.bid, 5),
            "state": state,
            "level": level,
            "rejection_level": rejection_level,
            "event": self.should_alert(state, level),
            "nearest_level": {
                "name": nearest,
                "value": self.pivots[nearest],
                "distance": round(abs(price - self.pivots[nearest]), 5),
                "side": "above" if price > self.pivots[nearest] else "below" if price < self.pivots[nearest] else "at",
            },
            "session": {
                "timezone": str(self.session_zone),
                "reset_hour": self.reset_hour,
                "key": self.session_key,
                "high": round(self.session_high, 5) if self.session_high is not None else None,
                "low": round(self.session_low, 5) if self.session_low is not None else None,
            },
            "pivots": self.pivots,
            "ohlc": asdict(self.ohlc) if self.ohlc else None,
            "ema": asdict(self.ema_context) if self.ema_context else None,
            "settings": {
                "break_tol": self.break_tol,
                "balance_band": self.balance_band,
                "accept_seconds": self.accept_seconds,
                "breakout_tolerance_points": round(breakout_tolerance, 5),
                "balance_band_points": round(balance_band_points, 5),
            },
        }


def calculate_ema(values, period: int) -> float:
    if len(values) < period:
        raise RuntimeError(f"Need at least {period} closes to calculate EMA{period}, got {len(values)}")
    multiplier = 2 / (period + 1)
    ema = sum(values[:period]) / period
    for value in values[period:]:
        ema = (value - ema) * multiplier + ema
    return ema


def fetch_previous_daily_ohlc(token: str, ticker: str = PAIR, lookback_days: int = 20) -> OHLC:
    end_date = datetime.now(timezone.utc).date()
    start_date = end_date - timedelta(days=lookback_days)
    response = requests.get(
        TIINGO_REST_URL.format(ticker=ticker),
        params={"startDate": start_date.isoformat(), "endDate": end_date.isoformat(), "resampleFreq": "1day"},
        headers={"Authorization": f"Token {token}"},
        timeout=20,
    )
    if response.status_code != 200:
        raise RuntimeError(f"Tiingo daily REST HTTP {response.status_code}: {response.text[:300]}")
    rows = response.json()
    if not isinstance(rows, list) or not rows:
        raise RuntimeError(f"Tiingo daily REST returned no rows: {rows!r}")

    today = datetime.now(timezone.utc).date()

    # Log every row returned by Tiingo so we can diagnose bad data
    logging.info("Tiingo OHLC raw rows for %s (last %d days):", ticker.upper(), lookback_days)
    for row in rows:
        try:
            d = parse_iso(str(row.get("date", ""))).date()
            h = float(row.get("high", 0))
            l = float(row.get("low", 0))
            c = float(row.get("close", 0))
            logging.info("  %s  H=%.5f  L=%.5f  C=%.5f  range=%.5f  %s",
                         d.isoformat(), h, l, c, h - l,
                         "TODAY(skip)" if d >= today else "OK" if (h - l) > 0.00010 else "ZERO-RANGE(skip)")
        except Exception:
            logging.info("  (unparseable row: %s)", row)

    completed = []
    for row in rows:
        try:
            d = parse_iso(str(row.get("date", ""))).date()
            if d < today:
                completed.append((d, row))
        except Exception:
            continue
    if not completed:
        raise RuntimeError(
            f"Tiingo daily REST returned no completed trading days in the last {lookback_days} days "
            f"(today={today}). Cannot compute pivots from a partial candle."
        )

    # For forex pairs, a real trading day has at least 20 pips range (0.00200 for 5dp pairs).
    # For XAUUSD (gold), a real day has at least $0.50 range.
    # Use a relative minimum: 0.05% of the close price. This adapts to both.
    selected_date, selected_row = None, None
    for d, row in reversed(completed):
        h = float(row.get("high", 0))
        l = float(row.get("low", 0))
        c = float(row.get("close", 0)) or 1.0
        pct_range = (h - l) / c  # e.g. 0.005 = 0.5%
        if pct_range >= 0.0005:   # at least 0.05% range — rejects zero-range stubs
            selected_date, selected_row = d, row
            break
        logging.warning(
            "Skipping %s OHLC: range %.5f (%.4f%%) is below minimum – likely weekend/holiday stub "
            "(H=%.5f L=%.5f C=%.5f)",
            d.isoformat(), h - l, pct_range * 100, h, l, c,
        )

    # Fallback: if all completed rows were flat/zero-range, use the most recent completed row
    # and let the small-range warning from set_ohlc alert the operator.
    if selected_date is None:
        selected_date, selected_row = completed[-1]
        logging.warning(
            "No completed OHLC row with a valid range found in last %d days; "
            "falling back to %s. Pivot levels may be compressed.",
            lookback_days, selected_date.isoformat(),
        )

    return OHLC(
        date=selected_date.isoformat(),
        open=float(selected_row["open"]), high=float(selected_row["high"]),
        low=float(selected_row["low"]), close=float(selected_row["close"]),
    )


def fetch_hourly_ema_context(token: str, ticker: str = PAIR, lookback_days: int = 14, price: Optional[float] = None) -> EMAContext:
    end_date = datetime.now(timezone.utc).date() + timedelta(days=1)
    start_date = datetime.now(timezone.utc).date() - timedelta(days=lookback_days)
    response = requests.get(
        TIINGO_REST_URL.format(ticker=ticker),
        params={"startDate": start_date.isoformat(), "endDate": end_date.isoformat(), "resampleFreq": "1hour"},
        headers={"Authorization": f"Token {token}"},
        timeout=20,
    )
    if response.status_code != 200:
        raise RuntimeError(f"Tiingo hourly EMA REST HTTP {response.status_code}: {response.text[:300]}")
    rows = response.json()
    if not isinstance(rows, list) or len(rows) < 50:
        rows_repr = repr(rows) if not isinstance(rows, list) else len(rows)
        raise RuntimeError(f"Tiingo hourly EMA returned insufficient rows: {rows_repr}")

    now_utc = datetime.now(timezone.utc)
    cleaned = []
    for row in rows:
        try:
            dt = parse_iso(str(row.get("date", "")))
            if dt.tzinfo is None:
                dt = dt.replace(tzinfo=timezone.utc)
            if dt <= now_utc + timedelta(minutes=5):
                cleaned.append((dt, float(row["close"])))
        except Exception:
            continue
    cleaned.sort(key=lambda x: x[0])
    if len(cleaned) < 50:
        raise RuntimeError(f"Not enough valid hourly closes for EMA50: {len(cleaned)}")

    closes = [c for _, c in cleaned]
    last_dt, last_close = cleaned[-1]
    ema20 = calculate_ema(closes, 20)
    ema50 = calculate_ema(closes, 50)
    bias = "bullish" if ema20 > ema50 else "bearish" if ema20 < ema50 else "neutral"

    reference = float(price) if price is not None else float(last_close)
    if reference > ema20 and reference > ema50:
        position = "above_ema20_ema50"
    elif reference < ema20 and reference < ema50:
        position = "below_ema20_ema50"
    elif reference >= ema20 and reference < ema50:
        position = "between_above_ema20_below_ema50"
    elif reference < ema20 and reference >= ema50:
        position = "between_below_ema20_above_ema50"
    else:
        position = "mixed"

    return EMAContext(
        timeframe="1hour",
        ema20=round(ema20, 5),
        ema50=round(ema50, 5),
        last_close=round(last_close, 5),
        last_bar_time_utc=last_dt.isoformat().replace("+00:00", "Z"),
        bias=bias,
        price_position=position,
    )


def parse_tiingo_tick(message: str) -> Optional[Tick]:
    data = json.loads(message)
    mtype = data.get("messageType")
    if mtype == "H":
        return None
    if mtype == "I":
        logging.info("Subscription response: %s", json.dumps(data, separators=(",", ":")))
        return None
    if mtype != "A":
        logging.debug("Other Tiingo message: %s", data)
        return None
    payload = data.get("data", [])
    if not isinstance(payload, list) or len(payload) < 8:
        logging.debug("Unexpected Tiingo payload: %s", payload)
        return None
    # Tiingo FX WebSocket payload layout:
    # [0] messageType  [1] ticker  [2] date
    # [3] bidSize  [4] bidPrice  [5] midPrice  [6] askSize  [7] askPrice
    if str(payload[1]).lower() != PAIR:
        return None
    return Tick(ts_utc=str(payload[2]), bid=float(payload[4]), mid=float(payload[5]), ask=float(payload[7]))


def build_ema_pivot_context(cross_signal: str, state: Optional[Dict[str, Any]]) -> Dict[str, Any]:
    if not state or not state.get("pivots") or state.get("price") is None:
        return {
            "title_action": "EMA cross detected",
            "nearest_name": "--", "nearest_value": "--", "distance": "--", "price": "--",
            "pivot_comment": "Pivot context unavailable",
        }

    price = float(state["price"])
    pivots = state["pivots"]
    if cross_signal == "ema20_cross_above_ema50":
        levels = ["PP", "R1", "R2", "R3"]
        crossing_word, breaking_word = "Crossing / Testing", "Breaking Above"
    else:
        levels = ["PP", "S1", "S2", "S3"]
        crossing_word, breaking_word = "Crossing / Testing", "Breaking Below"

    nearest = min(levels, key=lambda lvl: abs(price - float(pivots[lvl])))
    nearest_value = float(pivots[nearest])
    distance = abs(price - nearest_value)
    tolerance = env_float("EMA_PIVOT_CROSS_TOLERANCE", 1.50, minimum=0.0)

    if distance <= tolerance:
        title_action = f"{crossing_word} {nearest}"
        comment = f"Price is very close to {nearest}"
    elif cross_signal == "ema20_cross_above_ema50":
        if price > nearest_value:
            title_action = f"{breaking_word} {nearest}"
            comment = f"Price is trading above {nearest}"
        else:
            title_action = f"Approaching {nearest}"
            comment = f"Price is still below {nearest}"
    else:
        if price < nearest_value:
            title_action = f"{breaking_word} {nearest}"
            comment = f"Price is trading below {nearest}"
        else:
            title_action = f"Approaching {nearest}"
            comment = f"Price is still above {nearest}"

    return {
        "title_action": title_action,
        "nearest_name": nearest,
        "nearest_value": round(nearest_value, 2),
        "distance": round(distance, 2),
        "price": round(price, 2),
        "pivot_comment": comment,
    }


def format_ema_cross_alert(cross_signal: str, ema: EMAContext, state: Optional[Dict[str, Any]] = None) -> str:
    ctx = build_ema_pivot_context(cross_signal, state)
    if cross_signal == "ema20_cross_above_ema50":
        title = f"📈 <b>{PAIR.upper()} H1 EMA Bullish Cross</b>"
        signal_text = "EMA20 crossed above EMA50"
    elif cross_signal == "ema20_cross_below_ema50":
        title = f"📉 <b>{PAIR.upper()} H1 EMA Bearish Cross</b>"
        signal_text = "EMA20 crossed below EMA50"
    else:
        title = f"⚠️ <b>{PAIR.upper()} H1 EMA Cross</b>"
        signal_text = cross_signal

    return (
        f"{title}\n"
        f"<b>{ctx['title_action']}</b>\n\n"
        f"<b>Signal:</b> {signal_text}\n"
        f"<b>Price:</b> {ctx['price']}\n"
        f"<b>Nearest Pivot:</b> {ctx['nearest_name']} {ctx['nearest_value']}\n"
        f"<b>Distance:</b> {ctx['distance']}\n"
        f"<b>Context:</b> {ctx['pivot_comment']}\n\n"
        f"<b>EMA20:</b> {ema.ema20}\n"
        f"<b>EMA50:</b> {ema.ema50}\n"
        f"<b>EMA Bias:</b> {ema.bias}\n"
        f"<b>Price Position:</b> {ema.price_position}\n\n"
        f"<b>Last H1 Close:</b> {ema.last_close}\n"
        f"<b>Last H1 Bar UTC:</b> {ema.last_bar_time_utc}"
    )


def format_pivot_alert(state: Dict[str, Any]) -> str:
    p = state["pivots"]
    s = state["session"]
    n = state["nearest_level"]
    ema = state.get("ema") or {}
    ema_line = ""
    if ema:
        ema_line = (
            f"\n<b>Hourly EMA20:</b> {ema.get('ema20')}\n"
            f"<b>Hourly EMA50:</b> {ema.get('ema50')}\n"
            f"<b>EMA Bias:</b> {ema.get('bias')} / {ema.get('price_position')}\n"
        )
    rejection = state.get("rejection_level", "")
    rejection_line = f"<b>Rejection Level:</b> {rejection}\n" if rejection else ""
    return (
        f"🚨 <b>{PAIR.upper()} Pivot Alert</b>\n\n"
        f"<b>State:</b> {state['state']}\n"
        f"<b>Level:</b> {state['level']}\n"
        f"{rejection_line}"
        f"<b>Price:</b> {state['price']}\n"
        f"<b>Bid:</b> {state['bid']}\n"
        f"<b>Ask:</b> {state['ask']}\n"
        f"<b>Spread:</b> {state['spread']}\n\n"
        f"<b>Nearest:</b> {n['name']} {n['value']} ({n['distance']} away, price {n['side']})\n\n"
        f"<b>PP:</b> {p['PP']}\n"
        f"<b>R1:</b> {p['R1']} | <b>R2:</b> {p['R2']} | <b>R3:</b> {p['R3']}\n"
        f"<b>S1:</b> {p['S1']} | <b>S2:</b> {p['S2']} | <b>S3:</b> {p['S3']}\n\n"
        f"<b>Session High:</b> {s['high']}\n"
        f"<b>Session Low:</b> {s['low']}\n"
        f"<b>Session:</b> {s['key']}\n"
        f"<b>Time UTC:</b> {state['timestamp_utc']}"
        f"{ema_line}"
    )


def atomic_write_json(path: Path, payload: Dict[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_suffix(path.suffix + ".tmp")
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(payload, f, indent=2, sort_keys=True)
        f.flush()
        os.fsync(f.fileno())
    os.replace(tmp, path)


def connect_and_stream(token: str, engine: PivotEngine, output: Path, snapshot_seconds: int, refresh_ohlc_seconds: int, refresh_ema_seconds: int) -> None:
    last_snapshot = 0.0
    last_ohlc_refresh = 0.0
    last_ema_refresh = 0.0
    startup_message_sent = False
    last_state: Optional[Dict[str, Any]] = None

    while not STOP:
        ws = None
        try:
            if time.time() - last_ohlc_refresh > refresh_ohlc_seconds or not engine.pivots:
                engine.set_ohlc(fetch_previous_daily_ohlc(token))
                last_ohlc_refresh = time.time()

            if time.time() - last_ema_refresh > refresh_ema_seconds or engine.ema_context is None:
                cross = engine.set_ema_context(fetch_hourly_ema_context(token))
                last_ema_refresh = time.time()
                if cross and engine.ema_context:
                    send_telegram_alert(format_ema_cross_alert(cross, engine.ema_context, last_state))

            if not startup_message_sent:
                send_startup_telegram_message()
                startup_message_sent = True

            logging.info("Connecting to %s", TIINGO_WS_URL)
            ws = create_connection(TIINGO_WS_URL, timeout=20)
            ws.send(json.dumps({
                "eventName": "subscribe",
                "authorization": token,
                "eventData": {"thresholdLevel": 5, "tickers": [PAIR]},
            }))
            logging.info("Subscribed to %s", PAIR.upper())

            while not STOP:
                try:
                    message = ws.recv()
                except WebSocketTimeoutException:
                    continue

                tick = parse_tiingo_tick(message)
                if tick is None:
                    continue

                engine.update_session(tick)
                state = engine.classify(tick)
                last_state = state
                now = time.time()

                if state.get("event"):
                    logging.warning(
                        "EVENT %s %s price=%.2f nearest=%s sessionH=%s sessionL=%s",
                        state["state"], state["level"], state["price"], state["nearest_level"]["name"],
                        state["session"]["high"], state["session"]["low"],
                    )
                    send_telegram_alert(format_pivot_alert(state))

                if now - last_snapshot >= snapshot_seconds or state.get("event"):
                    atomic_write_json(output, {
                        "generated_at_utc": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
                        "source": "tiingo",
                        "mode": "websocket",
                        "data": state,
                    })
                    if state["state"] == "no_pivots":
                        logging.info("%s state=no_pivots (pivots not yet loaded)", PAIR.upper())
                    else:
                        logging.info(
                            "%s price=%.2f state=%s level=%s PP=%.2f R1=%.2f S1=%.2f spread=%.2f EMA20=%s EMA50=%s bias=%s",
                            PAIR.upper(), state["price"], state["state"], state["level"],
                            state["pivots"]["PP"], state["pivots"]["R1"], state["pivots"]["S1"], state["spread"],
                            state.get("ema", {}).get("ema20") if state.get("ema") else None,
                            state.get("ema", {}).get("ema50") if state.get("ema") else None,
                            state.get("ema", {}).get("bias") if state.get("ema") else None,
                        )
                    last_snapshot = now

                if time.time() - last_ohlc_refresh > refresh_ohlc_seconds:
                    engine.set_ohlc(fetch_previous_daily_ohlc(token))
                    last_ohlc_refresh = time.time()

                if time.time() - last_ema_refresh > refresh_ema_seconds:
                    cross = engine.set_ema_context(fetch_hourly_ema_context(token, price=tick.mid))
                    last_ema_refresh = time.time()
                    if cross and engine.ema_context:
                        logging.warning("EMA CROSS %s EMA20=%.2f EMA50=%.2f bias=%s", cross, engine.ema_context.ema20, engine.ema_context.ema50, engine.ema_context.bias)
                        send_telegram_alert(format_ema_cross_alert(cross, engine.ema_context, state))

        except WebSocketConnectionClosedException:
            logging.warning("WebSocket closed; reconnecting in 5 seconds")
            time.sleep(5)
        except Exception as exc:
            logging.exception("Daemon error: %s; reconnecting in 15 seconds", exc)
            time.sleep(15)
        finally:
            try:
                if ws:
                    ws.close()
            except Exception:
                pass


def main() -> int:
    global STOP_REASON
    parser = argparse.ArgumentParser(description=f"{PAIR.upper()} Tiingo pivot daemon with Telegram and H1 EMA20/EMA50 alerts")
    parser.add_argument("--token", default=os.environ.get("TIINGO_TOKEN", "").strip(), help="Tiingo API token or TIINGO_TOKEN env var")
    parser.add_argument("--output", default=os.environ.get("PIVOT_OUTPUT_JSON", "./pivot.json"), help="Output JSON file")
    parser.add_argument("--log-level", default=os.environ.get("LOG_LEVEL", "INFO"), help="DEBUG, INFO, WARNING")
    args = parser.parse_args()

    logging.basicConfig(level=getattr(logging, args.log_level.upper(), logging.INFO), format="%(asctime)s %(levelname)s %(message)s")

    if not args.token:
        logging.error("Missing TIINGO_TOKEN. Set it in .env or pass --token.")
        return 2

    engine = PivotEngine(
        break_tol=env_float("PIVOT_BREAK_TOL", 0.05, minimum=0.0),
        balance_band=env_float("PIVOT_BALANCE_BAND", 0.15, minimum=0.0),
        accept_seconds=env_int("PIVOT_ACCEPT_SECONDS", 120, minimum=1),
        session_tz=os.environ.get("PIVOT_SESSION_TZ", "Asia/Kuala_Lumpur"),
        reset_hour=env_int("PIVOT_SESSION_RESET_HOUR", 6, minimum=0),
        alert_cooldown_seconds=env_int("PIVOT_ALERT_COOLDOWN_SECONDS", 300, minimum=0),
    )

    output = Path(args.output).expanduser().resolve()
    snapshot_seconds = env_int("PIVOT_SNAPSHOT_SECONDS", 10, minimum=1)
    refresh_ohlc_seconds = env_int("PIVOT_REFRESH_OHLC_SECONDS", 3600, minimum=60)
    refresh_ema_seconds = env_int("PIVOT_REFRESH_EMA_SECONDS", 900, minimum=60)

    logging.info(
        "Starting %s pivot daemon output=%s snapshot=%ss session_tz=%s telegram=%s ema_refresh=%ss",
        PAIR.upper(), output, snapshot_seconds, os.environ.get("PIVOT_SESSION_TZ", "Asia/Kuala_Lumpur"),
        "enabled" if telegram_enabled() else "disabled", refresh_ema_seconds,
    )

    exit_code = 0
    try:
        connect_and_stream(args.token, engine, output, snapshot_seconds, refresh_ohlc_seconds, refresh_ema_seconds)
    except Exception as exc:
        STOP_REASON = f"fatal crash: {exc}"
        exit_code = 1
        logging.exception("Fatal daemon error before shutdown: %s", exc)
        send_crash_telegram_message(exc)
    finally:
        logging.info("Stopped: %s", STOP_REASON)
        send_stop_telegram_message(STOP_REASON)

    return exit_code


if __name__ == "__main__":
    raise SystemExit(main())