const fs = require('fs');
const path = require('path');

class AssetLoader {
  constructor() {
    this.relPath = './'
    this.baseDir = path.resolve(__dirname, this.relPath);
    this.cache = new Map(); // Cache loaded JSON files for better performance
  }

  /**
   * Load a specific curve by type
   * @param {string} curveType - The curve identifier (e.g., 'hidrostal-H05K-S03R')
   * @returns {Object|null} The curve data object or null if not found
   */
  loadModel(modelType) {
    return this.loadAsset('models', modelType);
  }

  /**
   * Load any asset from a specific dataset folder
   * @param {string} datasetType - The dataset folder name (e.g., 'curves', 'assetData')
   * @param {string} assetId - The specific asset identifier
   * @returns {Object|null} The asset data object or null if not found
   */
  loadAsset(datasetType, assetId) {
    //const cacheKey = `${datasetType}/${assetId}`;
    const cacheKey = `${assetId}`;

    
    // Check cache first
    if (this.cache.has(cacheKey)) {
      return this.cache.get(cacheKey);
    }

    try {
      const filePath = path.join(this.baseDir, `${assetId}.json`);

      // Check if file exists
      if (!fs.existsSync(filePath)) {
        console.warn(`Asset not found: ${filePath}`);
        return null;
      }

      // Load and parse JSON
      const rawData = fs.readFileSync(filePath, 'utf8');
      const assetData = JSON.parse(rawData);
      
      // Cache the result
      this.cache.set(cacheKey, assetData);
      
      return assetData;
    } catch (error) {
      console.error(`Error loading asset ${cacheKey}:`, error.message);
      return null;
    }
  }

  /**
   * Get all available assets in a dataset
   * @param {string} datasetType - The dataset folder name
   * @returns {string[]} Array of available asset IDs
   */
  getAvailableAssets(datasetType) {
    try {
      const datasetPath = path.join(this.baseDir, datasetType);
      
      if (!fs.existsSync(datasetPath)) {
        return [];
      }

      return fs.readdirSync(datasetPath)
        .filter(file => file.endsWith('.json'))
        .map(file => file.replace('.json', ''));
    } catch (error) {
      console.error(`Error reading dataset ${datasetType}:`, error.message);
      return [];
    }
  }

  /**
   * Clear the cache (useful for development/testing)
   */
  clearCache() {
    this.cache.clear();
  }
}

// Create and export a singleton instance
const assetLoader = new AssetLoader();

module.exports = {
  AssetLoader,
  assetLoader,
  // Convenience methods for backward compatibility
  loadModel: (modelType) => assetLoader.loadModel(modelType),
  loadAsset: (datasetType, assetId) => assetLoader.loadAsset(datasetType, assetId),
  getAvailableAssets: (datasetType) => assetLoader.getAvailableAssets(datasetType)
};

/*
// Example usage in your scripts
const loader = new AssetLoader();

// Load a specific curve
const curve = loader.loadModel('hidrostal-H05K-S03R');
if (curve) {
  console.log('Model loaded:', curve);
} else {
  console.log('Model not found');
}
/*
// Load any asset from any dataset
const someAsset = loadAsset('assetData', 'some-asset-id');

// Get list of available models
const availableCurves = getAvailableAssets('curves');
console.log('Available curves:', availableCurves);

// Using the class directly for more control
const { AssetLoader } = require('./index.js');
const customLoader = new AssetLoader();
const data = customLoader.loadCurve('hidrostal-H05K-S03R');
*/