#!/usr/bin/env python3
"""Channel-agnostic messenger bot with long polling (lesson AUT-203-L04). Standard library only.

Works with any Telegram-style bot API: the Barg Sabz mock (default), Bale, or Telegram — only by configuration.
  BOT_API_BASE   http://127.0.0.1:8787 (mock) | https://tapi.bale.ai | https://api.telegram.org
  BOT_TOKEN      the bot token from the platform's bot father (env only; never in code). Mock accepts any value.
  ORDERS_API_*   mock orders API (see AUT-201) for order status replies

Rules it demonstrates: offset saved after handling (no reprocessing), skip non-text updates, reply length cap,
no message text in logs, untrusted user text never becomes an instruction.

    python poll_bot.py --once       # one polling round, then exit (good for testing)
    python poll_bot.py              # keep polling (Ctrl+C to stop)
"""
import argparse
import json
import os
import re
import sys
import time
import urllib.error
import urllib.request

BASE = os.environ.get("BOT_API_BASE", "http://127.0.0.1:8787").rstrip("/")
TOKEN = os.environ.get("BOT_TOKEN", "mock-token")
ORDERS = os.environ.get("ORDERS_API_BASE_URL", "http://127.0.0.1:8787")
ORDERS_TOKEN = os.environ.get("ORDERS_API_TOKEN", "local-demo-token")
OFFSET_FILE = os.environ.get("BOT_OFFSET_FILE", "bot_offset.txt")
MAX_REPLY = 4000  # both Telegram and Bale cap text messages at 4096 characters
STATUS_FA = {"shipped": "ارسال شده", "processing": "در حال آماده‌سازی", "delivered": "تحویل شده", "cancelled": "لغو شده"}


def api(method, payload=None, query=""):
    url = f"{BASE}/bot{TOKEN}/{method}{query}"
    data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
    req = urllib.request.Request(url, data=data, method="POST" if data else "GET",
                                 headers={"Content-Type": "application/json"} if data else {})
    with urllib.request.urlopen(req, timeout=35) as r:
        return json.load(r)


def order_status(order_id):
    req = urllib.request.Request(f"{ORDERS}/orders/{order_id}", headers={"Authorization": f"Bearer {ORDERS_TOKEN}"})
    try:
        with urllib.request.urlopen(req, timeout=10) as r:
            return json.load(r).get("status")
    except urllib.error.HTTPError as e:
        return None if e.code == 404 else "error"


def reply_for(text):
    """Deterministic replies; a model step (lesson AUT-203-L01) could classify here instead.
    The text is data: we only look for an order id pattern, we never execute what it says."""
    m = re.search(r"BS-\d{4}", text)
    if m:
        st = order_status(m.group(0))
        if st == "error":
            return "الان به سامانه سفارش دسترسی نداریم؛ همکاران ما پیگیری می‌کنند."
        if st is None:
            return f"سفارشی با شماره {m.group(0)} پیدا نشد. لطفاً شماره را بررسی کن."
        return f"وضعیت سفارش {m.group(0)}: {STATUS_FA.get(st, st)}."
    return "پیامت ثبت شد. برای پیگیری سفارش، شماره سفارش (مثل BS-1001) را بفرست."


def load_offset():
    try:
        return int(open(OFFSET_FILE).read().strip())
    except (OSError, ValueError):
        return 0


def save_offset(n):
    with open(OFFSET_FILE, "w") as f:
        f.write(str(n))


def poll_once():
    offset = load_offset()
    res = api("getUpdates", query=f"?offset={offset}&timeout=0")
    for upd in res.get("result", []):
        uid = upd["update_id"]
        msg = upd.get("message") or {}
        chat_id = (msg.get("chat") or {}).get("id")
        text = msg.get("text")
        if chat_id is None or not text:
            print(f"update {uid}: skipped (no text)")
        else:
            out = reply_for(text)[:MAX_REPLY]
            api("sendMessage", {"chat_id": chat_id, "text": out})
            print(f"update {uid}: replied to chat {chat_id}")  # no message text in logs
        save_offset(uid + 1)  # only after handling: a crash re-delivers, never skips


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--once", action="store_true")
    once = ap.parse_args().once
    while True:
        try:
            poll_once()
        except urllib.error.HTTPError as e:
            print(f"bot API error {e.code}; stopping" if e.code in (401, 403, 404) else f"bot API error {e.code}; retrying", file=sys.stderr)
            if e.code in (401, 403, 404):
                sys.exit(2)
        except (urllib.error.URLError, TimeoutError) as e:
            print(f"network error {e.__class__.__name__}; retrying", file=sys.stderr)
        if once:
            break
        time.sleep(2)
