from datetime import datetime
from uuid import uuid4
import funcs
import config
import cv2
import os

directory = 'storysaver'

def UploadMedia(media):
    platform = 'Instagram'
    media_id = media['media_id']
    username = media['username']
    timestamp = media['timestamp']
    user_id = media['user_id']
    filepath = media['filepath']
    highlight_id = media['highlight_id']
    file_size = os.path.getsize(filepath)
    thumbnail_url = None
    phash = None
    
    if media_id and int(media_id) in existing_files:
        print('Duplicate file detected. Removing...')
        os.remove(filepath)
        return True
        
    filename = os.path.basename(filepath)
    file_extension = os.path.splitext(filename)[1].lower()

    media_type = funcs.get_media_type(filename)
    if not media_type:
        print(f'Error determining media type for {filename}. Skipping...')
        return False

    post_type = funcs.determine_post_type(filepath)
    if not post_type:
        print(f'Error determining post type for {filename}. Skipping...')
        return False

    file_hash = funcs.calculate_file_hash(filepath)

    post_date = datetime.fromtimestamp(int(timestamp)) if timestamp else datetime.now()

    width, height = funcs.get_media_dimensions(filepath)
    
    duration = funcs.get_video_duration(filepath)

    if media_type == 'image':
        phash = funcs.generate_phash(filepath)
    elif media_type == 'video':
        try:
            thumb_path = generate_thumbnail(filepath)
            obj_storage.PutFile(thumb_path, f'thumbnails/{file_hash}.jpg') # this might be a problem in case of duplicate hashes
            thumbnail_url = f"https://storysave.b-cdn.net/thumbnails/{file_hash}.jpg"
            phash = funcs.generate_phash(thumb_path)
            os.remove(thumb_path)
        except Exception as e:
            print(f'Error generating thumbnail: {e}. Skipping...')
            return False

    newFilename = f'{media_id}{file_extension}'
    server_path = f'media/{post_type}/{username}/{newFilename}'

    file_url = f"https://storysave.b-cdn.net/{server_path}"

    obj_storage.PutFile(filepath, server_path) # slow as fuck

    if highlight_id:
        newCursor.execute("INSERT IGNORE INTO highlights (highlight_id, user_id, media_id) VALUES (%s, %s, %s)", (highlight_id, user_id, media_id))
        newDB.commit()
        print(f'[{newCursor.rowcount}] added highlight {highlight_id} to user {user_id}')

    post_type = 'story' if post_type == 'stories' else 'post'
    query = "INSERT IGNORE INTO media (username, media_type, media_url, width, height, media_id, post_type, date, user_id, hash, filename, duration, thumbnail, phash, platform, file_size) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
    values = (username, media_type, file_url, width, height, media_id, post_type, post_date, user_id, file_hash, filename, duration, thumbnail_url, phash, platform, file_size)

    newCursor.execute(query, values) # slower
    newDB.commit()
    print(f'[{newCursor.rowcount}] records updated. File {filename} uploaded to {file_url}')

    os.remove(filepath)

    return True

def generate_thumbnail(filepath):   
    thumb_path = f'temp/{uuid4()}.jpg'
    cap = cv2.VideoCapture(filepath)
    ret, frame = cap.read()
    cv2.imwrite(thumb_path, frame)
    cap.release()
    return thumb_path

def get_user_id(username):
    username = username.lower()
    if username in existing_users:
        return existing_users[username]
    
    return None

def get_media_data(filepath):
    filename = os.path.basename(filepath)
    parts = filename.split('~')
    if len(parts) < 4:
        return False

    username = parts[0]
    timestamp = parts[1]
    media_id = parts[2]
    user_id = parts[3].split('_')[-1].split('.')[0]

    highlight_id = user_id.replace('highlight', '') if 'highlight' in user_id else None
    if highlight_id:
        user_id = get_user_id(username)

    try:
        media_id = int(media_id)
    except:
        print(f'Invalid media_id for file {filename}. Skipping...')
        media_id = None

    data = {'username': username, 'timestamp': timestamp, 'media_id': media_id, 'user_id': user_id, 'filepath': filepath, 'highlight_id': highlight_id}

    return data

def get_media(folder_path):
    medias = []
    
    for root, dirs, files in os.walk(folder_path):
        for filename in files:
            filepath = os.path.join(root, filename)
            
            data = get_media_data(filepath)
            if data:
                medias.append(data)
    
    return medias

def dump_instagram(folder_path):
    medias = get_media(folder_path)
    
    if cleanup_dupe_stories(medias):
        medias = get_media(folder_path)
    
    for media in medias:
        UploadMedia(media)
        existing_files.append(media['media_id'])

def cleanup_dupe_stories(medias):
    removed_count = 0
    for media in medias:
        media_id = media['media_id']
        filepath = media['filepath']

        if not media_id:
            print(f'Invalid media_id for file {filepath}. Skipping...')
            continue
        
        if media_id in existing_files:
            removed_count += 1
            print(f'Found duplicate file {filepath}. Removing...')
            os.remove(filepath)
                      
        if '(1)' in filepath:
            removed_count += 1
            print(f'Found duplicate file {filepath}. Removing...')
            os.remove(filepath)
    
    print(f'Removed {removed_count} duplicate files.')
    return removed_count
    
if __name__ == '__main__':
    print('Starting processing...')

    if not os.listdir(directory):
        print('No files to process. Exiting...')
        exit()
    
    newDB, newCursor = config.gen_connection()

    obj_storage = config.get_storage()

    newCursor.execute("SELECT media_id FROM media WHERE media_id IS NOT NULL")
    existing_files = [image[0] for image in newCursor.fetchall()]

    newCursor.execute("SELECT DISTINCT username, user_id FROM media WHERE user_id IS NOT NULL")
    existing_users = {user[0].lower(): user[1].lower() for user in newCursor.fetchall()}
    
    dump_instagram(directory)

    print("Processing completed.")