"""
Telegram alert sender.

Uses the Bot API directly (no library needed).
All messages are sent to the configured TELEGRAM_CHAT_ID.

Setup:
  1. Message @BotFather on Telegram → /newbot → copy the token
  2. Send any message to your bot, then visit:
       https://api.telegram.org/bot<TOKEN>/getUpdates
     to find your chat_id
  3. Set TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID in config.py
"""
import logging
import requests

logger = logging.getLogger(__name__)

_API = 'https://api.telegram.org/bot{token}/sendMessage'


def send_message(token: str, chat_id: str, text: str, parse_mode: str = 'HTML') -> bool:
    """Send a Telegram message. Returns True on success."""
    if not token or not chat_id:
        logger.debug('[Telegram] not configured — skipping alert')
        return False
    try:
        resp = requests.post(
            _API.format(token=token),
            json={'chat_id': chat_id, 'text': text, 'parse_mode': parse_mode},
            timeout=10,
        )
        if resp.status_code == 200:
            return True
        logger.warning(f'[Telegram] HTTP {resp.status_code}: {resp.text[:200]}')
        return False
    except Exception as ex:
        logger.warning(f'[Telegram] send failed: {ex}')
        return False


def arb_found_alert(token: str, chat_id: str, opp: dict, mode: str) -> bool:
    """Send an alert when a new arb opportunity is detected."""
    label    = '🔴 LIVE' if mode == 'live' else '⚪ PRE-MATCH'
    sport    = opp.get('sport', '').title()
    league   = opp.get('league', '')
    market   = opp.get('market', '')
    profit   = opp.get('arb_percentage', 0)

    outcomes_text = ''
    for o in opp.get('outcomes', []):
        outcomes_text += f'  • {o["bookmaker"]}  {o["outcome"]}  @ <b>{o["odds"]}</b>\n'

    event_name = opp.get('event_name', opp.get('home_team', '') + ' vs ' + opp.get('away_team', ''))
    text = (
        f'{label}  ARB DETECTED  💰 <b>{profit:.2f}%</b>\n\n'
        f'<b>{event_name}</b>\n'
        f'🏆 {league}\n'
        f'⚽ {sport}  |  {market}\n\n'
        f'{outcomes_text}\n'
        f'⌨️ Enter stake in the terminal to place.'
    )
    return send_message(token, chat_id, text)


def bet_placed_alert(
    token:      str,
    chat_id:    str,
    opp:        dict,
    legs:       list,    # list of LegStake
    results:    list,    # list of BetResult
    mode:       str,
) -> bool:
    """Send confirmation after bets are placed (or attempted)."""
    all_ok = all(r.success for r in results)
    any_ok = any(r.success for r in results)

    if all_ok:
        status_line = '✅ ALL BETS PLACED'
    elif any_ok:
        status_line = '⚠️ PARTIAL PLACEMENT — CHECK MANUALLY'
    else:
        status_line = '❌ PLACEMENT FAILED'

    label      = '🔴 LIVE' if mode == 'live' else '⚪ PRE-MATCH'
    event_name = opp.get('event_name', opp.get('home_team', '') + ' vs ' + opp.get('away_team', ''))
    market     = opp.get('market', '')

    legs_text = ''
    for leg, result in zip(legs, results):
        icon = '✅' if result.success else '❌'
        legs_text += (
            f'{icon} <b>{leg.bookmaker}</b>  {leg.outcome}  @ {leg.odds}\n'
            f'   Stake: ₦{leg.stake:,.0f}  |  Returns: ₦{leg.return_if_win:,.0f}\n'
        )
        if result.success and result.bet_id:
            legs_text += f'   Bet ID: <code>{result.bet_id}</code>\n'
        elif not result.success:
            legs_text += f'   Error: {result.message}\n'

    total_stake = sum(l.stake for l in legs)
    exp_profit  = legs[0].return_if_win - total_stake if legs else 0  # approximate

    text = (
        f'{label}  {status_line}\n\n'
        f'<b>{event_name}</b>  |  {market}\n\n'
        f'{legs_text}\n'
        f'💵 Total staked:  ₦{total_stake:,.0f}\n'
    )
    if all_ok:
        text += f'💰 Guaranteed profit:  ₦{exp_profit:,.2f}'

    return send_message(token, chat_id, text)


def error_alert(token: str, chat_id: str, message: str) -> bool:
    """Send a plain error/warning alert."""
    return send_message(token, chat_id, f'⚠️ ArbBot: {message}')
