"""Pinned official Google model bundles used for region analysis."""
import hashlib
import os
from pathlib import Path
from urllib.request import urlopen

DIRECTORY = Path(os.getenv("RETOUCH_MODELS", ".models")).resolve()
BASE = "https://storage.googleapis.com/mediapipe-models"
ASSETS = {
    "face.task": f"{BASE}/face_landmarker/face_landmarker/float16/1/face_landmarker.task",
    "parts.tflite": f"{BASE}/image_segmenter/selfie_multiclass_256x256/float32/1/selfie_multiclass_256x256.tflite",
}
CHECKSUMS = {
    "face.task": "64184e229b263107bc2b804c6625db1341ff2bb731874b0bcc2fe6544e0bc9ff",
    "parts.tflite": "c6748b1253a99067ef71f7e26ca71096cd449baefa8f101900ea23016507e0e0",
}


def install():
    DIRECTORY.mkdir(parents=True, exist_ok=True)
    for name, url in ASSETS.items():
        path = DIRECTORY / name
        if not path.exists():
            with urlopen(url, timeout=45) as response:
                payload = response.read(16 * 1024 * 1024 + 1)
            if not 1000 < len(payload) <= 16 * 1024 * 1024:
                raise ValueError(f"Unexpected model size: {name}")
            if hashlib.sha256(payload).hexdigest() != CHECKSUMS[name]:
                raise ValueError(f"Model integrity check failed: {name}")
            tmp = path.with_suffix(".download")
            tmp.write_bytes(payload)
            tmp.replace(path)
        actual = hashlib.sha256(path.read_bytes()).hexdigest()
        if actual != CHECKSUMS[name]:
            raise ValueError(f"Model integrity check failed: {name}")
        print(name, actual)


if __name__ == "__main__":
    install()

