import logging
import json
import os
from telegram import Update
from telegram.ext import ApplicationBuilder, ContextTypes, MessageHandler, filters, CommandHandler

# --- CONFIGURAZIONE ---
TOKEN = "8800959719:AAFlsOPVyR2TkXbMtusTeDX2rT1x7atFIbw"
MY_CHAT_ID = 1640434336
CONFIG_FILE = "bot_config.json"

# Stato globale
config = {"target_group_id": None}

# Logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)
logger = logging.getLogger(__name__)

def save_config():
    with open(CONFIG_FILE, "w") as f:
        json.dump(config, f)

def load_config():
    global config
    if os.path.exists(CONFIG_FILE):
        with open(CONFIG_FILE, "r") as f:
            config = json.load(f)

async def start_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_id = update.effective_user.id
    if user_id == MY_CHAT_ID:
        await update.message.reply_text(
            "🤖 Sniper Bot Attivo (Vocali Esclusi)!\n"
            "Comandi:\n"
            "/setid [ID] - Imposta l'ID manualmente\n"
            "/status - Controlla configurazione"
        )

async def status_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.effective_user.id == MY_CHAT_ID:
        target = config.get("target_group_id")
        status = f"🎯 Target attuale: `{target}`" if target else "❌ Nessun target impostato."
        await update.message.reply_text(status, parse_mode='Markdown')

async def setid_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.effective_user.id == MY_CHAT_ID:
        if not context.args:
            await update.message.reply_text("Sintassi: `/setid -100xxxxxxxxxx`", parse_mode='Markdown')
            return
        try:
            new_id = int(context.args[0])
            config["target_group_id"] = new_id
            save_config()
            await update.message.reply_text(f"✅ ID impostato a: `{new_id}`", parse_mode='Markdown')
        except ValueError:
            await update.message.reply_text("Errore: L'ID deve essere un numero.")

async def handle_everything(update: Update, context: ContextTypes.DEFAULT_TYPE):
    global config
    
    # Filtro per il gruppo target
    if update.effective_chat.id != config.get("target_group_id"):
        return

    # Inoltro Chiamate
    if update.message and update.message.video_chat_started:
        await context.bot.send_message(MY_CHAT_ID, f"⚠️ CHIAMATA INIZIATA in: {update.effective_chat.title}")
        return

    # Gestione Media
    if not update.message:
        return

    user_name = update.message.from_user.first_name if update.message.from_user else "Anonimo"
    
    try:
        # Foto
        if update.message.photo:
            await context.bot.send_photo(MY_CHAT_ID, update.message.photo[-1].file_id, caption=f"📸 Foto da {user_name}")
        
        # Video
        elif update.message.video:
            await context.bot.send_video(MY_CHAT_ID, update.message.video.file_id, caption=f"🎥 Video da {user_name}")
        
        # GIF
        elif update.message.animation:
            await context.bot.send_animation(MY_CHAT_ID, update.message.animation.file_id, caption=f"🎞️ GIF da {user_name}")
        
        # Documenti
        elif update.message.document:
            await context.bot.send_document(MY_CHAT_ID, update.message.document.file_id, caption=f"📄 File da {user_name}")
        
        # VIDEO MESSAGGI (Tondi)
        elif update.message.video_note:
            await context.bot.send_video_note(MY_CHAT_ID, update.message.video_note.file_id)
            
        # AUDIO (File musicali)
        elif update.message.audio:
            await context.bot.send_audio(MY_CHAT_ID, update.message.audio.file_id, caption=f"🎵 Audio da {user_name}")

        # NOTA: I messaggi vocali (voice) sono stati rimossi volontariamente.

    except Exception as e:
        logger.error(f"Errore durante l'inoltro media: {e}")

def main():
    load_config()
    application = ApplicationBuilder().token(TOKEN).build()

    application.add_handler(CommandHandler("start", start_cmd))
    application.add_handler(CommandHandler("status", status_cmd))
    application.add_handler(CommandHandler("setid", setid_cmd))
    
    # Handler per tutti i messaggi (escludendo esplicitamente i vocali tramite filtro)
    application.add_handler(MessageHandler(filters.ALL & ~filters.COMMAND & ~filters.VOICE, handle_everything))

    logger.info("Bot Sniper (No Vocali) avviato...")
    application.run_polling()

if __name__ == '__main__':
    main()
