import logging
from telegram import Update
from telegram.ext import Application, MessageHandler, filters, ContextTypes
import tweepy

# ==================== تنظیمات (اینجا پر کن) ====================
TELEGRAM_TOKEN="8639675666:AAFaj05sMNFJTX2DXJSG8m6RIaGkYTGDf6w"
TWITTER_API_KEY="ovkM1GQcFzm3hnJB4eFriqYqM"
TWITTER_API_SECRET="Xe6ad3YZqkAqWE4NvabGROBhCPQxwTyHI5BathxIbLFJOrXKBU"
TWITTER_ACCESS_TOKEN="1426494022005182465-aEhooT18tK1t1O0xSQaTbJ73VQlgAk"
TWITTER_ACCESS_TOKEN_SECRET="qz8ODpmZe99ESu0fkrWY3ot2mb5RrFwt1auzwpNrDxdmR"
CHANNEL_USERNAME="@TwitterCBMJustTest"
# ==============================================================

# تنظیمات لاگ
logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    level=logging.INFO
)
logger = logging.getLogger(__name__)

# کلاینت توییتر
twitter_client = tweepy.Client(
    consumer_key=TWITTER_API_KEY,
    consumer_secret=TWITTER_API_SECRET,
    access_token=TWITTER_ACCESS_TOKEN,
    access_token_secret=TWITTER_ACCESS_TOKEN_SECRET
)

async def handle_channel_post(update: Update, context: ContextTypes.DEFAULT_TYPE):
    message = update.channel_post
    if not message:
        return

    chat_username = message.chat.username
    if not chat_username:
        logger.warning("این کانال یوزرنیم عمومی نداره")
        return

    expected_username = CHANNEL_USERNAME.lstrip("@").lower()
    if chat_username.lower() != expected_username:
        logger.info(f"پیام از کانال دیگری اومد: @{chat_username}")
        return

    text = message.text or message.caption or ""

    if not text.strip():
        logger.info("پیام بدون متن رد شد")
        return

    # محدودیت کاراکتر X
    if len(text) > 280:
        text = text[:277] + "..."

    try:
        response = twitter_client.create_tweet(text=text)
        tweet_id = response.data["id"]
        logger.info(f"✅ پست شد در X | Tweet ID: {tweet_id}")
        print(f"✅ پست شد: {text[:50]}...")
    except Exception as e:
        logger.error(f"❌ خطا در پست کردن به X: {e}")
        print(f"❌ خطا در پست کردن به X: {e}")

def main():
    application = Application.builder().token(TELEGRAM_TOKEN).build()

    application.add_handler(
        MessageHandler(filters.UpdateType.CHANNEL_POST, handle_channel_post)
    )

    print("🤖 ربات شروع به کار کرد...")
    print(f"در حال گوش دادن به کانال: {CHANNEL_USERNAME}")
    application.run_polling(allowed_updates=Update.ALL_TYPES)

if __name__ == "__main__":
    main()