from concurrent.futures import ThreadPoolExecutor, as_completed

from apify_client import ApifyClient


PROFILE_ACTOR_ID = "LpVuK3Zozwuipa5bp"
COMMENTS_REACTIONS_ACTOR_ID = "FIDWZpFEciBahSs2T"

def call_profile_actor(apify_token, linkedin_urls):
    client = ApifyClient(apify_token)
    run_input = {
        "profileScraperMode": "Profile details no email ($4 per 1k)",
        "queries": linkedin_urls,
    }
    return client.actor(PROFILE_ACTOR_ID).call(
        run_input=run_input,
        memory_mbytes=512,
        timeout_secs=2000,
    )


def call_comments_reactions_actor(apify_token, linkedin_urls):
    client = ApifyClient(apify_token)
    run_input = {
        "scrapeType": "both",
        "profiles": linkedin_urls,
        "commentsLimit": 1,
        "reactionsLimit": 1,
        "postedLimit": "any",
    }
    return client.actor(COMMENTS_REACTIONS_ACTOR_ID).call(
        run_input=run_input,
        memory_mbytes=256,
        timeout_secs=2000,
    )


def dataset_items(client, run):
    dataset_id = run.get("defaultDatasetId")
    if not dataset_id:
        return []
    return list(client.dataset(dataset_id).iterate_items())


def fetch_linkedin_data(apify_token, linkedin_urls):
    calls = {
        "profile": lambda: call_profile_actor(apify_token, linkedin_urls),
        "comments/reactions": lambda: call_comments_reactions_actor(apify_token, linkedin_urls),
    }
    results = {}

    with ThreadPoolExecutor(max_workers=2) as executor:
        futures = {executor.submit(call): label for label, call in calls.items()}
        for future in as_completed(futures):
            label = futures[future]
            results[label] = future.result()

    client = ApifyClient(apify_token)
    return {
        "profile": dataset_items(client, results["profile"]),
        "activities": dataset_items(client, results["comments/reactions"]),
    }
