#!/usr/bin/env python3
"""Fetch one Douyin video via the same TikHub endpoint used by douyin-downloader.

The token is read from ~/.openclaw/config.json and is never printed.
"""

from __future__ import annotations

import json
import os
import re
import sys
import urllib.request


API = "https://api.tikhub.io/api/v1/douyin/web/fetch_one_video"


def load_token() -> str:
    config_path = os.path.expanduser("~/.openclaw/config.json")
    with open(config_path, "r", encoding="utf-8") as f:
        config = json.load(f)
    token = config.get("tikhub_api_token")
    if not token:
        raise RuntimeError("missing tikhub_api_token in ~/.openclaw/config.json")
    return token


def request_text(url: str, headers: dict[str, str]) -> str:
    req = urllib.request.Request(url, headers=headers)
    with urllib.request.urlopen(req, timeout=60) as resp:
        return resp.read().decode("utf-8", errors="replace")


def download(url: str, output_path: str) -> None:
    headers = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
        "Referer": "https://www.douyin.com/",
    }
    req = urllib.request.Request(url, headers=headers)
    with urllib.request.urlopen(req, timeout=120) as resp:
        data = resp.read()
    with open(output_path, "wb") as f:
        f.write(data)


def main() -> int:
    if len(sys.argv) != 3:
        print("usage: fetch_douyin_video.py <aweme_id> <output.mp4>", file=sys.stderr)
        return 2
    aweme_id, output_path = sys.argv[1], sys.argv[2]
    token = load_token()
    endpoint = f"{API}?aweme_id={aweme_id}&need_anchor_info=false"
    text = request_text(endpoint, {"Authorization": f"Bearer {token}"})
    normalized = text.replace("\\/", "/")
    match = re.search(r'(https://www\.douyin\.com/aweme/v1/play/[^\s"<>\\]+)', normalized)
    if not match:
        print("video_url not found in TikHub response", file=sys.stderr)
        return 1
    video_url = match.group(1)
    download(video_url, output_path)
    print(output_path)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
