export interface UserCorrectionRecord {
  record_type: 'conversation';
  action_type: 'user_correction';
  priority: 'critical_for_recovery';
  timestamp: string;
  original_claim: string;
  correction: string;
  principle_extracted: string;
  persisted_to: string[];
}

export function createCorrection(params: {
  originalClaim: string;
  correction: string;
  principleExtracted?: string;
  persistedTo?: string[];
}): UserCorrectionRecord {
  return {
    record_type: 'conversation',
    action_type: 'user_correction',
    priority: 'critical_for_recovery',
    timestamp: new Date().toISOString(),
    original_claim: params.originalClaim,
    correction: params.correction,
    principle_extracted: params.principleExtracted || '',
    persisted_to: params.persistedTo || [],
  };
}

export function findCorrections(
  records: Record<string, unknown>[],
): UserCorrectionRecord[] {
  return records.filter(
    r => r['action_type'] === 'user_correction',
  ) as unknown as UserCorrectionRecord[];
}

export function checkCorrectionConflict(
  proposedAction: string,
  corrections: UserCorrectionRecord[],
): UserCorrectionRecord | null {
  for (const c of corrections) {
    if (!c.original_claim) continue;
    const claimKeywords = c.original_claim.toLowerCase().split(/\s+/).filter(w => w.length > 3);
    const actionLower = proposedAction.toLowerCase();
    const matchCount = claimKeywords.filter(k => actionLower.includes(k)).length;
    if (matchCount >= 2 && matchCount / claimKeywords.length >= 0.5) {
      if (c.persisted_to.length > 0) return c;
    }
  }
  return null;
}
