import type { ApplicantProfile } from "./schema";
import { remainingDiseaseModules, healthGateComplete } from "./health";

export type ProcessStep = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;

export const STEP_META: Record<
  ProcessStep,
  { label: string; exitGate: string; phase: string }
> = {
  0: { label: "Lead intake", exitGate: "Contactable person + state", phase: "ZERO" },
  1: { label: "Lock intent", exitGate: "Intent + who to cover", phase: "INTENT" },
  2: { label: "Demographics & loan facts", exitGate: "Age or DOB + loan_balance", phase: "DATA" },
  3: { label: "Build + tobacco", exitGate: "BMI computed + tobacco answered", phase: "DATA" },
  4: { label: "Disease interview", exitGate: "R modules done or none reported", phase: "KNOWLEDGE" },
  5: { label: "Spouse / income", exitGate: "Income; spouse if co-borrower; beneficiary", phase: "KNOWLEDGE" },
  6: { label: "Soft decision", exitGate: "DecisionResult persisted", phase: "DECISION" },
  7: { label: "Carrier shortlist", exitGate: "At least one path or postpone", phase: "MATCH" },
  8: { label: "Hand off to licensed agent", exitGate: "Agent briefing acknowledged", phase: "AGENT" },
};

export function missingRequired(p: ApplicantProfile, step: ProcessStep): string[] {
  const miss: string[] = [];
  if (step === 0) {
    if (!p.name && !p.phone) miss.push("name_or_phone");
    if (!p.state) miss.push("state");
  }
  if (step === 1) {
    if (p.intent !== "mortgage_protection") miss.push("intent");
    if (!p.coverage_on_whom) miss.push("coverage_on_whom");
  }
  if (step === 2) {
    if (p.age == null && !p.date_of_birth) miss.push("date_of_birth");
    if (p.loan_balance == null) miss.push("loan_balance");
  }
  if (step === 3) {
    if (!p.height_ft_in) miss.push("height_ft_in");
    if (p.weight_lb == null) miss.push("weight_lb");
    if (!p.tobacco_answered && !p.tobacco_products?.length && p.nicotine_class == null)
      miss.push("tobacco");
  }
  if (step === 4) {
    if (!healthGateComplete(p)) {
      const left = remainingDiseaseModules(p);
      miss.push(left.length ? `diseases:${left.join(",")}` : "diseases");
    }
  }
  if (step === 5) {
    if (p.co_borrower_flag && !p.spouse_age_sex) miss.push("spouse_age_sex");
    if (p.co_borrower_flag && p.spouse_annual_income == null) miss.push("spouse_annual_income");
    if (p.annual_income == null) miss.push("annual_income");
    if (!p.beneficiary_relationship) miss.push("beneficiary_relationship");
  }
  if (step === 6 && !p.decision_result) miss.push("decision_result");
  if (step === 7 && !p.carrier_shortlist?.length) miss.push("carrier_shortlist");
  if (step === 8 && !p.agent_handoff_ack) miss.push("agent_handoff_ack");
  return miss;
}

function gate0(p: ApplicantProfile) {
  return Boolean((p.name || p.phone) && p.state);
}
function gate1(p: ApplicantProfile) {
  return p.intent === "mortgage_protection" && Boolean(p.coverage_on_whom);
}
function gate2(p: ApplicantProfile) {
  return (p.age != null || Boolean(p.date_of_birth)) && p.loan_balance != null;
}
function gate3(p: ApplicantProfile) {
  return Boolean(p.height_ft_in && p.weight_lb != null && p.bmi_computed != null && (p.tobacco_answered || p.tobacco_products?.length || p.nicotine_class));
}
function gate4(p: ApplicantProfile) {
  return healthGateComplete(p);
}
function gate5(p: ApplicantProfile) {
  if (p.co_borrower_flag && !p.spouse_age_sex) return false;
  if (p.co_borrower_flag && p.spouse_annual_income == null) return false;
  if (p.annual_income == null) return false;
  return Boolean(p.beneficiary_relationship);
}
function gate6(p: ApplicantProfile) {
  return Boolean(p.decision_result);
}
function gate7(p: ApplicantProfile) {
  return Boolean(p.carrier_shortlist && p.carrier_shortlist.length > 0);
}

export function computeProcess(p: ApplicantProfile, blocked?: string | null) {
  if (blocked) {
    return {
      step: 0 as ProcessStep,
      stepKey: "step-0",
      label: STEP_META[0].label,
      exitGate: STEP_META[0].exitGate,
      phase: STEP_META[0].phase,
      missingRequired: [blocked],
      blocked: true,
    };
  }
  let step: ProcessStep = 0;
  if (gate0(p)) step = 1;
  if (gate0(p) && gate1(p)) step = 2;
  if (gate0(p) && gate1(p) && gate2(p)) step = 3;
  if (gate0(p) && gate1(p) && gate2(p) && gate3(p)) step = 4;
  if (gate0(p) && gate1(p) && gate2(p) && gate3(p) && gate4(p)) step = 5;
  if (gate0(p) && gate1(p) && gate2(p) && gate3(p) && gate4(p) && gate5(p)) step = 6;
  if (gate0(p) && gate1(p) && gate2(p) && gate3(p) && gate4(p) && gate5(p) && gate6(p)) step = 7;
  if (gate0(p) && gate1(p) && gate2(p) && gate3(p) && gate4(p) && gate5(p) && gate6(p) && gate7(p))
    step = 8;

  const meta = STEP_META[step];
  return {
    step,
    stepKey: `step-${step}`,
    label: meta.label,
    exitGate: meta.exitGate,
    phase: meta.phase,
    missingRequired: missingRequired(p, step),
    blocked: false,
  };
}

export function detectStopPath(message: string): string | null {
  const t = message.toLowerCase();
  if (/\bi rent\b|\brenter\b|no mortgage|paid off/.test(t) && !/protect|coverage|insurance/.test(t))
    return "NO-MTG";
  if (/\bi rent\b/.test(t)) return "NO-MTG";
  if (/refinanc|lower (my )?rate|cash-?out|new (home )?loan/.test(t) && !/protect/.test(t))
    return "WR-LOAN";
  if (/health insurance|aca |medicare advantage|medical plan/.test(t)) return "WR-HEALTH";
  if (/do not call|don't call|dnc/.test(t)) return "DNC";
  return null;
}

export function detectEmergency(message: string): boolean {
  return /chest pain|can't breathe|cannot breathe|stroke|faint(ing)?|sudden weakness/.test(
    message.toLowerCase()
  );
}
