"""Prepare a pinned, locally loadable Mongolian CTranslate2 model."""
import argparse
import json
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

REPO = "Cafet/whisper-small-mongolian"
REVISION = "d54c63a518d6dea7ab54a27c83d0b6b52bea3e9d"


def prepare(destination: Path) -> None:
    from huggingface_hub import snapshot_download
    from transformers import AutoTokenizer

    destination.parent.mkdir(parents=True, exist_ok=True)
    if destination.exists():
        details = destination / "source.json"
        if details.is_file() and json.loads(details.read_text()).get("revision") == REVISION and all(
            (destination / f).is_file() for f in ("model.bin", "tokenizer.json", "preprocessor_config.json")
        ):
            print("Монгол загвар бэлэн байна.")
            return
        raise SystemExit("Зорилтот хавтас өмнө нь үүссэн байна. Хоосон шинэ хаяг сонгоно уу.")
    source = Path(snapshot_download(REPO, revision=REVISION, allow_patterns=[
        "*.json", "merges.txt", "*.safetensors", "README.md", "LICENSE*",
    ]))
    with tempfile.TemporaryDirectory(prefix=".prepare-", dir=destination.parent) as work:
        out = Path(work) / "model"
        converter = str(Path(sys.executable).with_name("ct2-transformers-converter"))
        subprocess.run([converter, "--model", str(source), "--output_dir", str(out),
                        "--copy_files", "preprocessor_config.json", "--quantization", "int8"], check=True)
        tokenizer = AutoTokenizer.from_pretrained(source, local_files_only=True, use_fast=True, trust_remote_code=False)
        tokenizer.save_pretrained(out)
        for name in ("tokenizer.json", "model.bin", "preprocessor_config.json"):
            if not (out / name).is_file():
                raise RuntimeError(f"Хувиргасан загварт {name} алга.")
        for path in [source / "README.md", *source.glob("LICENSE*")]:
            if path.is_file():
                shutil.copyfile(path, out / ("UPSTREAM-" + path.name))
        (out / "source.json").write_text(json.dumps({"repo": REPO, "revision": REVISION, "quantization": "int8"},
                                                   indent=2) + "\n")
        out.rename(destination)
    print(f"Монгол загварыг бэлдлээ. {destination}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", type=Path, default=Path("/models/whisper-small-mn-ct2"))
    prepare(parser.parse_args().output)
