"""Run four independent modality checks against the credited public Space."""

import argparse
from datetime import datetime, timezone
import json
from pathlib import Path
import shutil
import time
from urllib.request import urlopen

from gradio_client import Client, handle_file


BACKEND = "https://nemoyu-nlp-chapter6-nextgpt.hf.space"
ROOT = Path(__file__).resolve().parents[1]


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output-dir", type=Path, default=ROOT / "evidence" / "public-demo")
    options = parser.parse_args()
    options.output_dir.mkdir(parents=True, exist_ok=True)
    with urlopen(f"{BACKEND}/config", timeout=30) as response:
        config = json.load(response)
    examples = next(
        component["props"]["samples"]
        for component in config["components"]
        if component["type"] == "dataset"
    )
    birthday_video = examples[1][2]["video"]["url"]
    blossoms = examples[2][1]["url"]
    dog = ROOT / "evidence" / "real-inference" / "input.jpg"
    cases = [
        ("image-to-audio", "What animal is shown? Generate the sound it makes.",
         str(dog), None, ["音频"]),
        ("video-to-audio", "What is happening in this video? Generate the sound of people cheering.",
         None, birthday_video, ["音频"]),
        ("image-to-image-video", "Describe the scene and generate a similar image and short video.",
         blossoms, None, ["图片", "视频"]),
        ("text-to-all", "Describe a bird in a forest. Generate a picture, a short video, and birdsong.",
         None, None, ["图片", "音频", "视频"]),
    ]
    for name, prompt, image, video, requested in cases:
        directory = options.output_dir / name
        directory.mkdir(exist_ok=True)
        start = time.monotonic()
        record = {
            "backend": BACKEND,
            "verified_at_utc": datetime.now(timezone.utc).isoformat(),
            "prompt": prompt,
            "image": "evidence/real-inference/input.jpg" if image == str(dog) else image,
            "video": video,
            "requested": requested,
            "parameters": {
                "max_new_tokens": 80, "temperature": 1.0, "top_p": 0.01,
                "image_steps": 10, "audio_steps": 10, "video_steps": 8,
                "video_frames": 8, "seed": 13,
            },
        }
        try:
            client = Client(BACKEND, verbose=False)
            job = client.submit(
                prompt, handle_file(image) if image else None, None,
                {"video": handle_file(video), "subtitles": None} if video else None,
                **record["parameters"], output_modalities=requested, api_name="/chat",
            )
            conversation, gallery, audio, movie, downloads, *_ = job.result(timeout=240)
            files = []
            for source in downloads or []:
                path = Path(source)
                shutil.copyfile(path, directory / path.name)
                files.append({"name": path.name, "bytes": path.stat().st_size})
            for turn in conversation:
                for message in turn:
                    if isinstance(message, dict) and message.get("file"):
                        message["file"] = Path(message["file"]).name
            record.update(
                response=conversation, files=files,
                returned={"image": bool(gallery), "audio": bool(audio), "video": bool(movie)},
            )
        except Exception as exc:
            record["error"] = str(exc)
        record["elapsed_seconds"] = round(time.monotonic() - start, 2)
        (directory / "result.json").write_text(
            json.dumps(record, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
        )
        print(name, record.get("returned", record.get("error")), flush=True)


if __name__ == "__main__":
    main()
