"""
Ingress FS Telegram Bot
Author: Patrick Diepold
"""

import os
import logging
import requests
import io
import qrcode
from telegram import Update, ReplyKeyboardMarkup
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters
from dotenv import load_dotenv

load_dotenv()

TOKEN = os.getenv("TELEGRAM_TOKEN")
BACKEND_URL = "http://backend:8000" 
BASE_DOMAIN = "https://fs.padi.dev"

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    reply_keyboard = [['/checkin']]
    await update.message.reply_text(
        "Moin Patrick! Dein Ingress FS Bot ist bereit.\n\n"
        "1. Nutze /checkin für deinen persönlichen QR-Code.\n"
        "2. Poste deine Ingress Stats (TSV) hier rein, um dich zu registrieren.",
        reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=False, resize_keyboard=True)
    )

async def handle_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
    raw_text = update.message.text
    
    if "\t" not in raw_text:
        await update.message.reply_text("Das sieht nicht nach Ingress TSV-Daten aus. Bitte kopiere die Daten direkt aus Ingress.")
        return

    try:
        response = requests.post(f"{BACKEND_URL}/submit_stats", json={
            "user_id": update.effective_user.id,
            "username": update.effective_user.username or update.effective_user.first_name,
            "raw_data": raw_text
        })

        if response.status_code == 200:
            msg = response.json().get("message", "Stats empfangen!")
            await update.message.reply_text(f"✅ {msg}")
        else:
            await update.message.reply_text("❌ Fehler beim Speichern im Backend.")
    except Exception as e:
        await update.message.reply_text(f"❌ Verbindung zum Backend fehlgeschlagen.")

async def checkin(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_id = update.effective_user.id
    verify_url = f"{BASE_DOMAIN}/verify/{user_id}"
    
    # QR Code Bild generieren
    qr = qrcode.QRCode(version=1, box_size=10, border=5)
    qr.add_data(verify_url)
    qr.make(fit=True)
    img = qr.make_image(fill_color="black", back_color="white")
    
    # Bild in den Speicher (RAM) schreiben statt auf die Festplatte
    bio = io.BytesIO()
    bio.name = 'checkin_qr.png'
    img.save(bio, 'PNG')
    bio.seek(0)
    
    await context.bot.send_photo(
        chat_id=update.effective_chat.id,
        photo=bio,
        caption=f"Dein Check-In QR-Code.\n\nZeige diesen einem Admin zum Scannen.\n(Link: {verify_url})"
    )

if __name__ == '__main__':
    application = ApplicationBuilder().token(TOKEN).build()
    application.add_handler(CommandHandler('start', start))
    application.add_handler(CommandHandler('checkin', checkin))
    application.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), handle_stats))
    application.run_polling()