#!/bin/bash
# Local setup only. Key handling belongs to hb_mine.py, not this launcher.
set -euo pipefail

fail() {
    printf 'HASHBATTLE: %s\n' "$1" >&2
    exit 1
}

script_dir="$(cd -- "${BASH_SOURCE[0]%/*}" && pwd -P)"
cd -- "$script_dir"

command -v python3 >/dev/null 2>&1 || fail 'Python 3.10+ is required. Install Python 3 and its venv support, then retry.'
python3 -c 'import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)' || fail 'Python 3.10+ is required. Upgrade python3, then retry.'
command -v gcc >/dev/null 2>&1 || fail 'GCC is required to build and verify the mining kernel. Install gcc (build-essential on Debian/Ubuntu), then retry.'
[[ -f hb_mine.py && -f requirements.txt ]] || fail 'Incomplete download. Extract the entire miner kit into one directory.'

venv_python="$script_dir/.venv/bin/python"
if [[ ! -x "$venv_python" ]]; then
    printf 'Creating the local .venv...\n' >&2
    python3 -m venv "$script_dir/.venv" || fail 'Could not create .venv. Install Python venv support (python3-venv on Debian/Ubuntu), then retry.'
fi
"$venv_python" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)' || fail 'The existing .venv needs Python 3.10+. Remove only .venv and retry with an updated python3.'

# Reuse an installed environment; install only when a pinned dependency is missing
# or its version has changed. No system pip, activation, or automatic pip upgrade.
if ! "$venv_python" -c '
import importlib.metadata
from pathlib import Path
import sys
try:
    for line in Path(sys.argv[1]).read_text().splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        name, expected = line.split("==", 1)
        if importlib.metadata.version(name) != expected:
            raise ValueError("dependency version mismatch")
    import eth_account
    import wgpu
except (ImportError, ValueError, importlib.metadata.PackageNotFoundError):
    sys.exit(1)
' "$script_dir/requirements.txt"; then
    printf 'Installing pinned miner dependencies into .venv...\n' >&2
    "$venv_python" -m pip install --disable-pip-version-check -r "$script_dir/requirements.txt" || fail 'Could not install miner dependencies. Check your package-index/network access and Python pip support, then retry.'
fi

exec "$venv_python" "$script_dir/hb_mine.py" "$@"
