#!/usr/bin/env bash

# Resolving pipx `latest` reads the package's latest release from the
# registry. A command that only needs a matching version keeps that answer
# for the tool's release-age window when it is dated, as it keeps a dated
# version list (see test_version_list_release_age_window), instead of
# fetching the registry document again after fetch_remote_versions_cache (1h).
#
# A local stand-in serves the registry and logs each request.

mkdir -p srv/pypi/black
cat >srv/pypi/black/json <<'JSON'
{
  "releases": {
    "25.1.0": [{ "upload_time_iso_8601": "2025-01-01T00:00:00Z", "yanked": false }],
    "25.9.0": [{ "upload_time_iso_8601": "2025-09-01T00:00:00Z", "yanked": false }]
  }
}
JSON

start_http_server --handler - <<'PY'
import http.server
from pathlib import Path


class Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        path = self.path.split("?")[0]
        with open("requests.log", "a") as log:
            log.write(f"{path}\n")
        file = Path("srv") / path.lstrip("/")
        if not file.is_file():
            self.send_response(404)
            self.end_headers()
            return
        body = file.read_bytes()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, format, *args):
        pass
PY

cat >mise.toml <<TOML
[settings]
pypi.registry_url = "http://127.0.0.1:$HTTP_PORT/pypi/{}/json"
url_replacements = { "https://mise-versions.jdx.dev" = "http://127.0.0.1:$HTTP_PORT/versions" }

[tools]
"pipx:black" = "latest"
TOML

backdate_latest() {
  find "$MISE_CACHE_DIR" -name 'latest_version_info_*' -exec touch -d "$1" {} +
}

: >requests.log
assert_contains "mise install --dry-run 2>&1" "pipx:black@25.9.0"
assert "cat requests.log" "/pypi/black/json"

# Two hours later, install still uses the cached answer.
backdate_latest "2 hours ago"
: >requests.log
assert_contains "mise install --dry-run 2>&1" "pipx:black@25.9.0"
assert_empty "cat requests.log"

# Unless fetch_remote_versions_cache is set, which then applies as set.
: >requests.log
assert_contains "MISE_FETCH_REMOTE_VERSIONS_CACHE=1h mise install --dry-run 2>&1" "pipx:black@25.9.0"
assert "cat requests.log" "/pypi/black/json"

# Past 24 hours, install reads the registry again.
backdate_latest "25 hours ago"
: >requests.log
assert_contains "mise install --dry-run 2>&1" "pipx:black@25.9.0"
assert "cat requests.log" "/pypi/black/json"

# outdated reports what is newest, so it reads the registry after 1h.
backdate_latest "2 hours ago"
: >requests.log
assert_succeed "mise outdated"
assert "cat requests.log" "/pypi/black/json"
