import requests, hashlib, os

access_key = "471cd2e1-a943-4c61-ae69ddc6c2c2-c36d-4737"
video_library_id = 125094

def create_video(title):
    url = f"https://video.bunnycdn.com/library/{video_library_id}/videos"

    payload = f"{{\"title\":\"{title}\"}}"
    headers = {
        "accept": "application/json",
        "content-type": "application/*+json",
        "AccessKey": access_key
    }

    response = requests.post(url, data=payload, headers=headers)

    return response

def generate_signature(library_id, api_key, expiration_time, video_id):
    signature = hashlib.sha256((library_id + api_key + str(expiration_time) + video_id).encode()).hexdigest()
    return signature

def upload_video_process(file_path, video_id):
    url = f"https://video.bunnycdn.com/library/{video_library_id}/videos/{video_id}"

    headers = {"accept": "application/json","AccessKey": access_key}

    with open(file_path, "rb") as file:
        file_data = file.read()

    response = requests.put(url, headers=headers, data=file_data)

    return response.status_code

def upload_video(file_path, title=None):
    video_item = create_video(title)
    if video_item.status_code != 200:
        return False
    
    video_id = video_item.json()['guid']
    upload_video_process(file_path, video_id)

    return {
        "embed_link": f"https://vz-58ca89f1-986.b-cdn.net/{video_id}/playlist.m3u8",
        "animated_thumbnail": f"https://vz-58ca89f1-986.b-cdn.net/{video_id}/preview.webp",
        "default_thumbnail": f"https://vz-58ca89f1-986.b-cdn.net/{video_id}/thumbnail.jpg",
    }


def upload_video_recurbate(videoInfo):
    title = f"{videoInfo['username']} {videoInfo['platform']}"
    video_item = create_video(title)
    if video_item.status_code != 200:
        return False
    
    video_id = video_item.json()['guid']
    upload_video_process(videoInfo['filename'], video_id)

    videoInfo["embed_link"] = f"https://vz-58ca89f1-986.b-cdn.net/{video_id}/playlist.m3u8"
    videoInfo["animated_thumbnail"] = f"https://vz-58ca89f1-986.b-cdn.net/{video_id}/preview.webp"
    videoInfo["default_thumbnail"] = f"https://vz-58ca89f1-986.b-cdn.net/{video_id}/thumbnail.jpg"

    return True

def delete_video(video_id):
    video_id = video_id.replace('https://vz-58ca89f1-986.b-cdn.net/', '').replace('/playlist.m3u8', '')
    
    url = f"https://video.bunnycdn.com/library/{video_library_id}/videos/{video_id}"

    headers = {"accept": "application/json","AccessKey": access_key}

    response = requests.delete(url, headers=headers)

    return response.status_code

def list_videos():
    url = f"https://video.bunnycdn.com/library/{video_library_id}/videos"

    params = {
        "page": 1,
        "itemsPerPage": 1000,
        "orderBy": "date"
    }

    headers = {"accept": "application/json","AccessKey": access_key}

    videos = []
    while True:
        response = requests.get(url, headers=headers, params=params)

        data = response.json()
        videos += data['items']

        if len(videos) == data['totalItems']:
            return videos

        params['page'] += 1

def get_heatmap(video_id):
    url = "https://video.bunnycdn.com/library/libraryId/videos/videoId/heatmap"
    url = url.replace('libraryId', str(video_library_id)).replace('videoId', str(video_id))

    headers = {"accept": "application/json","AccessKey": access_key}

    response = requests.get(url, headers=headers).json()

    return response

def get_video(video_id):
    url = "https://video.bunnycdn.com/library/libraryId/videos/videoId"
    url = url.replace('libraryId', str(video_library_id)).replace('videoId', str(video_id))

    headers = {"accept": "application/json","AccessKey": access_key}

    response = requests.get(url, headers=headers).json()

    return response


def download_video(video_id, directory):
    download_url = f'https://storage.bunnycdn.com/vz-dd4ea005-7c2/{video_id}/'

    params = {'download': '','accessKey': '5b1766f7-c1ab-463f-b05cce6f1f2e-1190-4c09'}

    video_response = requests.get(download_url, params=params)

    if video_response.status_code == 200:
        content_disposition = video_response.headers.get('Content-Disposition')
        if content_disposition:
            filename = content_disposition.split('filename=')[1].strip('"')
            ext = filename.split('.')[-1]

        filename = f'{video_id}.{ext}'
        filePath = os.path.join(directory, filename)
                
        with open(filePath, 'wb') as video_file:
            video_file.write(video_response.content)
        print(f'Video downloaded successfully as {filePath}')
    else:
        print('Failed to download video', video_response.status_code, video_response.text)
