#!/usr/bin/env python3
"""Upload resumavel (chunked) de video para o Meta - robusto para arquivos grandes."""
import sys, os, json, uuid
import urllib.request, urllib.parse, urllib.error
sys.path.insert(0, "/opt/mia/workspace/clientes/borrello")
from _meta_api import API, ACT, TOKEN, load_ids, save_ids

VIDEOS = {
    "MESAS 2": "/opt/mia/workspace/clientes/borrello/videos_mesas/MESAS 2 - REELS.mp4",
    "MESAS 3": "/opt/mia/workspace/clientes/borrello/videos_mesas/MESAS 3 - REELS.mp4",
    "MESAS 4": "/opt/mia/workspace/clientes/borrello/videos_mesas/MESAS 4 - REELS.mp4",
    "MESAS 5": "/opt/mia/workspace/clientes/borrello/videos_mesas/MESAS 5 - REEL.mp4",
}


def _multipart(url, fields, filefield=None):
    boundary = uuid.uuid4().hex
    parts = []
    for k, v in fields.items():
        parts.append(f"--{boundary}\r\n".encode())
        parts.append(f'Content-Disposition: form-data; name="{k}"\r\n\r\n'.encode())
        parts.append(f"{v}\r\n".encode())
    if filefield:
        name, data = filefield
        parts.append(f"--{boundary}\r\n".encode())
        parts.append(f'Content-Disposition: form-data; name="{name}"; filename="chunk"\r\n'.encode())
        parts.append(b"Content-Type: application/octet-stream\r\n\r\n")
        parts.append(data)
        parts.append(b"\r\n")
    parts.append(f"--{boundary}--\r\n".encode())
    body = b"".join(parts)
    req = urllib.request.Request(url, data=body, method="POST")
    req.add_header("Content-Type", f"multipart/form-data; boundary={boundary}")
    for attempt in range(4):
        try:
            with urllib.request.urlopen(req, timeout=300) as r:
                return json.loads(r.read().decode())
        except urllib.error.HTTPError as e:
            raise RuntimeError(f"HTTP {e.code}: {e.read().decode()}")
        except Exception as e:
            if attempt == 3:
                raise
            print(f"    retry {attempt+1} ({e})", flush=True)


def upload_chunked(filepath, name):
    url = f"{API}/{ACT}/advideos"
    filesize = os.path.getsize(filepath)
    # START
    res = _multipart(url, {"access_token": TOKEN, "upload_phase": "start",
                           "file_size": str(filesize)})
    session_id = res["upload_session_id"]
    video_id = res["video_id"]
    start = int(res["start_offset"]); end = int(res["end_offset"])
    with open(filepath, "rb") as f:
        while start < end:
            f.seek(start)
            chunk = f.read(end - start)
            res = _multipart(url, {
                "access_token": TOKEN, "upload_phase": "transfer",
                "upload_session_id": session_id, "start_offset": str(start),
            }, filefield=("video_file_chunk", chunk))
            start = int(res["start_offset"]); end = int(res["end_offset"])
            print(f"    offset {start}/{filesize}", flush=True)
    # FINISH
    _multipart(url, {"access_token": TOKEN, "upload_phase": "finish",
                     "upload_session_id": session_id, "title": name})
    return video_id


ids = load_ids()
for label, path in VIDEOS.items():
    if ids["videos"].get(label):
        print(f"SKIP {label} -> {ids['videos'][label]}")
        continue
    print(f"Chunked upload {label} ({os.path.getsize(path)//1024//1024}MB) ...", flush=True)
    vid = upload_chunked(path, f"MESAS RADIONICAS - {label} - 07.2026")
    ids["videos"][label] = vid
    save_ids(ids)
    print(f"  OK {label} -> {vid}", flush=True)

print("DONE CHUNKED UPLOADS")
print(json.dumps(ids["videos"], ensure_ascii=False))
