import { createHash } from "node:crypto";
import { createLogger } from "../logger.js";
import {
  normalizeUrl,
  getHashAndStatusForNormalizedUrl,
  getMarkdownForNormalizedUrl
} from "./store.js";
import { computeDiffSummary } from "./diff-summary.js";
const log = createLogger("cache");
function detectChange(url, newMarkdown, newHttpStatus) {
  try {
    const normalizedUrl = normalizeUrl(url);
    const { hash: previousHash, status: previousStatus } = getHashAndStatusForNormalizedUrl(normalizedUrl);
    if (previousHash === null) {
      log.debug("no cached entry for change detection", { url: normalizedUrl });
      return { changed: false };
    }
    const newHash = createHash("sha256").update(newMarkdown).digest("hex");
    const statusChanged = previousStatus !== null && typeof newHttpStatus === "number" && previousStatus !== newHttpStatus;
    if (newHash === previousHash && !statusChanged) {
      log.debug("content unchanged", { url: normalizedUrl, hash: newHash });
      return { changed: false };
    }
    const previousMarkdown = getMarkdownForNormalizedUrl(normalizedUrl);
    const diffSummary = previousMarkdown !== null ? computeDiffSummary(previousMarkdown, newMarkdown) : void 0;
    log.info("content change detected", {
      url: normalizedUrl,
      previousHash,
      newHash,
      previousStatus,
      newHttpStatus,
      statusChanged,
      diffSummary
    });
    return {
      changed: true,
      previousHash,
      diffSummary,
      ...statusChanged ? { previousHttpStatus: previousStatus } : {}
    };
  } catch (err) {
    log.error("change detection failed", {
      url,
      error: err instanceof Error ? err.message : String(err)
    });
    return { changed: false };
  }
}
export {
  detectChange
};
//# sourceMappingURL=change-detector.js.map