// Responsibility: explicit v0.3 CaseRun runtime endpoint resolution.

import { cliError, text } from "./hwlab-caserun-evidence.ts";
import type { CaseContext } from "./hwlab-caserun-shared.ts";

const REMOVED_V02_API_URL = "http://74.48.78.17:19667";
const REMOVED_V02_WEB_URL = "http://74.48.78.17:19666";

export function webUrlFrom(context: CaseContext) {
  const value = text(context.parsed.baseUrl ?? context.parsed.webUrl ?? context.env.HWLAB_RUNTIME_WEB_URL ?? context.env.HWLAB_CLOUD_WEB_URL);
  if (!value) {
    throw cliError("caserun_runtime_web_url_required", "CaseRun v0.3 requires an explicit runtime Web URL from --base-url, --web-url, HWLAB_RUNTIME_WEB_URL, or HWLAB_CLOUD_WEB_URL; case runtime.webUrl fallback is removed.", {
      allowed: ["--base-url", "--web-url", "HWLAB_RUNTIME_WEB_URL", "HWLAB_CLOUD_WEB_URL"],
      removedFallbacks: ["case.runtime.webUrl", REMOVED_V02_WEB_URL],
    });
  }
  return rejectRemovedV02RuntimeUrl(value, "web");
}

export function apiUrlFrom(context: CaseContext) {
  const value = text(context.parsed.apiUrl ?? context.parsed.apiBaseUrl ?? context.parsed.runtimeApiUrl ?? context.env.HWLAB_RUNTIME_API_URL ?? context.env.HWLAB_CASERUN_RUNTIME_API_URL);
  if (!value) {
    throw cliError("caserun_runtime_api_url_required", "CaseRun v0.3 requires an explicit runtime API URL from --api-url, --api-base-url, --runtime-api-url, HWLAB_RUNTIME_API_URL, or HWLAB_CASERUN_RUNTIME_API_URL; case runtime.apiUrl fallback is removed.", {
      allowed: ["--api-url", "--api-base-url", "--runtime-api-url", "HWLAB_RUNTIME_API_URL", "HWLAB_CASERUN_RUNTIME_API_URL"],
      removedFallbacks: ["case.runtime.apiUrl", REMOVED_V02_API_URL],
    });
  }
  return rejectRemovedV02RuntimeUrl(value, "api");
}

function rejectRemovedV02RuntimeUrl(value: string, kind: "api" | "web") {
  const normalized = value.replace(/\/+$/u, "");
  const removed = kind === "web" ? REMOVED_V02_WEB_URL : REMOVED_V02_API_URL;
  if (normalized === removed) throw cliError("caserun_removed_v02_runtime_url", `CaseRun v0.3 does not support the removed v0.2 ${kind} runtime URL`, { kind, url: normalized });
  return normalized;
}
