#!/usr/bin/env python3
"""
Baixa o arquivo do Google Drive usando OAuth2 configurado.
FILE_ID: 1cDTTrpUTqJgTQ6lWb9ON0sfEpoTHA-Ew
"""
import json
import os
import sys
import requests
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request

TOKENS_PATH = "/opt/mia/config/drive_tokens.json"
DEST = "/opt/mia/workspace/clientes/borrello/live_feng_shui_raw/"
FILE_ID = "1cDTTrpUTqJgTQ6lWb9ON0sfEpoTHA-Ew"

def get_credentials():
    with open(TOKENS_PATH) as f:
        t = json.load(f)
    creds = Credentials(
        token=t.get("access_token") or t.get("token"),
        refresh_token=t.get("refresh_token"),
        token_uri=t.get("token_uri", "https://oauth2.googleapis.com/token"),
        client_id=t.get("client_id"),
        client_secret=t.get("client_secret"),
        scopes=t.get("scopes", ["https://www.googleapis.com/auth/drive"]),
    )
    if not creds.valid:
        creds.refresh(Request())
        t["access_token"] = creds.token
        t["token"] = creds.token
        with open(TOKENS_PATH, "w") as f:
            json.dump(t, f, indent=2)
    return creds

def get_file_metadata(creds, file_id):
    resp = requests.get(
        f"https://www.googleapis.com/drive/v3/files/{file_id}",
        params={"fields": "name,size,mimeType"},
        headers={"Authorization": f"Bearer {creds.token}"}
    )
    resp.raise_for_status()
    return resp.json()

def download_file(creds, file_id, dest_path):
    url = f"https://www.googleapis.com/drive/v3/files/{file_id}?alt=media"
    headers = {"Authorization": f"Bearer {creds.token}"}
    with requests.get(url, headers=headers, stream=True) as r:
        r.raise_for_status()
        total = int(r.headers.get("content-length", 0))
        downloaded = 0
        with open(dest_path, "wb") as f:
            for chunk in r.iter_content(chunk_size=8*1024*1024):
                if chunk:
                    f.write(chunk)
                    downloaded += len(chunk)
                    if total:
                        pct = downloaded / total * 100
                        print(f"\r  {pct:.1f}% ({downloaded/1024/1024:.0f}MB / {total/1024/1024:.0f}MB)", end="", flush=True)
    print()
    return dest_path

if __name__ == "__main__":
    print("Autenticando com Google Drive...")
    creds = get_credentials()

    print(f"Buscando metadados do arquivo {FILE_ID}...")
    meta = get_file_metadata(creds, FILE_ID)
    name = meta.get("name", "live_feng_shui.mp4")
    size_bytes = int(meta.get("size", 0))
    mime = meta.get("mimeType", "")
    print(f"  Nome: {name}")
    print(f"  Tamanho: {size_bytes/1024/1024:.1f} MB")
    print(f"  Tipo: {mime}")

    # Garante extensao correta
    if not name.lower().endswith(".mp4"):
        name = "live_feng_shui_borrello.mp4"

    dest_path = os.path.join(DEST, name)
    print(f"Baixando para: {dest_path}")
    download_file(creds, FILE_ID, dest_path)

    actual_size = os.path.getsize(dest_path)
    print(f"Download concluido: {actual_size/1024/1024:.1f} MB")
    print(f"DEST:{dest_path}")
