import tweepy
import config

def post_to_x(text, image_path):
    print(f"\n🚀 [X_Handler] Request received.")
    try:
        # 1. Connect to v1.1 API (Required for Media Uploads)
        auth = tweepy.OAuth1UserHandler(
            config.X_API_KEY, config.X_API_SECRET,
            config.X_ACCESS_TOKEN, config.X_ACCESS_SECRET
        )
        api = tweepy.API(auth)

        # 2. Connect to v2 Client (Required for Tweeting)
        client = tweepy.Client(
            consumer_key=config.X_API_KEY,
            consumer_secret=config.X_API_SECRET,
            access_token=config.X_ACCESS_TOKEN,
            access_token_secret=config.X_ACCESS_SECRET
        )

        # 3. Upload the Image
        print(f"   🐦 Uploading image to X...")
        media = api.media_upload(filename=image_path)

        # 4. Enforce X's 280 Character Limit
        tweet_text = text
        if len(tweet_text) > 280:
            print("   ✂️ Text too long for X! Truncating to 280 characters...")
            tweet_text = tweet_text[:277] + "..."

        # 5. Publish the Tweet with the attached Image
        print("   🐦 Publishing Tweet...")
        response = client.create_tweet(text=tweet_text, media_ids=[media.media_id])
        
        print(f"   🎉 TWEET PUBLISHED SUCCESSFULLY! ID: {response.data['id']}")
        return True
        
    except Exception as e:
        print(f"   ❌ X/Twitter API Error: {e}")
        return False
