"use strict";

import { cleanFilePath } from "../utils/fileUtils.js";

/**
 * Service for Audio Tagging functionality
 */
export class AudioTaggingService {
  initialized = false;
  constructor(api) {
    this.api = api;
  }

  /**
   * Initialize the Audio Tagging engine
   * @param config The Audio Tagging model configuration
   * @returns Promise resolving to initialization result
   */
  async initialize(config) {
    try {
      // First validate library
      const validation = await this.api.validateLibraryLoaded();
      if (!validation.loaded) {
        throw new Error(`Library validation failed: ${validation.status}`);
      }
      const cleanedConfig = {
        ...config,
        modelDir: cleanFilePath(config.modelDir)
      };
      const result = await this.api.initAudioTagging(cleanedConfig);
      this.initialized = result.success;
      return result;
    } catch (error) {
      this.initialized = false;
      throw error;
    }
  }

  /**
   * Get the initialized status
   */
  isInitialized() {
    return this.initialized;
  }

  /**
   * Process and compute audio tagging in a single call
   * This method properly manages resources throughout the operation
   * for both file-based and sample-based processing.
   * @param options Options for processing audio
   * @returns Promise resolving to the audio tagging result
   */
  async processAndCompute(options) {
    if (!this.initialized) {
      throw new Error('Audio Tagging is not initialized. Call initialize() first.');
    }

    // Use our safer dedicated methods for both files and samples
    if (options.filePath) {
      return this.api.processAndComputeAudioTagging({
        filePath: cleanFilePath(options.filePath),
        topK: options.topK
      });
    } else if (options.samples && options.sampleRate) {
      return this.api.processAndComputeAudioSamples({
        sampleRate: options.sampleRate,
        samples: options.samples,
        topK: options.topK
      });
    } else {
      throw new Error('Either filePath or (samples and sampleRate) must be provided');
    }
  }

  /**
   * Release Audio Tagging resources
   */
  async release() {
    const result = await this.api.releaseAudioTagging();
    if (result.released) {
      this.initialized = false;
    }
    return result;
  }
}
//# sourceMappingURL=AudioTaggingService.js.map