export type QueryType =
  | "factual"
  | "conceptual"
  | "procedural"
  | "ambiguous"
  | "other";

export interface QueryExpanderOptions {
  expansionDegree?: number; // 1~3, 확장 강도
  enableFeedback?: boolean;
}

export interface ExpansionFeedback {
  original: string;
  reformulated: string;
  success: boolean;
  notes?: string;
}

export class QueryExpander {
  private options: QueryExpanderOptions;
  private feedbacks: ExpansionFeedback[] = [];

  constructor(options: QueryExpanderOptions = {}) {
    this.options = { expansionDegree: 2, enableFeedback: true, ...options };
  }

  classify(query: string): QueryType {
    // 간단한 규칙 기반 분류 (실제 서비스에서는 ML 모델 대체 가능)
    if (/^how to|steps|process|procedure/i.test(query)) return "procedural";
    if (/^(what|who|when|where|how|why)\b/i.test(query)) return "factual";
    if (/^explain|describe|meaning|concept|definition/i.test(query))
      return "conceptual";
    if (query.length < 8) return "ambiguous";
    return "other";
  }

  expand(query: string, type?: QueryType): string {
    const t = type || this.classify(query);
    let expanded = query;
    if (t === "ambiguous" || t === "other") {
      expanded += " (자세히 설명, 관련 키워드 포함)";
    } else if (t === "factual") {
      expanded += " (정확한 정보, 날짜, 인물 등 포함)";
    } else if (t === "conceptual") {
      expanded += " (정의, 배경, 예시 포함)";
    } else if (t === "procedural") {
      expanded += " (단계별 설명, 예시 포함)";
    }
    // 확장 강도 옵션 적용
    for (let i = 1; i < (this.options.expansionDegree || 2); i++) {
      expanded += " | 관련 맥락 추가";
    }
    return expanded;
  }

  reformulate(query: string): string {
    // 벡터 검색 최적화를 위한 재구성 (불필요한 stopword 제거 등)
    return query
      .replace(/\b(the|a|an|is|are|was|were|of|in|on|for|to|with)\b/gi, "")
      .replace(/\s+/g, " ")
      .trim();
  }

  feedback(
    original: string,
    reformulated: string,
    success: boolean,
    notes?: string
  ) {
    if (this.options.enableFeedback) {
      this.feedbacks.push({ original, reformulated, success, notes });
    }
  }

  getFeedbacks(): ExpansionFeedback[] {
    return this.feedbacks;
  }
}
