import fs from 'fs';
import path from 'path';

export class StandardScaler {
  constructor() {
    this.means = {};
    this.stds = {};
  }

  fit(featuresArray) {
    if (!featuresArray.length) return;
    
    // Get all feature keys
    const keys = Object.keys(featuresArray[0]);

    for (const key of keys) {
      const values = featuresArray.map(f => f[key]);
      const mean = values.reduce((sum, v) => sum + v, 0) / values.length;
      
      const variance = values.reduce((sum, v) => sum + Math.pow(v - mean, 2), 0) / values.length;
      const std = Math.sqrt(variance);

      this.means[key] = mean;
      this.stds[key] = std || 1; // Avoid divide by 0
    }
  }

  transform(features) {
    const scaled = {};
    for (const key of Object.keys(this.means)) {
      if (features[key] === undefined) continue;
      scaled[key] = (features[key] - this.means[key]) / this.stds[key];
    }
    return scaled;
  }

  transformArray(featuresArray) {
    return featuresArray.map(f => this.transform(f));
  }

  save(filepath) {
    fs.writeFileSync(filepath, JSON.stringify({ means: this.means, stds: this.stds }, null, 2));
  }

  load(filepath) {
    if (!fs.existsSync(filepath)) return;
    const data = JSON.parse(fs.readFileSync(filepath, 'utf8'));
    this.means = data.means;
    this.stds = data.stds;
  }
}
