const API_BASE_URL = String(__API_BASE__ || "").replace(/\/$/, "");
const FILE_BASE_URL = String(__UPLOAD_PUBLIC_BASE__ || __API_BASE__ || "").replace(/\/$/, "");

const INVALID_MEDIA_TEXT = new Set(["", "-", "null", "undefined", "/null", "/undefined", "[object object]"]);
const MEDIA_OBJECT_FIELDS = [
  "url",
  "publicUrl",
  "public_url",
  "originalUrl",
  "original_url",
  "downloadUrl",
  "download_url",
  "coverImageUrl",
  "cover_image_url",
  "coverUrl",
  "cover_url",
  "imageUrl",
  "image_url",
  "image",
  "src",
  "href",
  "fileUrl",
  "file_url",
  "webpUrl",
  "webp_url",
  "thumbnailUrl",
  "thumbnail_url",
  "poster",
  "path",
  "storagePath",
  "storage_path",
];

export function firstText(...values: unknown[]) {
  for (const value of values) {
    if (value === undefined || value === null) continue;
    const text = String(value).trim();
    if (text && !INVALID_MEDIA_TEXT.has(text.toLowerCase())) return text;
  }
  return "";
}

function assetBaseUrl() {
  if (!API_BASE_URL) return "";
  return API_BASE_URL.endsWith("/api") ? API_BASE_URL.slice(0, -4) : API_BASE_URL;
}

function fileBaseUrl() {
  if (!FILE_BASE_URL) return assetBaseUrl();
  return FILE_BASE_URL.endsWith("/api") ? FILE_BASE_URL.slice(0, -4) : FILE_BASE_URL;
}

function cleanMediaText(value: unknown) {
  if (value === undefined || value === null) return "";
  const text = String(value).trim().replace(/^['"]|['"]$/g, "");
  return INVALID_MEDIA_TEXT.has(text.toLowerCase()) ? "" : text;
}

function htmlImageSrc(value: string) {
  const match = value.match(/<img\b[^>]*\bsrc=["']([^"']+)["']/i);
  return match?.[1] ? cleanMediaText(match[1]) : "";
}

function objectStoragePath(value: string) {
  const match = value.match(/^s3:\/\/([^/]+)\/(.+)$/i);
  if (!match) return "";
  const bucket = encodeURIComponent(match[1]);
  const objectKey = match[2].split("/").map(encodeURIComponent).join("/");
  return `/files/${bucket}/${objectKey}`;
}

function joinFilePath(path: string) {
  const base = fileBaseUrl();
  if (!base) return path;
  try {
    const url = new URL(base);
    if (url.pathname === "/files" || url.pathname.startsWith("/files/")) {
      return `${url.origin}${path}`;
    }
  } catch {
    // Non-standard dev bases are still useful for local proxies.
  }
  return `${base}${path}`;
}

function legacyLocalUploadPath(value: string) {
  try {
    const url = new URL(value);
    const localHost = ["local", "host"].join("");
    const loopbackHost = ["127", "0", "0", "1"].join(".");
    const isLegacyLocal = (url.hostname === localHost || url.hostname === loopbackHost) && url.port === "8080";
    return isLegacyLocal && url.pathname.startsWith("/uploads/") ? `${url.pathname}${url.search}` : "";
  } catch {
    return "";
  }
}

function localPublicFilePath(value: string) {
  try {
    const url = new URL(value);
    const localHost = ["local", "host"].join("");
    const loopbackHost = ["127", "0", "0", "1"].join(".");
    const isLocal = url.hostname === localHost || url.hostname === loopbackHost;
    return isLocal && url.pathname.startsWith("/files/") ? `${url.pathname}${url.search}` : "";
  } catch {
    return "";
  }
}

export function mediaSource(value: unknown): string {
  return mediaSourceInner(value, 0);
}

function mediaSourceInner(value: unknown, depth: number): string {
  if (depth > 4) return "";
  if (Array.isArray(value)) {
    for (const item of value) {
      const source = mediaSourceInner(item, depth + 1);
      if (source) return source;
    }
    return "";
  }
  if (value && typeof value === "object") {
    const record = value as Record<string, unknown>;
    const bucket = cleanMediaText(record.bucket ?? record.bucketName ?? record.bucket_name);
    const objectKey = cleanMediaText(record.objectKey ?? record.object_key);
    if (bucket && objectKey) return `s3://${bucket}/${objectKey}`;
    for (const key of MEDIA_OBJECT_FIELDS) {
      const source = mediaSourceInner(record[key], depth + 1);
      if (source) return source;
    }
    return mediaSourceInner(record.metadata ?? record.data ?? record.response, depth + 1);
  }
  const text = cleanMediaText(value);
  if (!text) return "";
  if ((text.startsWith("{") || text.startsWith("[")) && depth < 4) {
    try {
      const source = mediaSourceInner(JSON.parse(text), depth + 1);
      if (source) return source;
    } catch {
      // Not JSON; keep the original text.
    }
  }
  return htmlImageSrc(text) || text;
}

export function resolveMediaUrl(value?: unknown, fallback = "") {
  const normalized = mediaSource(value);
  if (!normalized) return fallback;
  const storagePath = objectStoragePath(normalized);
  if (storagePath) return joinFilePath(storagePath);
  const legacyUploadPath = legacyLocalUploadPath(normalized);
  if (legacyUploadPath) return `${assetBaseUrl()}${legacyUploadPath}`;
  const localFilePath = localPublicFilePath(normalized);
  if (localFilePath) return joinFilePath(localFilePath);
  if (/^(https?:)?\/\//i.test(normalized) || normalized.startsWith("data:") || normalized.startsWith("blob:")) {
    return normalized.startsWith("//") ? `https:${normalized}` : normalized;
  }
  const path = normalized.startsWith("/") ? normalized : `/${normalized}`;
  if (path.startsWith("/files/")) return joinFilePath(path);
  if (/^\/(?:public|private)-media\//i.test(path)) return joinFilePath(`/files${path}`);
  if (path.startsWith("/uploads/")) return `${assetBaseUrl()}${path}`;
  return `${assetBaseUrl()}${path}`;
}

export function mediaUrlCandidates(...values: unknown[]) {
  const seen = new Set<string>();
  const urls: string[] = [];
  values.forEach((value) => {
    const url = resolveMediaUrl(value);
    if (!url || seen.has(url)) return;
    seen.add(url);
    urls.push(url);
  });
  return urls;
}

export function avatarUrl(value?: unknown, name = "XLH") {
  return resolveMediaUrl(value, `https://api.dicebear.com/9.x/initials/svg?seed=${encodeURIComponent(name || "XLH")}`);
}
