"""
YouTube Uploader Engine for The Holy Bible For World
Uploads videos and shorts directly using token_holybible.json
"""
import os
import json
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from google.oauth2.credentials import Credentials

CREDENTIALS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'credentials')
TOKEN_FILE = os.path.join(CREDENTIALS_DIR, 'token_holybible.json')

def upload_video(
    video_file_path: str,
    title: str,
    description: str,
    tags: list = None,
    category_id: str = "27",  # 27: Education, 29: Nonprofits & Activism
    privacy_status: str = "public"  # "public", "private", "unlisted"
) -> dict:
    if not os.path.exists(TOKEN_FILE):
        raise FileNotFoundError(f"Kanal yetki dosyasi bulunamadi: {TOKEN_FILE}")

    if not os.path.exists(video_file_path):
        raise FileNotFoundError(f"Video dosyasi bulunamadi: {video_file_path}")

    with open(TOKEN_FILE, 'r', encoding='utf-8') as f:
        token_data = json.load(f)

    creds = Credentials.from_authorized_user_info(token_data)
    youtube = build('youtube', 'v3', credentials=creds)

    body = {
        'snippet': {
            'title': title,
            'description': description,
            'tags': tags or ['bible', 'faith', 'shorts'],
            'categoryId': category_id
        },
        'status': {
            'privacyStatus': privacy_status,
            'selfDeclaredMadeForKids': False
        }
    }

    media = MediaFileUpload(
        video_file_path,
        mimetype='video/mp4',
        resumable=True,
        chunksize=1024*1024*4
    )

    print(f"[*] YouTube yukleme baslatiliyor: '{title}' ({privacy_status})...", flush=True)
    request = youtube.videos().insert(
        part=','.join(body.keys()),
        body=body,
        media_body=media
    )

    response = None
    while response is None:
        status, response = request.next_chunk()
        if status:
            print(f"[*] Yukleme ilerlemesi: %{int(status.progress() * 100)}", flush=True)

    video_id = response.get('id')
    video_url = f"https://youtube.com/shorts/{video_id}"
    print(f"[+] BASARILI! Video yuklendi: {video_url}", flush=True)
    return response

if __name__ == '__main__':
    print("[*] YouTube Uploader modulu hazir.")
