import os
import sys
import json
import subprocess
import google.auth.transport.requests
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

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

SCOPES = [
    'https://www.googleapis.com/auth/youtube.upload',
    'https://www.googleapis.com/auth/youtube.readonly',
    'https://www.googleapis.com/auth/youtube.force-ssl',
    'https://www.googleapis.com/auth/drive.readonly'
]

class UrlHook:
    def format(self, url):
        with open('auth_url.txt', 'w', encoding='utf-8') as f:
            f.write(url)
        print("\n=======================================================", flush=True)
        print("VUI LÒNG BẤM VÀO ĐƯỜNG LINK XÁC THỰC DUY NHẤT DƯỚI ĐÂY:", flush=True)
        print(url, flush=True)
        print("=======================================================\n", flush=True)
        try:
            subprocess.Popen(['powershell', '-Command', f'Start-Process "{url}"'])
        except Exception:
            pass
        return f"AUTH_URL_READY: {url}"

def authenticate(port=8080):
    creds = None
    if os.path.exists('token.json'):
        try:
            with open('token.json', 'r', encoding='utf-8') as f:
                token_data = json.load(f)
            granted = set(token_data.get('scopes', []))
            if all(s in granted for s in SCOPES):
                creds = Credentials.from_authorized_user_file('token.json', SCOPES)
            else:
                print("[Thông báo] Cần bổ sung quyền youtube.force-ssl để upload phụ đề tự động. Khởi tạo xác thực...", flush=True)
                creds = None
        except Exception:
            creds = None
    
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            try:
                creds.refresh(google.auth.transport.requests.Request())
            except Exception:
                creds = None
        
        if not creds or not creds.valid:
            flow = InstalledAppFlow.from_client_secrets_file(
                'client_secrets.json', SCOPES)
            
            print(f"Khởi động server callback OAuth tại cổng {port}...", flush=True)
            creds = flow.run_local_server(
                port=port,
                open_browser=False,
                authorization_prompt_message=UrlHook(),
                prompt='consent',
                access_type='offline'
            )
        
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
            
    print("\n[OK] Xác thực thành công! File token.json đã được tạo.", flush=True)
    
    try:
        yt = build('youtube', 'v3', credentials=creds)
        res = yt.channels().list(part='snippet', mine=True).execute()
        if res.get('items'):
            ch = res['items'][0]
            print(f"[OK] Kênh kết nối thành công: {ch['snippet']['title']} (ID: {ch['id']})", flush=True)
        else:
            print("[Cảnh báo] Chưa tìm thấy kênh YouTube nào gắn với tài khoản này. Vui lòng đảm bảo bạn đã bấm Tạo kênh.", flush=True)
    except Exception as e:
        print(f"[Lưu ý] {e}", flush=True)
        
    return creds

if __name__ == '__main__':
    authenticate()
