import json
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload

# Auth
with open('/opt/mia/config/drive_tokens.json') as f:
    tokens = json.load(f)
with open('/opt/mia/config/oauth_client.json') as f:
    client_data = json.load(f)['installed']

creds = Credentials(
    token=tokens['access_token'],
    refresh_token=tokens['refresh_token'],
    token_uri='https://oauth2.googleapis.com/token',
    client_id=client_data['client_id'],
    client_secret=client_data['client_secret'],
    scopes=['https://www.googleapis.com/auth/drive']
)
if creds.expired:
    creds.refresh(Request())
    # salva token renovado
    tokens['access_token'] = creds.token
    with open('/opt/mia/config/drive_tokens.json', 'w') as f:
        json.dump(tokens, f)

service = build('drive', 'v3', credentials=creds)

MIA_ROOT = '1F-0M5zBPDVTjQh3QIQFc0pIcQUuDX0hE'
BORRELLO_ID = '1a9fQeMsIdQtFeP-hpOmzDeSzGXqOcxvn'  # Borrello dentro da PASTA DA MIA

def find_or_create_folder(name, parent_id):
    query = (
        f"name='{name}' and mimeType='application/vnd.google-apps.folder' "
        f"and '{parent_id}' in parents and trashed=false"
    )
    results = service.files().list(q=query, fields='files(id,name)').execute()
    files = results.get('files', [])
    if files:
        print(f'Pasta existente: {name} ({files[0]["id"]})')
        return files[0]['id']
    meta = {
        'name': name,
        'mimeType': 'application/vnd.google-apps.folder',
        'parents': [parent_id]
    }
    folder = service.files().create(body=meta, fields='id').execute()
    print(f'Pasta criada: {name} ({folder["id"]})')
    return folder['id']

def upload_file(local_path, name, parent_id, mime_type):
    media = MediaFileUpload(local_path, mimetype=mime_type)
    meta = {'name': name, 'parents': [parent_id]}
    f = service.files().create(body=meta, media_body=media, fields='id,webViewLink').execute()
    print(f'Upload OK: {name} -> {f["webViewLink"]}')
    return f

# Criar estrutura Blog > 01_Para_Revisao dentro de Borrello
blog_id = find_or_create_folder('Blog', BORRELLO_ID)
revisao_id = find_or_create_folder('01_Para_Revisao', blog_id)

BASE = '/opt/mia/workspace/clientes/borrello/blog/'

# Upload dos 3 arquivos
docx = upload_file(
    BASE + 'radiestesia_artigo_2026-09-28.docx',
    'radiestesia_artigo_2026-09-28.docx',
    revisao_id,
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
)

seo = upload_file(
    BASE + 'radiestesia_seo_plan_2026-09-28.md',
    'radiestesia_seo_plan_2026-09-28.md',
    revisao_id,
    'text/markdown'
)

html = upload_file(
    BASE + 'radiestesia_html_wp_2026-09-28.html',
    'radiestesia_html_wp_2026-09-28.html',
    revisao_id,
    'text/html'
)

print()
print('=== LINKS ===')
print(f'DOCX : {docx["webViewLink"]}')
print(f'SEO  : {seo["webViewLink"]}')
print(f'HTML : {html["webViewLink"]}')
