export interface CalculationInput {
  materialSfm: number;
  materialChipLoad: number;
  toolDiameter: number;
  toolFlutes: number;
  machineMaxRpm: number;
  machineMaxFeedRate: number;
  machineHorsepower: number;
  cutDepth: number;
  cutWidth: number;
  aggressiveness: number; // 0-100, 50 is neutral
}

export interface CalculationResult {
  rpm: number;
  feedRate: number;
  chipLoad: number;
  mrr: number;
  sfpm: number;
  rpmLimited: boolean;
  feedLimited: boolean;
  powerWarning: boolean;
  recommendations: string[];
}

export function calculateSpeedsAndFeeds(input: CalculationInput): CalculationResult {
  const {
    materialSfm,
    materialChipLoad,
    toolDiameter,
    toolFlutes,
    machineMaxRpm,
    machineMaxFeedRate,
    machineHorsepower,
    cutDepth,
    cutWidth,
    aggressiveness,
  } = input;

  // Aggressiveness multiplier: 0.5 to 1.5 based on slider (0-100)
  const aggMultiplier = 0.5 + (aggressiveness / 100);

  // Calculate ideal RPM from surface feet per minute
  // RPM = (SFM × 12) / (π × Diameter)
  const idealRpm = (materialSfm * 12) / (Math.PI * toolDiameter);
  
  // Apply aggressiveness and limit to machine max
  let rpm = Math.round(idealRpm * aggMultiplier);
  const rpmLimited = rpm > machineMaxRpm;
  rpm = Math.min(rpm, machineMaxRpm);

  // Adjusted chip load based on aggressiveness
  const adjustedChipLoad = materialChipLoad * aggMultiplier;

  // Calculate feed rate: Feed = RPM × Flutes × Chip Load
  let feedRate = rpm * toolFlutes * adjustedChipLoad;
  const feedLimited = feedRate > machineMaxFeedRate;
  feedRate = Math.min(feedRate, machineMaxFeedRate);

  // Actual chip load after limiting
  const actualChipLoad = feedRate / (rpm * toolFlutes);

  // Material Removal Rate (MRR) in cubic inches per minute
  const mrr = (cutWidth * cutDepth * feedRate);

  // Actual SFPM
  const sfpm = (Math.PI * toolDiameter * rpm) / 12;

  // Power estimation (rough): HP = MRR × Material Factor
  // Using simplified unit HP factor
  const estimatedHp = mrr * 0.5; // Simplified calculation
  const powerWarning = estimatedHp > machineHorsepower * 0.8;

  const recommendations: string[] = [];
  if (rpmLimited) {
    recommendations.push('RPM limited by machine - consider smaller tool diameter');
  }
  if (feedLimited) {
    recommendations.push('Feed rate limited by machine - reduce aggressiveness');
  }
  if (powerWarning) {
    recommendations.push('High power usage - reduce cut depth or width');
  }
  if (aggressiveness > 75) {
    recommendations.push('Aggressive settings - monitor tool wear closely');
  }
  if (aggressiveness < 25) {
    recommendations.push('Conservative settings - good for finishing passes');
  }

  return {
    rpm: Math.round(rpm),
    feedRate: Math.round(feedRate * 10) / 10,
    chipLoad: Math.round(actualChipLoad * 10000) / 10000,
    mrr: Math.round(mrr * 1000) / 1000,
    sfpm: Math.round(sfpm),
    rpmLimited,
    feedLimited,
    powerWarning,
    recommendations,
  };
}
