#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Sobe as 5 featured images v2 (com safe zone) pro Drive.
Destino: PASTA DA MIA > Borrello > Blog > featured_images_v1_2026-09-18
Substitui os arquivos existentes com mesmo nome.
"""
import json
import os
import requests
from pathlib import Path
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request

TOKENS = "/opt/mia/config/drive_tokens.json"
CLIENT = "/opt/mia/config/oauth_client.json"
BORRELLO_FOLDER_ID = "1a9fQeMsIdQtFeP-hpOmzDeSzGXqOcxvn"
IMGS_DIR = Path("/opt/mia/workspace/clientes/borrello/blog/artigos_v1_2026-09-18/featured_images")

FILES = [
    "featured_01_entrada.jpg",
    "featured_02_quarto.jpg",
    "featured_03_plantas.jpg",
    "featured_04_animais.jpg",
    "featured_05_bagua.jpg",
]

with open(TOKENS) as f:
    t = json.load(f)
with open(CLIENT) as f:
    c = json.load(f)["installed"]

creds = Credentials(
    token=t.get("access_token"),
    refresh_token=t.get("refresh_token"),
    token_uri="https://oauth2.googleapis.com/token",
    client_id=c["client_id"],
    client_secret=c["client_secret"],
    scopes=["https://www.googleapis.com/auth/drive"],
)
if not creds.valid:
    creds.refresh(Request())
    t["access_token"] = creds.token
    with open(TOKENS, "w") as f:
        json.dump(t, f)
    print("Token renovado.")

H = {"Authorization": f"Bearer {creds.token}"}


def get_or_create(name, parent):
    q = (
        f"'{parent}' in parents and name = '{name}' and "
        f"mimeType = 'application/vnd.google-apps.folder' and trashed = false"
    )
    r = requests.get(
        "https://www.googleapis.com/drive/v3/files",
        headers=H, params={"q": q, "fields": "files(id,name)"},
    )
    r.raise_for_status()
    fs = r.json().get("files", [])
    if fs:
        return fs[0]["id"]
    r = requests.post(
        "https://www.googleapis.com/drive/v3/files",
        headers=H,
        json={"name": name, "parents": [parent],
              "mimeType": "application/vnd.google-apps.folder"},
    )
    r.raise_for_status()
    return r.json()["id"]


def upload_replace(local_path, name, parent):
    """Se ja existe arquivo com esse nome, atualiza; senao cria."""
    # Procura existente
    q = f"'{parent}' in parents and name = '{name}' and trashed = false"
    r = requests.get(
        "https://www.googleapis.com/drive/v3/files",
        headers=H, params={"q": q, "fields": "files(id,name)"},
    )
    r.raise_for_status()
    fs = r.json().get("files", [])
    data = Path(local_path).read_bytes()

    if fs:
        # PATCH content
        fid = fs[0]["id"]
        r = requests.patch(
            f"https://www.googleapis.com/upload/drive/v3/files/{fid}?uploadType=media",
            headers={**H, "Content-Type": "image/jpeg"},
            data=data,
        )
        r.raise_for_status()
        print(f"  ATUALIZADO: {name} (id={fid})")
        return fid, fs[0].get("webViewLink")
    else:
        # POST multipart
        meta = {"name": name, "parents": [parent]}
        files = {
            "data": ("metadata", json.dumps(meta), "application/json"),
            "file": (name, data, "image/jpeg"),
        }
        r = requests.post(
            "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
            headers=H, files=files,
        )
        r.raise_for_status()
        j = r.json()
        print(f"  CRIADO: {name} (id={j['id']})")
        return j["id"], None


print("Montando estrutura no Drive...")
blog_id = get_or_create("Blog", BORRELLO_FOLDER_ID)
leva_id = get_or_create("featured_images_v1_2026-09-18", blog_id)
print(f"Pasta destino id: {leva_id}")

uploaded = []
for fname in FILES:
    p = IMGS_DIR / fname
    if not p.exists():
        print(f"AUSENTE: {p}")
        continue
    fid, link = upload_replace(str(p), fname, leva_id)
    uploaded.append((fname, fid))

print(f"\n=== Pasta: https://drive.google.com/drive/folders/{leva_id} ===")
for fname, fid in uploaded:
    print(f"  {fname}: https://drive.google.com/file/d/{fid}/view")
