/** Normalize Agri-Access raw credit score (300–850) to AGNET 0–1000 scale (AA-007). */
export function normalizeScore(
  rawScore: number,
  min = 300,
  max = 850,
): number {
  const clamped = Math.max(min, Math.min(max, rawScore));
  return Math.round(((clamped - min) / (max - min)) * 1000);
}

export type EligibilityOutcome = "eligible" | "conditional" | "not_eligible";

export function eligibilityFromRawScore(
  rawScore: number,
  eligibleMin = 650,
  conditionalMin = 550,
): EligibilityOutcome {
  if (rawScore >= eligibleMin) return "eligible";
  if (rawScore >= conditionalMin) return "conditional";
  return "not_eligible";
}

/** Map Agri-Access SHAP feature names to AGNET reason codes (AA-017). */
const SHAP_FEATURE_TO_CODE: Record<string, string> = {
  ndvi: "RC_NDVI_ANOMALY",
  vegetation_health: "RC_NDVI_ANOMALY",
  predicted_yield: "RC_YIELD_FORECAST",
  historical_yield: "RC_YIELD_FORECAST",
  rainfall_patterns: "RC_DROUGHT_INDEX",
  drought_index: "RC_DROUGHT_INDEX",
  farm_size: "RC_LAND_AREA",
  land_area: "RC_LAND_AREA",
  loan_amount: "RC_DTI_PROXY",
  dti_ratio: "RC_DTI_PROXY",
  repayment_history: "RC_REPAYMENT_HISTORY",
  document_quality: "RC_DOC_QUALITY",
};

export interface ShapFeature {
  feature: string;
  shap_value: number;
  value?: number;
}

export interface ReasonCode {
  code?: string;
  feature?: string;
  contribution?: number;
  direction?: "positive" | "negative";
}

export function mapShapToReasonCodes(features: ShapFeature[]): ReasonCode[] {
  return features
    .map((f) => {
      const code = SHAP_FEATURE_TO_CODE[f.feature] ?? `RC_${f.feature.toUpperCase()}`;
      const contribution = Math.abs(f.shap_value);
      return {
        code,
        feature: f.feature,
        contribution,
        direction: f.shap_value >= 0 ? ("positive" as const) : ("negative" as const),
      };
    })
    .sort((a, b) => (b.contribution ?? 0) - (a.contribution ?? 0));
}
