#!/usr/bin/env python3
"""
BambangThinkTank_bot — Long polling
Token: 8754205941:AAHFcR64BaBbmVmlIYNDPrzMuuDT5ifhtuo
"""

import requests
import time
import logging
import json
import os

BOT_TOKEN = "8754205941:AAHFcR64BaBbmVmlIYNDPrzMuuDT5ifhtuo"
API_URL = f"https://api.telegram.org/bot{BOT_TOKEN}"
OFFSET_FILE = "/tmp/bambang_bot_offset.txt"

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler("/home/mantapman/.hermes/profiles/atun/workspace/bambang_bot.log")
    ]
)
log = logging.getLogger("bambang")


def send_message(chat_id, text):
    try:
        r = requests.post(f"{API_URL}/sendMessage", json={
            "chat_id": chat_id,
            "text": text,
            "parse_mode": "HTML"
        }, timeout=10)
        if r.status_code == 200:
            return True
        else:
            log.error(f"Send failed: {r.status_code} {r.text[:200]}")
    except Exception as e:
        log.error(f"Send error: {e}")
    return False


def get_updates(offset=None):
    params = {"timeout": 30, "allowed_updates": ["message"]}
    if offset:
        params["offset"] = offset
    try:
        r = requests.get(f"{API_URL}/getUpdates", params=params, timeout=35)
        if r.status_code == 200:
            return r.json().get("result", [])
        else:
            log.error(f"getUpdates failed: {r.status_code}")
    except Exception as e:
        log.error(f"getUpdates error: {e}")
    return []


def handle_message(msg):
    chat_id = msg.get("chat", {}).get("id")
    text = msg.get("text", "")
    username = msg.get("from", {}).get("username", "unknown")
    
    log.info(f"💬 @{username}: {text[:150]}")

    # Auto reply sederhana
    if text == "/start":
        send_message(chat_id, 
            "Halo! Saya Bambang, asisten virtual Bos Uky.\n"
            "Ada yang bisa saya bantu? 🚀"
        )
    elif text == "/help":
        send_message(chat_id,
            "Perintah yang tersedia:\n"
            "/start — Mulai\n"
            "/help — Bantuan"
        )
    else:
        # Forward notif
        send_message(chat_id,
            f"Hai @{username}! Pesanmu udah diterima. Nanti Wati (asisten utama) yang bakal bales lebih lengkap ya 😊"
        )


def main():
    log.info("🤖 BambangThinkTank_bot polling started!")
    
    # Notifikasi Bos
    send_message(85049143, "🤖 @BambangThinkTank_bot udah bangun dan siap!")
    
    # Baca offset terakhir
    offset = None
    if os.path.exists(OFFSET_FILE):
        with open(OFFSET_FILE) as f:
            try:
                offset = int(f.read().strip())
            except:
                pass
    
    while True:
        try:
            updates = get_updates(offset)
            for update in updates:
                update_id = update.get("update_id")
                if offset and update_id < offset:
                    continue
                
                msg = update.get("message")
                if msg:
                    handle_message(msg)
                
                offset = update_id + 1
                with open(OFFSET_FILE, "w") as f:
                    f.write(str(offset))
            
            time.sleep(1)
        except KeyboardInterrupt:
            log.info("Bot stopped")
            break
        except Exception as e:
            log.error(f"Loop error: {e}", exc_info=True)
            time.sleep(5)


if __name__ == "__main__":
    main()
