(function attachSafeSceneDatabase(root) {
  "use strict";

  var Common = root.SafeSceneCommon || require("./common.js");

  function SceneDatabase(dataset) {
    this.dataset = dataset || { version: 1, episodes: [] };
    this.episodes = Array.isArray(this.dataset.episodes) ? this.dataset.episodes : [];
    this.byCompositeKey = new Map();

    for (var index = 0; index < this.episodes.length; index += 1) {
      var episode = this.episodes[index];
      var key = buildCompositeKey(episode.showTitle, episode.seasonNumber, episode.episodeNumber);
      this.byCompositeKey.set(key, episode);
    }
  }

  function buildCompositeKey(showTitle, seasonNumber, episodeNumber) {
    return [
      Common.normalizeText(showTitle),
      Number(seasonNumber) || 0,
      Number(episodeNumber) || 0
    ].join("|");
  }

  function normalizeRange(range, episode) {
    var startSeconds = Common.parseTimecodeToSeconds(range.start);
    var endSeconds = Common.parseTimecodeToSeconds(range.end);

    if (startSeconds === null || endSeconds === null || endSeconds <= startSeconds) {
      return null;
    }

    return {
      id: range.id || [
        Common.normalizeText(episode.showTitle),
        episode.seasonNumber,
        episode.episodeNumber,
        Common.normalizeText(range.category),
        startSeconds
      ].join("-"),
      category: range.category || "nudity",
      start: range.start,
      end: range.end,
      startSeconds: startSeconds,
      endSeconds: endSeconds,
      confidence: range.confidence || "unknown",
      notes: range.notes || null,
      sourceName: range.sourceName || null,
      sourceUrl: range.sourceUrl || null
    };
  }

  SceneDatabase.prototype.lookup = function lookup(query) {
    var key = buildCompositeKey(query.showTitle, query.seasonNumber, query.episodeNumber);
    var episode = this.byCompositeKey.get(key);

    if (!episode) {
      return {
        status: "none",
        exactRanges: [],
        warningOnly: [],
        episode: null
      };
    }

    var exactRanges = Array.isArray(episode.ranges)
      ? episode.ranges.map(function mapRange(range) {
        return normalizeRange(range, episode);
      }).filter(Boolean)
      : [];

    return {
      status: exactRanges.length > 0 ? "exact" : "warning_only",
      exactRanges: exactRanges,
      warningOnly: Array.isArray(episode.warningOnly) ? Common.clone(episode.warningOnly) : [],
      episode: Common.clone(episode)
    };
  };

  function createSceneDatabase(dataset) {
    return new SceneDatabase(dataset);
  }

  var api = {
    SceneDatabase: SceneDatabase,
    createSceneDatabase: createSceneDatabase
  };

  root.SafeSceneDatabase = api;

  if (typeof module !== "undefined" && module.exports) {
    module.exports = api;
  }
}(typeof globalThis !== "undefined" ? globalThis : this));
