#!/usr/bin/env python3
"""
WatiFinance_bot — Long polling
Token: 8969609443:AAHncPkaaeTsdBmGI3Ci0fEMfxQamsVR6zM
Username: @WatiFinance_bot
"""

import requests
import time
import logging
import json
import os

BOT_TOKEN = "8969609443:AAHncPkaaeTsdBmGI3Ci0fEMfxQamsVR6zM"
API_URL = f"https://api.telegram.org/bot{BOT_TOKEN}"
OFFSET_FILE = "/tmp/wati_finance_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/wati_finance_bot.log")
    ]
)
log = logging.getLogger("wati_finance")


def send_message(chat_id, text, parse_mode="HTML"):
    try:
        r = requests.post(f"{API_URL}/sendMessage", json={
            "chat_id": chat_id,
            "text": text,
            "parse_mode": parse_mode
        }, 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", "callback_query"]}
    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"[MSG] @{username}: {text[:200]}")

    if text == "/start":
        send_message(chat_id,
            "👋 Halo! Saya <b>WatiFinance</b> — asisten keuangan virtual.\n"
            "Siap bantu urusan finansial dan pembukuan ringan 💰"
        )
    elif text == "/help":
        send_message(chat_id,
            "📋 <b>Perintah WatiFinance:</b>\n\n"
            "/start — Mulai\n"
            "/help — Bantuan"
        )
    else:
        # Forward ke Bos / balas default
        send_message(chat_id,
            f"Halo @{username}! Pesanmu udah diterima. "
            "Tim keuangan akan merespons segera ya 💪"
        )


def handle_callback(cb):
    """Handle tombol inline"""
    chat_id = cb.get("message", {}).get("chat", {}).get("id")
    data = cb.get("data", "")
    cb_id = cb.get("id")
    
    log.info(f"[CB] data={data} chat={chat_id}")
    
    # Acknowledge callback
    requests.post(f"{API_URL}/answerCallbackQuery", json={
        "callback_query_id": cb_id,
    }, timeout=5)


def main():
    log.info("💰 WatiFinance_bot polling started!")
    
    # Notifikasi Bos udah bangun
    bot_info = requests.get(f"{API_URL}/getMe").json()
    log.info(f"🤖 Bot: @{bot_info['result']['username']} (id: {bot_info['result']['id']})")
    
    # 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)
                
                cb = update.get("callback_query")
                if cb:
                    handle_callback(cb)
                
                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()
