#!/usr/bin/env python3
"""
Sobe os reels gerados para o Google Drive.
Estrutura: PASTA DA MIA > Borrello > Live_FengShui_Cortes > Para_Aprovacao/
"""
import json
import os
import requests
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request

TOKENS_PATH = "/opt/mia/config/drive_tokens.json"
CONFIG_PATH = "/opt/mia/config/drive_config.json"
REELS_DIR = "/opt/mia/workspace/clientes/borrello/live_feng_shui_cortes/"
REELS_SUMMARY = os.path.join(REELS_DIR, "reels_summary.json")

# Pasta raiz da Mia
with open(CONFIG_PATH) as f:
    cfg = json.load(f)
MIA_ROOT = cfg["mia_root"]  # 1F-0M5zBPDVTjQh3QIQFc0pIcQUuDX0hE


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 find_or_create_folder(creds, name, parent_id):
    """Busca pasta por nome dentro de parent_id; cria se nao existir."""
    headers = {"Authorization": f"Bearer {creds.token}"}
    # Buscar
    q = f"name='{name}' and mimeType='application/vnd.google-apps.folder' and '{parent_id}' in parents and trashed=false"
    resp = requests.get(
        "https://www.googleapis.com/drive/v3/files",
        params={"q": q, "fields": "files(id,name)"},
        headers=headers
    )
    resp.raise_for_status()
    files = resp.json().get("files", [])
    if files:
        folder_id = files[0]["id"]
        print(f"  Pasta existente: '{name}' (id={folder_id})")
        return folder_id

    # Criar
    meta = {
        "name": name,
        "mimeType": "application/vnd.google-apps.folder",
        "parents": [parent_id],
    }
    resp = requests.post(
        "https://www.googleapis.com/drive/v3/files",
        json=meta,
        headers=headers
    )
    resp.raise_for_status()
    folder_id = resp.json()["id"]
    print(f"  Pasta criada: '{name}' (id={folder_id})")
    return folder_id


def upload_file(creds, local_path, folder_id, mime_type="video/mp4"):
    """Upload de arquivo para pasta do Drive."""
    name = os.path.basename(local_path)
    file_size = os.path.getsize(local_path)
    headers = {"Authorization": f"Bearer {creds.token}"}

    # Verificar se ja existe
    q = f"name='{name}' and '{folder_id}' in parents and trashed=false"
    resp = requests.get(
        "https://www.googleapis.com/drive/v3/files",
        params={"q": q, "fields": "files(id,name,size)"},
        headers=headers
    )
    existing = resp.json().get("files", [])
    if existing:
        existing_id = existing[0]["id"]
        print(f"  [ja existe] {name} (id={existing_id})")
        return existing_id, f"https://drive.google.com/file/d/{existing_id}/view"

    # Upload multipart simples para arquivos < 5MB
    # Para arquivos maiores, usar resumable upload
    meta = {"name": name, "parents": [folder_id]}

    if file_size < 5 * 1024 * 1024:
        from requests_toolbelt import MultipartEncoder
        m = MultipartEncoder(
            fields={
                "metadata": (None, json.dumps(meta), "application/json; charset=UTF-8"),
                "file": (name, open(local_path, "rb"), mime_type),
            }
        )
        resp = requests.post(
            "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
            data=m,
            headers={"Authorization": f"Bearer {creds.token}", "Content-Type": m.content_type},
        )
    else:
        # Resumable upload para videos maiores
        # Passo 1: iniciar sessao
        init_resp = requests.post(
            "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",
            json=meta,
            headers={
                "Authorization": f"Bearer {creds.token}",
                "Content-Type": "application/json; charset=UTF-8",
                "X-Upload-Content-Type": mime_type,
                "X-Upload-Content-Length": str(file_size),
            }
        )
        init_resp.raise_for_status()
        upload_url = init_resp.headers["Location"]

        # Passo 2: enviar dados
        with open(local_path, "rb") as f:
            data = f.read()
        resp = requests.put(
            upload_url,
            data=data,
            headers={
                "Content-Type": mime_type,
                "Content-Length": str(file_size),
            }
        )

    resp.raise_for_status()
    file_id = resp.json()["id"]
    drive_url = f"https://drive.google.com/file/d/{file_id}/view"
    print(f"  Enviado: {name} -> {drive_url}")
    return file_id, drive_url


def main():
    print("Autenticando no Google Drive...")
    creds = get_credentials()

    # Estrutura de pastas: MIA_ROOT/Borrello/Live_FengShui_Cortes/Para_Aprovacao
    print("\nCriando estrutura de pastas...")
    borrello_id = find_or_create_folder(creds, "Borrello", MIA_ROOT)
    live_id = find_or_create_folder(creds, "Live_FengShui_Cortes", borrello_id)
    aprovacao_id = find_or_create_folder(creds, "Para_Aprovacao", live_id)

    aprovacao_url = f"https://drive.google.com/drive/folders/{aprovacao_id}"
    print(f"\nPasta de aprovacao: {aprovacao_url}")

    # Listar reels gerados
    mp4_files = sorted([
        os.path.join(REELS_DIR, f)
        for f in os.listdir(REELS_DIR)
        if f.startswith("reel_") and f.endswith(".mp4")
    ])

    if not mp4_files:
        print("ERRO: nenhum reel encontrado em", REELS_DIR)
        return None

    print(f"\nEnviando {len(mp4_files)} reels...")
    uploaded = []
    for mp4 in mp4_files:
        size_mb = os.path.getsize(mp4) / 1024 / 1024
        print(f"\n  {os.path.basename(mp4)} ({size_mb:.1f} MB)")
        try:
            file_id, url = upload_file(creds, mp4, aprovacao_id)
            uploaded.append({"file": os.path.basename(mp4), "id": file_id, "url": url})
        except Exception as e:
            print(f"  ERRO ao enviar {mp4}: {e}")

    # Salvar resultado
    result = {
        "folder_url": aprovacao_url,
        "folder_id": aprovacao_id,
        "uploaded": uploaded,
    }
    with open(os.path.join(REELS_DIR, "drive_upload_result.json"), "w") as f:
        json.dump(result, f, indent=2, ensure_ascii=False)

    print(f"\n=== UPLOAD CONCLUIDO: {len(uploaded)}/{len(mp4_files)} ===")
    print(f"Pasta Drive: {aprovacao_url}")
    return result


if __name__ == "__main__":
    main()
