#!/usr/bin/env python3
"""Type-check the shipped Lua with emmylua_check.

The checker is a pinned release, downloaded once into the cache directory and
verified against its checksum. .emmyrc.json at the repository root says which
diagnostics fail the check.
"""

import io
import hashlib
import os
import platform
import subprocess
import sys
import tarfile
import zipfile
from pathlib import Path
from urllib.request import urlopen

ROOT = Path(__file__).resolve().parents[3]
VERSION = "0.25.1"
URL = (
    "https://github.com/EmmyLuaLs/emmylua-analyzer-rust/releases/download/"
    f"{VERSION}/{{asset}}"
)
ASSETS = {
    ("Linux", "x86_64"): (
        "emmylua_check-linux-musl.tar.gz",
        "eb6fda391d72395bc665bab0f5777e72feebfe3f7f513332baab7458ecdb66a1",
    ),
    ("Darwin", "arm64"): (
        "emmylua_check-darwin-arm64.tar.gz",
        "eeaad59d173cb8d7cb0fe778936d7b584fe114a3eb46587ef3e4aec24b605af4",
    ),
    ("Darwin", "x86_64"): (
        "emmylua_check-darwin-x64.tar.gz",
        "e91fe82c361d8dece8e2ce9aeb2313b8809b4714f72bbbeab5a27e754d8de2c6",
    ),
    ("Windows", "AMD64"): (
        "emmylua_check-win32-x64.zip",
        "577982e68d925972d8ae35f54b5f384ad77a84a2e31e340bd663d1efd2ef5983",
    ),
}
SOURCES = ["src/lua", "data/trx/ship"]


def cache_dir() -> Path:
    base = os.environ.get("PREK_HOME") or os.environ.get("XDG_CACHE_HOME")
    if base is None:
        base = Path.home() / ".cache"
    return Path(base) / f"trx-emmylua-{VERSION}"


def checker() -> Path:
    key = (platform.system(), platform.machine())
    if key not in ASSETS:
        sys.exit(f"emmylua_check has no pinned build for {key[0]} {key[1]}")
    asset, digest = ASSETS[key]
    binary = cache_dir() / (
        "emmylua_check.exe" if asset.endswith(".zip") else "emmylua_check"
    )
    if binary.is_file():
        return binary

    with urlopen(URL.format(asset=asset)) as response:
        data = response.read()
    if hashlib.sha256(data).hexdigest() != digest:
        sys.exit(f"{asset} does not match its pinned checksum")
    binary.parent.mkdir(parents=True, exist_ok=True)
    if asset.endswith(".zip"):
        with zipfile.ZipFile(io.BytesIO(data)) as archive:
            binary.write_bytes(archive.read(binary.name))
    else:
        with tarfile.open(fileobj=io.BytesIO(data)) as archive:
            member = archive.extractfile(f"./{binary.name}")
            binary.write_bytes(member.read())
    binary.chmod(0o755)
    return binary


def main() -> int:
    command = [
        str(checker()),
        "--config",
        ".emmyrc.json",
        "--severity",
        "error",
        *SOURCES,
    ]
    if os.environ.get("GITHUB_ACTIONS") == "true":
        command[1:1] = ["--output-format", "github"]
    return subprocess.run(command, cwd=ROOT).returncode


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