from concurrent.futures import ThreadPoolExecutor
from google.oauth2.service_account import Credentials
import gspread
import os
import requests
import tempfile
from services.firebase.firestore_service import FirestoreService
from services.firebase.firebase_storage_service import FirebaseStorageService
from services.instagram.public_instagram_scraper import PublicInstagramScraper
from environment import Environment

def fetch_instagram_data(instagram_handle):
    public_instagram_scraper = PublicInstagramScraper()
    instagram_data, status_code = public_instagram_scraper.get_user_profile(instagram_handle)
    return instagram_data

def upload_profile_pic(profile_pic_url, instagram_handle):
    response = requests.get(profile_pic_url)
    if response.status_code == 200:
        with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as temp_file:
            temp_file.write(response.content)
            temp_file_path = temp_file.name

        destination_path = f"Influencer-ProfilePics/{instagram_handle}"
        storage_url = FirebaseStorageService.upload_file_to_storage(temp_file_path, destination_path)
        
        os.unlink(temp_file_path)  # Delete the temporary file
        return storage_url
    return None 

def process_record(record):
    instagram_handle = record.get('Instagram Handle', '').strip()
    tiktok_handle = record.get('TikTok Handle', '').strip()
    first_name = record.get('First Name', '').strip()
    last_name = record.get('Last Name', '').strip()
    city = record.get('City', '').strip()
    state = record.get('State', '').split(',')[0].strip()
    email_address = record.get('Email Address', '').strip()
    featured = record.get('Featured', '').lower().strip() == 'yes'
    
    print("processing: ", instagram_handle)
    if instagram_handle:
        instagram_data = fetch_instagram_data(instagram_handle)
        if instagram_data:
            profile_pic_url = instagram_data.get("profile_pic_url", "").strip()
            storage_url = upload_profile_pic(profile_pic_url, instagram_handle) if profile_pic_url else None
            influencer_data = {
                'instagramHandle': instagram_handle,
                'tiktokHandle': tiktok_handle,
                'firstName': first_name,
                'lastName': last_name,
                'profile_pic_url': storage_url,
                'city': city,
                'state': state,
                'email_address': email_address,
                'featured': featured,
                'instagramId': instagram_data.get("pk", "").strip(),
                'follower_count': instagram_data.get("follower_count", "")
            }
            FirestoreService.update_influencer_data(influencer_data)
    else:
        print("Instagram handle missing")

def refresh_influencer_data():

    scopes = [
        'https://www.googleapis.com/auth/spreadsheets',
        'https://www.googleapis.com/auth/drive'
    ]

    credentials = Credentials.from_service_account_file(
        os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', Environment.gcloud_creds_filename)),
        scopes=scopes
    )

    gc = gspread.authorize(credentials)
    spreadsheet = gc.open_by_url('https://docs.google.com/spreadsheets/d/1WFgxM_55ltuMzQvhByiBUSJB5F97-_eDzDq8RGBHYQo/edit?gid=0#gid=0')
    
    
    expected_headers = [
        'Instagram Handle',
        'TikTok Handle',
        'First Name',
        'Last Name',
        'IG Profile Link',
        'City',
        'State',
        'Email Address',
        'Featured'
    ]

    all_records = []
    for worksheet in spreadsheet.worksheets():
        print(f"Processing Worksheet: {worksheet.title}")
        records = worksheet.get_all_records(expected_headers=expected_headers)
        all_records.extend(records)

    
    
    # Using ThreadPoolExecutor for concurrent processing
    with ThreadPoolExecutor(max_workers=10) as executor:
        executor.map(process_record, all_records)

    print("Data successfully transferred to Firebase!")
    print(len(all_records))
