import { DEFAULT_RELEASE_OWNER, DEFAULT_RELEASE_REPO } from "./release-config.js";

export async function resolveVersion(requestedVersion) {
  if (requestedVersion && requestedVersion !== "latest") {
    return requestedVersion;
  }

  const apiUrl = `https://api.github.com/repos/${DEFAULT_RELEASE_OWNER}/${DEFAULT_RELEASE_REPO}/releases/latest`;
  const response = await fetch(apiUrl, {
    headers: {
      "User-Agent": "codex-harness-cli"
    }
  });

  if (!response.ok) {
    throw new Error(`Failed to resolve latest release version: ${response.status} ${response.statusText}`);
  }

  const json = await response.json();
  const tag = String(json.tag_name || "").trim();
  if (!tag) {
    throw new Error("Latest release did not include tag_name.");
  }

  return tag.startsWith("v") ? tag.slice(1) : tag;
}
