#!/usr/bin/env bash

# The remote-versions cache must not be shared between runs with and without
# the versions host: a list the host served lags new releases, and
# MISE_USE_VERSIONS_HOST=0 is how users go straight to the source (#13604).
#
# A local stand-in serves both the versions host and the GitHub API. The host
# only knows 0.0.10; GitHub already has 0.0.11.

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


def release(tag, date):
    return {
        "tag_name": tag,
        "draft": False,
        "prerelease": False,
        "created_at": date,
        "published_at": date,
        "assets": [
            {
                "name": "tak-x86_64-unknown-linux-gnu.tar.gz",
                "browser_download_url": f"https://github.com/jdx/tak/releases/download/{tag}/tak-x86_64-unknown-linux-gnu.tar.gz",
                "url": "https://api.github.com/repos/jdx/tak/releases/assets/1",
            }
        ],
    }


HOSTED = b'[versions."0.0.10"]\ncreated_at = 2026-01-01T00:00:00Z\n'
RELEASES = [
    release("v0.0.11", "2026-02-01T00:00:00Z"),
    release("v0.0.10", "2026-01-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/tak.toml":
            self.reply("application/toml", HOSTED)
        elif path == "/github/repos/jdx/tak/releases":
            self.reply("application/json", json.dumps(RELEASES).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", "https://api.github.com" = "http://127.0.0.1:$HTTP_PORT/github" }
EOF

# Warm the cache from the versions host.
assert "mise ls-remote tak" "0.0.10"

# With the host off, mise lists from GitHub instead of the cached host list.
assert "MISE_USE_VERSIONS_HOST=0 mise ls-remote tak" "0.0.10
0.0.11"

# The host-on entry is still cached separately.
assert "mise ls-remote tak" "0.0.10"
