export interface TextClassification {
  isSpam: boolean;
  confidence: number;
  score: number;
}

export interface CallFeatures {
  callerNumber: string;
  areaCode: string;
  prefix: string;
  duration: number;
  timeOfDay: number;
}

export interface RuleResult {
  matched: boolean;
  action: "block" | "flag" | "allow" | "challenge";
  ruleId: string;
  ruleType: string;
}

export async function classifyTextBERT(text: string): Promise<TextClassification> {
  return {
    isSpam: false,
    confidence: 1.0,
    score: 0.0,
  };
}

export async function extractFeatures(metadata: {
  callerNumber: string;
  duration?: number;
  timeOfDay?: number;
}): Promise<CallFeatures> {
  const areaCode = metadata.callerNumber.length >= 3
    ? metadata.callerNumber.slice(0, 3)
    : metadata.callerNumber;

  return {
    callerNumber: metadata.callerNumber,
    areaCode,
    prefix: metadata.callerNumber.slice(0, 6),
    duration: metadata.duration ?? 0,
    timeOfDay: metadata.timeOfDay ?? new Date().getHours(),
  };
}

interface Rule {
  id: string;
  ruleType: string;
  pattern: string;
  action: "block" | "flag" | "allow" | "challenge";
  priority: number;
}

export async function ruleEngine(
  rules: Rule[],
  input: { phoneNumber: string; text?: string },
): Promise<RuleResult | null> {
  const sorted = [...rules].sort((a, b) => b.priority - a.priority);

  for (const rule of sorted) {
    const matched = matchRule(rule, input);
    if (matched) {
      return {
        matched: true,
        action: rule.action,
        ruleId: rule.id,
        ruleType: rule.ruleType,
      };
    }
  }

  return null;
}

function matchRule(
  rule: Rule,
  input: { phoneNumber: string; text?: string },
): boolean {
  switch (rule.ruleType) {
    case "phoneNumber":
      return input.phoneNumber === rule.pattern;
    case "areaCode":
      return input.phoneNumber.startsWith(rule.pattern);
    case "prefix":
      return input.phoneNumber.startsWith(rule.pattern);
    case "pattern":
      return input.text
        ? new RegExp(rule.pattern, "i").test(input.text)
        : new RegExp(rule.pattern, "i").test(input.phoneNumber);
    case "reputation":
      return false;
    default:
      return false;
  }
}
