"""Ví dụ: gửi một video trending (thay nhân vật vào video có sẵn) bằng API của LIN AI rồi tải kết quả.

    pip install requests
    export LIN_AI_URL="https://<địa chỉ trang LIN AI>"
    export LIN_AI_KEY="lin_..."
    python trending_video.py character.jpg source.mp4
    python trending_video.py character.jpg "https://www.tiktok.com/@.../video/..."
"""
import mimetypes
import os
import sys
import time

import requests

BASE = os.environ["LIN_AI_URL"].rstrip("/")
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['LIN_AI_KEY']}"
character, source = sys.argv[1], sys.argv[2]

terms = session.get(f"{BASE}/api/trends", timeout=60).json()["terms"]
print(f"Lượt này trừ {terms['cost']} linh thạch; hệ thống dùng {terms['maxSeconds']} giây đầu của video")

# Gửi: ảnh nhân vật kèm MỘT trong hai nguồn, file video hoặc link TikTok. Bước này trừ linh thạch ngay.
def part(path: str):
    """Một file trong form: phải kèm đúng kiểu file (image/jpeg, video/mp4...), máy chủ kiểm tra theo đó."""
    return (os.path.basename(path), open(path, "rb"), mimetypes.guess_type(path)[0] or "application/octet-stream")


files = {"character": part(character)}
data = {"title": "Gửi từ API"}
if source.startswith("https://"):
    data["url"] = source
else:
    files["video"] = part(source)
res = session.post(f"{BASE}/api/trends", files=files, data=data, timeout=600)
if res.status_code >= 400:
    raise SystemExit(f"POST /api/trends -> {res.status_code}: {res.text}")
trend_id = res.json()["id"]
print("Đã gửi", trend_id)

# Chờ dựng xong. Lượt lỗi được hoàn linh thạch, câu báo lỗi nằm ở trường error.
while True:
    mine = next(t for t in session.get(f"{BASE}/api/trends", timeout=60).json()["trends"] if t["id"] == trend_id)
    print(" ", mine["status"])
    if mine["status"] == "done":
        break
    if mine["status"] == "failed":
        raise SystemExit(f"Lượt này lỗi: {mine['error']}")
    time.sleep(15)

video = session.get(f"{BASE}/api/trends/{trend_id}/video?download=1", timeout=300)
video.raise_for_status()
out = f"trending-{trend_id[:8]}.mp4"
with open(out, "wb") as f:
    f.write(video.content)
print("Đã tải", out)
