#!/usr/bin/env python3
"""Explicit offline speech asset installation. Never called by Cast startup."""
import argparse
import hashlib
import json
import os
from pathlib import Path
from urllib.parse import urlsplit
import urllib.request

ASSETS = {
    "tiny.en": {
        "license_file": "model-licenses/Whisper-model-MIT.txt",
        "license_sha256": "b5d65a59060e68c4ff940e1eddfa6f94b2d68fdf58ed7f4dd57721c997e35e9d",
        "url": "https://huggingface.co/ggerganov/whisper.cpp/resolve/c521a4b02f422512d734391fdf08bb08c0862f68/ggml-tiny.en.bin",
        "sha256": "921e4cf8686fdd993dcd081a5da5b6c365bfde1162e72b08d75ac75289920b1f",
        "bytes": 77704715,
        "license": "MIT",
        "verification_source": "https://huggingface.co/ggerganov/whisper.cpp/blob/c521a4b02f422512d734391fdf08bb08c0862f68/ggml-tiny.en.bin",
    },
    "tiny-q5_1": {
        "license_file": "model-licenses/Whisper-model-MIT.txt",
        "license_sha256": "b5d65a59060e68c4ff940e1eddfa6f94b2d68fdf58ed7f4dd57721c997e35e9d",
        "url": "https://huggingface.co/ggerganov/whisper.cpp/resolve/c521a4b02f422512d734391fdf08bb08c0862f68/ggml-tiny-q5_1.bin",
        "sha256": "818710568da3ca15689e31a743197b520007872ff9576237bda97bd1b469c3d7",
        "bytes": 32152673,
        "license": "MIT",
        "verification_source": "https://huggingface.co/ggerganov/whisper.cpp/blob/c521a4b02f422512d734391fdf08bb08c0862f68/ggml-tiny-q5_1.bin",
    },
    "tiny": {
        "license_file": "model-licenses/Whisper-model-MIT.txt",
        "license_sha256": "b5d65a59060e68c4ff940e1eddfa6f94b2d68fdf58ed7f4dd57721c997e35e9d",
        "url": "https://huggingface.co/ggerganov/whisper.cpp/resolve/c521a4b02f422512d734391fdf08bb08c0862f68/ggml-tiny.bin",
        "sha256": "be07e048e1e599ad46341c8d2a135645097a538221678b7acdd1b1919c6e1b21",
        "bytes": 77691713,
        "license": "MIT",
        "verification_source": "https://huggingface.co/ggerganov/whisper.cpp/blob/c521a4b02f422512d734391fdf08bb08c0862f68/ggml-tiny.bin",
    },
    "base": {
        "license_file": "model-licenses/Whisper-model-MIT.txt",
        "license_sha256": "b5d65a59060e68c4ff940e1eddfa6f94b2d68fdf58ed7f4dd57721c997e35e9d",
        "url": "https://huggingface.co/ggerganov/whisper.cpp/resolve/c521a4b02f422512d734391fdf08bb08c0862f68/ggml-base.bin",
        "sha256": "60ed5bc3dd14eea856493d334349b405782ddcaf0028d4b5df4088345fba2efe",
        "bytes": 147951465,
        "license": "MIT",
        "verification_source": "https://huggingface.co/ggerganov/whisper.cpp/blob/c521a4b02f422512d734391fdf08bb08c0862f68/ggml-base.bin",
    },
    "base-q5_1": {
        "license_file": "model-licenses/Whisper-model-MIT.txt",
        "license_sha256": "b5d65a59060e68c4ff940e1eddfa6f94b2d68fdf58ed7f4dd57721c997e35e9d",
        "url": "https://huggingface.co/ggerganov/whisper.cpp/resolve/c521a4b02f422512d734391fdf08bb08c0862f68/ggml-base-q5_1.bin",
        "sha256": "422f1ae452ade6f30a004d7e5c6a43195e4433bc370bf23fac9cc591f01a8898",
        "bytes": 59707625,
        "license": "MIT",
        "verification_source": "https://huggingface.co/ggerganov/whisper.cpp/blob/c521a4b02f422512d734391fdf08bb08c0862f68/ggml-base-q5_1.bin",
    },
    "small-q5_1": {
        "license_file": "model-licenses/Whisper-model-MIT.txt",
        "license_sha256": "b5d65a59060e68c4ff940e1eddfa6f94b2d68fdf58ed7f4dd57721c997e35e9d",
        "url": "https://huggingface.co/ggerganov/whisper.cpp/resolve/c521a4b02f422512d734391fdf08bb08c0862f68/ggml-small-q5_1.bin",
        "sha256": "ae85e4a935d7a567bd102fe55afc16bb595bdb618e11b2fc7591bc08120411bb",
        "bytes": 190085487,
        "license": "MIT",
        "verification_source": "https://huggingface.co/ggerganov/whisper.cpp/blob/c521a4b02f422512d734391fdf08bb08c0862f68/ggml-small-q5_1.bin",
    },
    "silero-v6.2": {
        "license_file": "model-licenses/Silero-model-MIT.txt",
        "license_sha256": "2e63e9a38b6e8fc0c7bc37ce174caca1862870856c6daf5697cfb785e925520b",
        "url": "https://huggingface.co/ggml-org/whisper-vad/resolve/9ffd54a1e1ee413ddf265af9913beaf518d1639b/ggml-silero-v6.2.0.bin",
        "sha256": "2aa269b785eeb53a82983a20501ddf7c1d9c48e33ab63a41391ac6c9f7fb6987",
        "bytes": 885098,
        "license": "MIT",
        "verification_source": "https://huggingface.co/ggml-org/whisper-vad/commit/9ffd54a1e1ee413ddf265af9913beaf518d1639b",
    }
}


def _digest(path):
    with path.open("rb") as source:
        return hashlib.file_digest(source, "sha256").hexdigest()


def model_directory():
    """Match the app's per-user model directory; relative XDG paths are ignored."""
    data = os.environ.get("XDG_DATA_HOME", "")
    return (Path(data) if Path(data).is_absolute() else Path.home() / ".local/share") / "cast/models"


def download(asset, output):
    """Install only verified bytes, preserving any existing file or symlink."""
    output = output.absolute()
    if output.exists() or output.is_symlink():
        if (not output.is_symlink() and output.is_file() and
                output.stat().st_size == asset["bytes"] and
                _digest(output) == asset["sha256"]):
            print("Already installed verified local model: " + str(output))
            return
        raise ValueError("output already exists; choose a new path, existing models are never replaced")
    output.parent.mkdir(parents=True, exist_ok=True)
    temporary = output.with_name(output.name + ".partial")
    fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
    completed = False
    try:
        digest = hashlib.sha256()
        total = 0
        with os.fdopen(fd, "wb") as target:
            request = urllib.request.Request(asset["url"], headers={
                "User-Agent": "SuperScreencast-model-installer/1.0"})
            with urllib.request.urlopen(request, timeout=30) as source:
                if urlsplit(source.url).scheme != "https":
                    raise ValueError("HTTPS redirect required")
                while chunk := source.read(65536):
                    total += len(chunk)
                    if total > asset["bytes"]:
                        raise ValueError("asset exceeds pinned size")
                    target.write(chunk)
                    digest.update(chunk)
            target.flush()
            os.fsync(target.fileno())
        if total != asset["bytes"] or digest.hexdigest() != asset["sha256"]:
            raise ValueError("asset differs from pinned official SHA256/size")
        os.link(temporary, output, follow_symlinks=False)
        completed = True
        print("Installed verified local model: " + str(output))
    finally:
        temporary.unlink(missing_ok=True)
    if completed:
        directory = os.open(output.parent, os.O_RDONLY | os.O_DIRECTORY)
        try:
            os.fsync(directory)
        finally:
            os.close(directory)


def installed_assets():
    # The installation kit supplies immutable CDN URLs for reviewed models.
    # Source/developer use retains the upstream, revision-pinned catalog.
    catalog = Path(__file__).resolve().parents[1] / "share/cast-pro/speech/inventory.json"
    assets = {name: dict(record) for name, record in ASSETS.items()}
    if catalog.is_file():
        inventory = json.loads(catalog.read_text())
        if inventory.get("schema") != 1:
            raise ValueError("unsupported installed model catalog")
        for name, record in inventory["assets"].items():
            if name not in assets or any(record[field] != assets[name][field]
                                         for field in ("sha256", "bytes", "license_sha256")):
                raise ValueError("installed model catalog differs from pinned model identity")
            parsed = urlsplit(record["url"])
            if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password:
                raise ValueError("model download requires HTTPS without credentials")
            assets[name]["url"] = record["url"]
    return assets


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("asset", choices=ASSETS, nargs="?")
    parser.add_argument("--list", action="store_true", help="list available models without downloading")
    parser.add_argument("--output", type=Path, help="default: per-user cast/models/NAME.bin")
    parser.add_argument("--download", action="store_true", help="explicitly enable HTTPS download")
    args = parser.parse_args()
    assets = installed_assets()
    if args.list:
        for name, asset in assets.items():
            print(f"{name:16} {asset['bytes'] / 1000000:6.1f} MB  {asset['license']}")
        return
    if args.asset is None:
        parser.error("choose a model or use --list")
    asset = assets[args.asset]
    if not args.download:
        print(json.dumps(asset, indent=2))
        return
    download(asset, args.output or model_directory() / (args.asset + ".bin"))


if __name__ == "__main__":
    try:
        main()
    except (OSError, ValueError) as error:
        raise SystemExit("speech-assets: " + str(error))
