import { emptyProfile, type ApplicantProfile } from "./schema";
import { heuristicPatch, mergeProfile } from "./extract";
import { computeProcess } from "./gates";
import { healthGateComplete } from "./health";
import { STUB_CARRIERS, stubDecision } from "./decisionStub";

export type ChatTurn = { role: "user" | "assistant"; content: string };

/** Rebuild ApplicantProfile from a full chat, section by section (steps 0–8 fields). */
export function replayConversation(turns: ChatTurn[]): ApplicantProfile {
  let profile = emptyProfile();
  let lastAssistant = "";
  for (const turn of turns) {
    if (turn.role === "assistant") {
      lastAssistant = turn.content;
      continue;
    }
    if (/^chatgpt said:/i.test(turn.content.trim())) continue;
    profile = mergeProfile(profile, heuristicPatch(turn.content, { lastAssistant, profile }));
  }
  if (profile.coverage_on_whom === "primary" && !profile.beneficiary_relationship) {
    profile = mergeProfile(profile, { beneficiary_relationship: "self" });
  }
  if (healthGateComplete(profile) && !profile.decision_result) {
    profile = mergeProfile(profile, { decision_result: stubDecision(profile) });
  }
  if (healthGateComplete(profile) && profile.beneficiary_relationship && !profile.carrier_shortlist?.length) {
    profile = mergeProfile(profile, { carrier_shortlist: STUB_CARRIERS });
  }
  return profile;
}

export function replayProcess(turns: ChatTurn[]) {
  const profile = replayConversation(turns);
  return { profile, process: computeProcess(profile) };
}
