import os
import sys
import datetime
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload

if hasattr(sys.stdout, 'reconfigure'):
    try:
        sys.stdout.reconfigure(encoding='utf-8')
    except Exception:
        pass

def get_youtube_service():
    creds = Credentials.from_authorized_user_file('token.json')
    return build('youtube', 'v3', credentials=creds)

def upload_video(video_path, title, description, tags, publish_time):
    youtube = get_youtube_service()
    
    body = {
        'snippet': {
            'title': title,
            'description': description,
            'tags': tags,
            'categoryId': '27' # Education
        },
        'status': {
            'privacyStatus': 'private',
            'publishAt': publish_time.isoformat() + 'Z', # Lên lịch
            'selfDeclaredMadeForKids': False
        }
    }
    
    media = MediaFileUpload(video_path, chunksize=-1, resumable=True)
    
    print(f"Đang upload video: {title} (Lên lịch: {publish_time})")
    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"Upload tiến độ: {int(status.progress() * 100)}%")
            
    print(f"Upload thành công! Video ID: {response['id']}")
    return response['id']

def upload_subtitle(video_id, srt_path, language='en', name=None):
    if not os.path.exists(srt_path):
        print(f" [Lỗi] Không tìm thấy file phụ đề: {srt_path}")
        return None
    if name is None:
        name = f"{language.upper()} Subtitles"
        
    youtube = get_youtube_service()
    
    # Kiểm tra xem phụ đề chuẩn (standard) cho ngôn ngữ này đã tồn tại chưa
    try:
        existing = youtube.captions().list(part='snippet', videoId=video_id).execute()
        for item in existing.get('items', []):
            if item['snippet'].get('trackKind') == 'standard' and item['snippet']['language'] == language:
                print(f" -> Phụ đề [{language}] đã tồn tại trên video {video_id} (ID: {item['id']}). Bỏ qua.")
                return item
    except Exception as e:
        pass

    body = {
        'snippet': {
            'videoId': video_id,
            'language': language,
            'name': name,
            'isDraft': False
        }
    }
    
    media = MediaFileUpload(srt_path, mimetype='application/x-subrip')
    
    print(f" -> Đang upload phụ đề [{language} - {name}] lên video {video_id}...")
    try:
        request = youtube.captions().insert(
            part='snippet',
            sync=False,
            body=body,
            media_body=media
        )
        response = request.execute()
        print(f" [OK] Upload phụ đề [{language}] thành công! ID: {response['id']}")
        return response
    except Exception as e:
        print(f" [Lưu ý upload phụ đề {language}] {e}")
        return None

def set_thumbnail(video_id, thumbnail_path):
    youtube = get_youtube_service()
    request = youtube.thumbnails().set(
        videoId=video_id,
        media_body=MediaFileUpload(thumbnail_path)
    )
    request.execute()
    print(f"Cập nhật ảnh bìa thành công cho video {video_id}")
