#!/usr/bin/env python3
"""Generate one Native Seedance 2.5 test video and print its result URL.

Python 3.8+ and curl; no third-party Python packages.
Run again from the same folder to resume this test, never to create a replacement.
"""

import fcntl
import getpass
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import time
import uuid
from urllib.parse import urlparse

BASE_URL = "https://ai-api.lightspeedfuture.com"
POLL_SECONDS = 30
WAIT_SECONDS = 1800
PROMPT = "A red ceramic cup on a wooden table in soft daylight, with a slow smooth camera move."
ALIAS_RE = re.compile(r"lsf-seedance-2\.5-(?!native-flash(?:-|$)|flash(?:-|$)|production(?:-|$))[A-Za-z0-9][A-Za-z0-9_-]*\Z")
TASK_RE = re.compile(r"[A-Za-z0-9_-]{1,256}\Z")


class StarterError(Exception):
    pass


def save_json(path, value):
    temp = path.with_name(path.name + ".tmp")
    fd = os.open(str(temp), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w", encoding="utf-8") as out:
        json.dump(value, out, indent=2, ensure_ascii=False)
        out.write("\n")
        out.flush()
        os.fsync(out.fileno())
    os.replace(str(temp), str(path))


def read_json(path):
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except (OSError, ValueError) as exc:
        raise StarterError("Cannot read the saved test. Keep the lsf-first-video folder and contact LSF.") from exc


def request_json(method, route, key, folder, body=None):
    """Use curl's normal HTTPS transport; no POST retries or redirects."""
    if not route.startswith("/v1/videos") or "\n" in route or "\r" in route:
        raise StarterError("Invalid request path.")
    safe_key = key.replace("\\", "\\\\").replace('"', '\\"')
    config = 'header = "Authorization: Bearer ' + safe_key + '"\n'
    config += 'header = "Content-Type: application/json"\n'
    output = folder / "last-http-response.json"
    args = ["curl", "--silent", "--show-error", "--proto", "=https",
            "--connect-timeout", "15", "--max-time", "60",
            "--max-filesize", "2097152", "--request", method,
            "--url", BASE_URL + route, "--config", "-",
            "--output", str(output), "--write-out", "%{http_code}"]
    if body is not None:
        request_file = folder / "request.json"
        save_json(request_file, body)
        args += ["--data-binary", "@" + str(request_file)]
    try:
        completed = subprocess.run(args, input=config, text=True,
                                   capture_output=True, timeout=75)
    except (OSError, subprocess.TimeoutExpired) as exc:
        raise StarterError("The connection was interrupted.") from exc
    if output.exists():
        os.chmod(str(output), 0o600)
    if completed.returncode != 0:
        raise StarterError("The connection did not complete (curl code %s)." % completed.returncode)
    try:
        status = int(completed.stdout.strip())
        if output.stat().st_size > 2097152:
            raise ValueError("response too large")
        payload = json.loads(output.read_text(encoding="utf-8"))
    except (ValueError, OSError) as exc:
        raise StarterError("The server returned an unreadable response.") from exc
    if not isinstance(payload, dict):
        raise StarterError("The server returned an unexpected response.")
    return status, payload


def api_error(status, payload, key):
    error = payload.get("error", {})
    message = error.get("message", "") if isinstance(error, dict) else str(error)
    message = " ".join(str(message).replace(key, "[REDACTED]").split())[:300]
    return "HTTP %s%s" % (status, ": " + message if message else "")


def run_test(folder, key, alias, transport=request_json, sleep=time.sleep,
             clock=time.monotonic, wait_seconds=WAIT_SECONDS):
    journal = folder / "test.json"
    if journal.exists():
        state = read_json(journal)
        task_id = state.get("task_id")
        if not task_id:
            raise StarterError("The earlier submission has no confirmed task ID. No new video was submitted. "
                               "Send LSF the request ID: " + str(state.get("request_id", "unknown")))
        print("Resuming your saved test. No new generation will be submitted.")
    else:
        if not ALIAS_RE.fullmatch(alias):
            raise StarterError("Paste the Native Seedance 2.5 model alias supplied by LSF, "
                               "for example lsf-seedance-2.5-youraccount. This starter does not use a Flash or Production alias.")
        request_id = "lsf-first-video-" + uuid.uuid4().hex
        body = {"model": alias, "prompt": PROMPT, "metadata": {
            "duration": 5, "resolution": "720p", "ratio": "16:9",
            "output_format": "mp4", "generate_audio": False,
            "client_request_id": request_id}}
        state = {"version": 1, "model": alias, "request_id": request_id,
                 "key_reference": hashlib.sha256(key.encode()).hexdigest()[:16],
                 "phase": "submission_started", "request": body}
        # Save before sending. An interrupted POST must never become another POST.
        save_json(journal, state)
        print("Submitting one Native Seedance 2.5 video: 5 seconds, 720p, 16:9, MP4, no audio.")
        try:
            status, result = transport("POST", "/v1/videos", key, folder, body)
        except StarterError as exc:
            raise StarterError(str(exc) + " Submission may have been accepted. Do not start a replacement. "
                               "Send LSF the request ID: " + request_id) from exc
        save_json(folder / "submit-response.json", result)
        task_id = result.get("task_id") or result.get("id")
        if not (200 <= status < 300 and isinstance(task_id, str) and TASK_RE.fullmatch(task_id)):
            state["phase"] = "submission_needs_help"
            state["http_status"] = status
            save_json(journal, state)
            raise StarterError(api_error(status, result, key) + ". No automatic retry. "
                               "Send LSF the request ID: " + request_id)
        state.update(task_id=task_id, phase="accepted")
        save_json(journal, state)
    if not isinstance(task_id, str) or not TASK_RE.fullmatch(task_id):
        raise StarterError("The saved task ID is invalid. Contact LSF; no new video was submitted.")
    print("Task: " + task_id)
    print("Waiting for your video. You can stop and run this command again from the same folder.")
    started = clock()
    while clock() - started < wait_seconds:
        try:
            status, result = transport("GET", "/v1/videos/" + task_id, key, folder)
        except StarterError:
            print("Connection interrupted. Checking the same task again in 30 seconds...")
            sleep(POLL_SECONDS)
            continue
        if status == 429 or status >= 500:
            print("Status check temporarily unavailable. Checking the same task again in 30 seconds...")
            sleep(POLL_SECONDS)
            continue
        if status != 200:
            raise StarterError(api_error(status, result, key) + ". Your task ID is saved; no new video was submitted.")
        reported_id = result.get("task_id") or result.get("id")
        if reported_id is not None and reported_id != task_id:
            raise StarterError("The response did not match your task ID. Contact LSF.")
        save_json(folder / "response.json", result)
        current = str(result.get("status", "unknown"))
        if current == "completed":
            metadata = result.get("metadata") or {}
            url = metadata.get("url") if isinstance(metadata, dict) else None
            parsed = urlparse(url) if isinstance(url, str) else None
            if not parsed or parsed.scheme != "https" or not parsed.netloc:
                raise StarterError("The task completed but no HTTPS video URL was returned. "
                                   "Send LSF your task ID; no replacement was submitted.")
            state.update(phase="completed")
            save_json(journal, state)
            fd = os.open(str(folder / "video_url.txt"), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
            with os.fdopen(fd, "w", encoding="utf-8") as out:
                out.write(url + "\n")
            print("\nYour video is ready:\n\n" + url)
            print("\nOpen this link in your browser and save the video.")
            print("Full API response: " + str(folder / "response.json"))
            return url
        if current in ("failed", "expired"):
            state.update(phase=current)
            save_json(journal, state)
            raise StarterError("Task " + current + ". " + api_error(status, result, key) +
                               ". Contact LSF with the task ID above; no replacement was submitted.")
        if current not in ("queued", "pending", "processing", "in_progress", "running"):
            raise StarterError("Unexpected task status. Keep response.json and contact LSF with the task ID.")
        print("Generating... checking again in 30 seconds.")
        sleep(POLL_SECONDS)
    raise StarterError("The video is still processing. Run the same command from the same folder later "
                       "to continue checking this task. No replacement was submitted.")


def main():
    if not shutil.which("curl"):
        print("curl is required. Contact LSF for help with this computer.", file=sys.stderr)
        return 1
    folder = Path.cwd() / "lsf-first-video"
    folder.mkdir(mode=0o700, exist_ok=True)
    lock = folder / "running.lock"
    lock_fd = os.open(str(lock), os.O_CREAT | os.O_RDWR, 0o600)
    try:
        fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        os.close(lock_fd)
        print("This test is already open. Use the original Terminal window.", file=sys.stderr)
        return 1
    try:
        print("LSF first video test\nYour API key stays on this computer and is sent only to the LSF API.")
        key = getpass.getpass("Paste your LSF API key (hidden), then press Enter: ").strip()
        if not key or any(c in key for c in "\r\n\x00"):
            raise StarterError("The API key is empty or invalid. No video was submitted.")
        alias = ""
        if not (folder / "test.json").exists():
            alias = input("Paste your Native Seedance 2.5 model alias, then press Enter: ").strip()
        run_test(folder, key, alias)
        return 0
    except KeyboardInterrupt:
        print("\nStopped locally. Keep the lsf-first-video folder; run this command again to resume the saved task.")
        return 130
    except (StarterError, OSError) as exc:
        print("\n" + str(exc), file=sys.stderr)
        print("Help: info@lightspeedfuture.com. Share your task/request ID, never your API key.", file=sys.stderr)
        return 1
    finally:
        # The OS releases this lock even if Terminal closes unexpectedly.
        # Keep the file: unlinking it could let two processes lock different files.
        os.close(lock_fd)


if __name__ == "__main__":
    sys.exit(main())
