import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..','..')))
import requests
from dotenv import load_dotenv
import re
import logging
from services.my_slack.my_slack import send_slack

load_dotenv()

def vimeo_upload(file_path,new_file_name):
    logging.info("=== Vimeo Upload Function Started ===")
    logging.info(f"Vimeo upload called: file_path={file_path}, new_file_name={new_file_name}, user_folder_id=22423637")
    
    # Vimeoのアクセストークン
    vimeo_access_token = os.getenv('VIMEO_ACCESS_TOKEN')
    logging.info("Loaded Vimeo access token from environment")

    # ファイルサイズの取得
    file_size = os.path.getsize(file_path)
    logging.info(f"File size obtained: {file_size} bytes")

    # ヘッダーの設定
    headers = {
        'Authorization': f'Bearer {vimeo_access_token}',
        'Content-Type': 'application/json',
        'Accept': 'application/vnd.vimeo.*+json;version=3.4',
    }
    logging.info("Headers configured for Vimeo API request")

    # アップロード開始
    logging.info("Initiating POST request to Vimeo API for video creation")
    response = requests.post(
        'https://api.vimeo.com/users/124467677/videos',
        headers=headers,
        json={
            'upload': {
                'approach': 'tus',
                'size': file_size
            }
        }
    )
    logging.info(f"Video creation request completed with status: {response.status_code}")
    
    if response.status_code != 200:
        logging.error(f"Failed to create video. Status: {response.status_code}, Response: {response.text}")
        send_slack("Vimeoのアップロードに失敗しました。Vimeoのファイルアップロード制限可能性あり。")
        raise Exception(f'Failed to create video. Response: {response.text}')

    # アップロードURLの取得
    upload_link = response.json()['upload']['upload_link']
    logging.info("Upload link obtained successfully")
    
    # ファイルをアップロード
    logging.info("Starting file upload to Vimeo")
    with open(file_path, 'rb') as f:
        upload_response = requests.patch(
            upload_link,
            headers={
                'Tus-Resumable': '1.0.0',
                'Upload-Offset': '0',
                'Content-Type': 'application/offset+octet-stream',
                'Authorization': f'Bearer {vimeo_access_token}'
            },
            data=f
        )
    logging.info(f"File upload completed with status: {upload_response.status_code}")

    if upload_response.status_code != 204:
        logging.error(f"Failed to upload video. Status: {upload_response.status_code}, Response: {upload_response.text}")
        raise Exception(f'Failed to upload video. Response: {upload_response.text}')

    logging.info('Video uploaded successfully!')
    
    ###ファイル名の変更
    logging.info("Starting file name change process")
    video_uri = response.json()['uri']
    match = re.search(r'\d+', video_uri)

    if match:
        new_video_id = match.group()
        logging.info(f"Video ID extracted: {new_video_id}")
    else:
        logging.error("No video ID found in URI")
        
    # APIエンドポイント
    url = f'https://api.vimeo.com{video_uri}'
    logging.info(f"Constructed URL for name change: {url}")

    # ヘッダー設定
    headers = {
        'Authorization': f'Bearer {vimeo_access_token}',
        'Content-Type': 'application/json',
        'Accept': 'application/vnd.vimeo.*+json;version=3.4'
    }

    # データ設定
    data = {
        'name': new_file_name
    }
    logging.info(f"Preparing to change video name to: {new_file_name}")

    # PATCHリクエストを送信して動画の名前を変更
    response_change_file_name = requests.patch(url, headers=headers, json=data)
    logging.info(f"Name change request completed with status: {response_change_file_name.status_code}")

    if response_change_file_name.status_code == 200:
        logging.info(f"Successfully updated video name to '{new_file_name}'")
    else:
        logging.error(f"Failed to update video name. Status code: {response_change_file_name.status_code}")
        logging.error(f"Error response: {response_change_file_name.json()}")
    
    # APIエンドポイント
    url = f'https://api.vimeo.com/me/projects/22423637/videos/{new_video_id}'
    logging.info(f"Constructed URL for location change: {url}")
    # ヘッダー設定
    headers = {
        'Authorization': f'Bearer {vimeo_access_token}',
        'Content-Type': 'application/json'
    }
    # ファイルの場所変更
    logging.info(f"Starting file location change - File: {new_file_name}, Destination: 22423637")
    response = requests.put(url, headers=headers)
    logging.info(f"Location change request completed with status: {response.status_code}")
    
    if response.status_code == 204:
        logging.info("File location changed successfully")

        # 動画の詳細を取得するためのAPIリクエストを送信
        video_details_url = f'https://api.vimeo.com/videos/{new_video_id}'
        logging.info(f"Retrieving video details from: {video_details_url}")
        video_response = requests.get(video_details_url, headers=headers)

        if video_response.status_code == 200:
            video_data = video_response.json()
            video_link = video_data.get('link')
            logging.info(f'Video viewing URL obtained: {video_link}')
            logging.info("=== Vimeo Upload Process Completed Successfully ===")
            return video_link
        else:
            logging.error(f'Failed to retrieve video details: {video_response.status_code}')
            return
    else:
        logging.error(f'Failed to change file location: {response.status_code}')
        return