import os

from dotenv import load_dotenv
from services.firebase.firestore_service import FirestoreService
from services.scheduling.cloud_queue_service import CloudQueueService

# NOTE: The private Instagram scraper is currently out of commission and needs updating before re-enabling.

class PrivateInstagramScraper:
    load_dotenv()
    def __init__(self):
        self.android_automation_server_api_key = os.environ.get("ANDROID_AUTOMATION_SERVER_API_KEY")
        self.cloud_queue_service = CloudQueueService()

    # Follows the user by user_id
    # User id is the unique identifier for each user and can be extracted using user_to_follow.pk
    def follow_user(self, username, server_name):
        
        self.cloud_queue_service.schedule_task(server_name, {"function": "follow_instagram_user", "username": username})
        # Check if request was successful
        
        res = {"message": "The bot *attempted* to follow the user. This message does not guarantee that the request was sent or that the user accepts the request."} # TODO: Make this message more accurate. Does not actually check if the bot was successful.
        print(res)
        return res
    
    def verify_instagram_story(self, username, required_tagged_username, bot_username, phone_number, offer_id, client_id, location_id):
        bots = FirestoreService.get_instagram_bots()

        bot = next((bot.to_dict() for bot in bots if bot.to_dict()["instagramHandle"] == bot_username), None)

        if bot is None:
            raise Exception("Bot not found")
        
        # Check if bot active. If false, throw an error
        if bot["active"] == False:
            raise Exception("Assigned bot is not active")
        
        # Make request to proxy server to verify story
        server_name = bot["serverName"]
        self.cloud_queue_service.schedule_task(server_name, {"function": "verify_instagram_stories", "username": username, "required_tagged_username": required_tagged_username, "phone_number": phone_number, "offer_id": offer_id, "client_id": client_id, "location_id": location_id})
        return {"task_sent": True}
        
        
