import { readFileSync, existsSync } from "node:fs";
import { join } from "node:path";
import { getConfig } from "../../../config.js";
import { createLogger } from "../../../logger.js";
const log = createLogger("search");
function isValidUrl(raw) {
  try {
    const u = new URL(raw);
    return u.protocol === "http:" || u.protocol === "https:";
  } catch {
    return false;
  }
}
function loadEnvFeeds() {
  const raw = process.env.WIGOLO_RSS_FEEDS;
  if (!raw) return [];
  const out = [];
  for (const piece of raw.split(",")) {
    const url = piece.trim();
    if (!url) continue;
    if (!isValidUrl(url)) {
      log.warn("invalid RSS feed URL in env", { url });
      continue;
    }
    out.push({ url });
  }
  return out;
}
function loadFileFeeds(dataDir) {
  const path = join(dataDir, "rss-feeds.json");
  if (!existsSync(path)) return [];
  let raw;
  try {
    raw = readFileSync(path, "utf8");
  } catch (err) {
    log.warn("could not read rss-feeds.json", {
      path,
      error: err instanceof Error ? err.message : String(err)
    });
    return [];
  }
  let parsed;
  try {
    parsed = JSON.parse(raw);
  } catch (err) {
    log.warn("malformed rss-feeds.json \u2014 ignoring", {
      path,
      error: err instanceof Error ? err.message : String(err)
    });
    return [];
  }
  if (!Array.isArray(parsed)) {
    log.warn("rss-feeds.json must be an array \u2014 ignoring", { path });
    return [];
  }
  const out = [];
  for (const entry of parsed) {
    if (!entry || typeof entry !== "object") continue;
    const url = typeof entry.url === "string" ? entry.url.trim() : "";
    if (!url || !isValidUrl(url)) {
      log.warn("invalid RSS feed URL in rss-feeds.json", { url });
      continue;
    }
    const feed = { url };
    if (typeof entry.category === "string" && entry.category.length > 0) {
      feed.category = entry.category;
    }
    if (typeof entry.intervalSec === "number" && isFinite(entry.intervalSec) && entry.intervalSec > 0) {
      feed.intervalSec = entry.intervalSec;
    }
    out.push(feed);
  }
  return out;
}
function loadFeedConfig(opts) {
  const dataDir = opts?.dataDir ?? getConfig().dataDir;
  const envFeeds = loadEnvFeeds();
  const fileFeeds = loadFileFeeds(dataDir);
  const sources = [];
  if (envFeeds.length > 0) sources.push("env");
  if (fileFeeds.length > 0) sources.push("file");
  const byUrl = /* @__PURE__ */ new Map();
  for (const f of fileFeeds) byUrl.set(f.url, f);
  for (const f of envFeeds) byUrl.set(f.url, f);
  return { feeds: Array.from(byUrl.values()), sources };
}
export {
  loadFeedConfig
};
//# sourceMappingURL=feed-config.js.map