import path from 'path';
import { readdir, readFile } from 'fs/promises';

class ContentLoader {
  constructor() {
    this.contentDir = null;
    this.tickets = new Map();
    this.quests = new Map();
    this.docs = new Map();
    this.dialogue = new Map();
    this.incidents = new Map();
    this.pressureProfiles = new Map();
    this.vmProfiles = new Map();
    this.trustUnlocks = [];
    this.worldFlagsRegistry = {};
  }

  async load() {
    this.contentDir = path.resolve(process.cwd(), process.env.CONTENT_DIR ?? '../content');
    this.tickets = await this._loadCollection('tickets');
    this.quests = await this._loadCollection('quests');
    this.docs = await this._loadCollection('docs');
    this.dialogue = await this._loadCollection('dialogue');
    this.incidents = await this._loadCollection('incidents');
    this.pressureProfiles = await this._loadCollection('pressure_profiles');
    this.vmProfiles = await this._loadCollection('vm_profiles');
    this.trustUnlocks = await this._loadJsonFile(path.join(this.contentDir, 'progression', 'trust_unlocks.json'));
    this.worldFlagsRegistry = await this._loadJsonFile(path.join(this.contentDir, 'world_flags', 'world_flags.json'));
    return this;
  }

  get(type, id) {
    const collection = this[type];
    if (!(collection instanceof Map)) {
      return undefined;
    }
    return collection.get(id);
  }

  async _loadCollection(subdirectory) {
    const directory = path.join(this.contentDir, subdirectory);
    const entries = await readdir(directory, { withFileTypes: true });
    const map = new Map();

    for (const entry of entries) {
      if (!entry.isFile()) {
        continue;
      }

      if (!entry.name.endsWith('.json') || entry.name.endsWith('.bak') || entry.name.includes('SPLIT_DONE')) {
        continue;
      }

      const payload = await this._loadJsonFile(path.join(directory, entry.name));
      if (payload?.id) {
        map.set(payload.id, payload);
      }
    }

    return map;
  }

  async _loadJsonFile(filePath) {
    const raw = await readFile(filePath, 'utf8');
    return JSON.parse(raw);
  }
}

export const contentLoader = new ContentLoader();
