#!/usr/bin/env bash

# Every backend's version list may come from the versions host, not only the
# source-hosting ones. A tool whose source settings redirect it somewhere else
# must still list from that source, since the host's list describes the
# public one.
#
# A local stand-in serves both the versions host and a PyPI-style index. The
# host only knows 1.0.0; the index also has 1.1.0.

start_http_server --handler - <<'PY'
import http.server
import json

HOSTED = b'[versions."1.0.0"]\ncreated_at = 2026-01-01T00:00:00Z\n'
FILE = {"upload_time_iso_8601": "2026-01-01T00:00:00Z", "yanked": False}
INDEX = {
    "releases": {
        "1.0.0": [FILE],
        "1.1.0": [dict(FILE, upload_time_iso_8601="2026-02-01T00:00:00Z")],
    }
}


class Handler(http.server.BaseHTTPRequestHandler):
    def reply(self, content_type, body):
        self.send_response(200)
        self.send_header("Content-Type", content_type)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        path = self.path.split("?")[0]
        if path == "/versions/data/ansible-core.toml":
            self.reply("application/toml", HOSTED)
        elif path == "/pypi/ansible-core/json":
            self.reply("application/json", json.dumps(INDEX).encode())
        else:
            self.send_response(404)
            self.end_headers()

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

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

# A pipx tool, which the host once skipped, reads the host's list.
assert "mise ls-remote ansible-core" "1.0.0"

# Redirecting the index makes the host's list wrong for it: list from the index.
assert "MISE_PYPI_REGISTRY_URL=http://127.0.0.1:$HTTP_PORT/pypi/{}/json mise ls-remote ansible-core" "1.0.0
1.1.0"

# The redirected list does not replace the default entry.
assert "mise ls-remote ansible-core" "1.0.0"
