import json
import os
import re
import shutil
import sys
import time
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlsplit
from urllib.request import Request, urlopen

TASKS = "https://api.quickrouter.ai/api/v3/contents/generations/tasks"
STATE = Path("seedance-task-id.txt")
VIDEO = Path("product-video.mp4")


def task_request(token, task_id="", body=None):
    url = TASKS + ("/" + quote(task_id, safe="") if task_id else "")
    data = None if body is None else json.dumps(body, ensure_ascii=False).encode()
    headers = {"Authorization": "Bearer " + token}
    if data is not None:
        headers["Content-Type"] = "application/json"
    with urlopen(Request(url, data, headers), timeout=30) as response:
        result = json.load(response)
    if not isinstance(result, dict):
        raise ValueError("任务响应格式异常")
    return result.get("data") if isinstance(result.get("data"), dict) else result


def validate(body):
    if body.get("model") != "doubao-seedance-2-5-260628":
        raise ValueError("request.json 的 model 需要是 Seedance 2.5 完整 ID")
    for item in body.get("content", []):
        if item.get("role") == "reference_image":
            parsed = urlsplit(item.get("image_url", {}).get("url", ""))
            if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.hostname == "your-public-image-url":
                raise ValueError("请把示例 URL 换成图片的可访问 HTTPS 直链")
            return
    raise ValueError("request.json 需要一个 reference_image")


def create(token, source):
    if STATE.exists():
        raise ValueError(f"已有 {STATE}；先查询原任务。确需新建时请先归档旧 ID。")
    body = json.loads(Path(source).read_text(encoding="utf-8"))
    validate(body)
    result = task_request(token, body=body)
    task_id = result.get("id")
    if not isinstance(task_id, str) or not task_id.strip():
        raise ValueError("创建响应没有任务 ID；请到控制台确认后再决定是否重试")
    STATE.write_text(task_id + "\n", encoding="utf-8")
    print("任务 ID:", task_id)


def save_video(url):
    if VIDEO.exists():
        raise ValueError(f"{VIDEO} 已存在，请先改名或移动")
    parsed = urlsplit(url)
    if parsed.scheme != "https" or not parsed.hostname or parsed.username:
        raise ValueError("任务未返回有效的 HTTPS 视频地址")
    temporary = VIDEO.with_suffix(".mp4.part")
    try:
        with urlopen(url, timeout=60) as response:
            if urlsplit(response.geturl()).scheme != "https":
                raise ValueError("视频地址重定向到了非 HTTPS 链接")
            mime = response.headers.get_content_type()
            if mime not in {"video/mp4", "application/mp4", "application/octet-stream"}:
                raise ValueError(f"视频下载响应类型异常：{mime}")
            with temporary.open("wb") as output:
                shutil.copyfileobj(response, output)
        if not temporary.stat().st_size:
            raise ValueError("下载文件为空")
        temporary.replace(VIDEO)
    finally:
        temporary.unlink(missing_ok=True)


def download(token):
    task_id = STATE.read_text(encoding="utf-8").strip()
    if not task_id:
        raise ValueError(f"{STATE} 没有任务 ID")
    deadline = time.monotonic() + 600
    while time.monotonic() < deadline:
        task = task_request(token, task_id)
        status = task.get("status")
        print("任务状态:", status, flush=True)
        if status == "succeeded":
            url = (task.get("content") or {}).get("video_url")
            if not url:
                raise ValueError("任务成功，但没有 content.video_url")
            save_video(url)
            print("已保存:", VIDEO)
            return
        if status in {"failed", "cancelled", "canceled", "expired"}:
            raise ValueError(f"任务已结束：{status}。详情：{task.get('error', '')}")
        if status not in {"queued", "running"}:
            raise ValueError("未识别的任务状态，请查看控制台")
        time.sleep(min(5, max(0, deadline - time.monotonic())))
    raise TimeoutError("查询超时；再次运行 download 继续查询同一任务")


def main():
    args = sys.argv[1:]
    if not (len(args) == 2 and args[0] == "create" or args == ["download"]):
        raise ValueError("用法：seedance-25-product-video.py create request.json 或 download")
    token = os.environ.get("QUICKROUTER_API_KEY", "").strip()
    if not token:
        raise ValueError("请先设置 QUICKROUTER_API_KEY")
    if args[0] == "create":
        create(token, args[1])
    else:
        download(token)


if __name__ == "__main__":
    try:
        main()
    except HTTPError as exc:
        print(f"HTTP {exc.code}；请查看控制台。创建请求遇到超时或服务错误时，先确认是否已有任务。", file=sys.stderr)
        sys.exit(1)
    except (OSError, ValueError, URLError) as exc:
        safe_error = re.sub(r"https?://\S+|sk-[\w-]{12,}", "[已隐藏]", str(exc))
        print(safe_error, file=sys.stderr)
        sys.exit(1)
