// ===== Language type =====
export type PromptLanguage = 'zh' | 'en';

export interface AttributeNode {
  name: string;
  category?: string;  // Materials, Functions, Usages, User Groups
  children?: AttributeNode[];
}

export interface AnalyzeRequest {
  query: string;
  model?: string;
  temperature?: number;
  categories?: string[];
  lang?: PromptLanguage;
}

export const DEFAULT_CATEGORIES = {
  zh: ['材料', '功能', '用途', '使用族群', '特性'],
  en: ['Materials', 'Functions', 'Usages', 'User Groups', 'Characteristics'],
};

export const CATEGORY_DESCRIPTIONS: Record<PromptLanguage, Record<string, string>> = {
  zh: {
    '材料': '物件由什麼材料組成',
    '功能': '物件能做什麼',
    '用途': '物件在什麼場景使用',
    '使用族群': '誰會使用這個物件',
    '特性': '物件有什麼特徵',
  },
  en: {
    'Materials': 'What materials the object is made of',
    'Functions': 'What the object can do',
    'Usages': 'In what scenarios the object is used',
    'User Groups': 'Who uses this object',
    'Characteristics': 'What features the object has',
  },
};

export interface AnalyzeResponse {
  query: string;
  attributes: AttributeNode;
}

export interface ModelListResponse {
  models: string[];
}

export interface HistoryItem {
  query: string;
  result: AttributeNode;
  timestamp: Date;
}

// ===== Multi-step streaming types =====

export interface Step1Result {
  materials: string[];
  functions: string[];
  usages: string[];
  users: string[];
}

export interface CausalChain {
  material: string;
  function: string;
  usage: string;
  user: string;
}

// ===== Dynamic category system types =====

export interface CategoryDefinition {
  name: string;
  description?: string;
  is_fixed: boolean;
  order: number;
}

export interface Step0Result {
  categories: CategoryDefinition[];
}

export interface DynamicStep1Result {
  attributes: Record<string, string[]>;
}

export interface DynamicCausalChain {
  chain: Record<string, string>;
}

export const CategoryMode = {
  FIXED_ONLY: 'fixed_only',
  FIXED_PLUS_CUSTOM: 'fixed_plus_custom',
  FIXED_PLUS_DYNAMIC: 'fixed_plus_dynamic',
  CUSTOM_ONLY: 'custom_only',
  DYNAMIC_AUTO: 'dynamic_auto',
} as const;

export type CategoryMode = typeof CategoryMode[keyof typeof CategoryMode];

export interface StreamAnalyzeRequest {
  query: string;
  model?: string;
  temperature?: number;
  chain_count: number;
  // Dynamic category support
  category_mode?: CategoryMode;
  custom_categories?: string[];
  suggested_category_count?: number;
  // Language setting
  lang?: PromptLanguage;
}

export interface StreamProgress {
  step: 'idle' | 'step0' | 'step1' | 'chains' | 'done' | 'error';
  step0Result?: Step0Result;
  categoriesUsed?: CategoryDefinition[];
  step1Result?: Step1Result | DynamicStep1Result;
  currentChainIndex: number;
  totalChains: number;
  completedChains: (CausalChain | DynamicCausalChain)[];
  message: string;
  error?: string;
}

export interface StreamAnalyzeResponse {
  query: string;
  step0_result?: Step0Result;
  categories_used: CategoryDefinition[];
  step1_result: Step1Result | DynamicStep1Result;
  causal_chains: (CausalChain | DynamicCausalChain)[];
  attributes: AttributeNode;
}

// ===== DAG (Directed Acyclic Graph) types =====

export interface DAGNode {
  id: string;
  name: string;
  category: string;
  order: number;
}

export interface DAGEdge {
  source_id: string;
  target_id: string;
}

export interface AttributeDAG {
  query: string;
  categories: CategoryDefinition[];
  nodes: DAGNode[];
  edges: DAGEdge[];
}

export interface DAGRelationship {
  source_category: string;
  source: string;
  target_category: string;
  target: string;
}

export interface DAGStreamAnalyzeResponse {
  query: string;
  step0_result?: Step0Result;
  categories_used: CategoryDefinition[];
  step1_result: DynamicStep1Result;
  relationships: DAGRelationship[];
  dag: AttributeDAG;
}

// ===== Transformation Agent types =====

export interface TransformationRequest {
  query: string;
  category: string;
  attributes: string[];
  model?: string;
  temperature?: number;
  keyword_count?: number;
  lang?: PromptLanguage;
}

export interface TransformationDescription {
  keyword: string;
  description: string;
}

export interface TransformationCategoryResult {
  category: string;
  original_attributes: string[];
  new_keywords: string[];
  descriptions: TransformationDescription[];
}

export interface TransformationDAGResult {
  query: string;
  results: TransformationCategoryResult[];
}

export interface TransformationProgress {
  step: 'idle' | 'keyword' | 'description' | 'done' | 'error';
  currentCategory: string;
  processedCategories: string[];
  message: string;
  error?: string;
}

export interface TransformationInput {
  query: string;
  categories: CategoryDefinition[];
  attributesByCategory: Record<string, string[]>;
}

// ===== Expert Transformation Agent types =====

export interface ExpertProfile {
  id: string;                    // "expert-0"
  name: string;                  // "藥師"
  domain: string;                // "醫療與健康"
  perspective?: string;          // "從藥物與健康管理角度思考"
}

export interface ExpertKeyword {
  keyword: string;
  expert_id: string;
  expert_name: string;
  source_attribute: string;      // 來自哪個原始屬性
}

export interface ExpertTransformationDescription {
  keyword: string;
  expert_id: string;
  expert_name: string;
  description: string;
}

export interface ExpertTransformationCategoryResult {
  category: string;
  original_attributes: string[];
  expert_keywords: ExpertKeyword[];
  descriptions: ExpertTransformationDescription[];
}

export interface ExpertTransformationDAGResult {
  query: string;
  experts: ExpertProfile[];
  results: ExpertTransformationCategoryResult[];
}

export type ExpertSource = 'llm' | 'curated' | 'dbpedia' | 'wikidata';

export interface ExpertTransformationRequest {
  query: string;
  category: string;
  attributes: string[];
  expert_count: number;              // 2-8
  keywords_per_expert: number;       // 1-3
  custom_experts?: string[];         // User-specified experts
  expert_source?: ExpertSource;      // Expert source (default: 'llm')
  expert_language?: string;          // External source language (default: 'en')
  model?: string;
  temperature?: number;
  lang?: PromptLanguage;             // Prompt language
}

export interface ExpertTransformationProgress {
  step: 'idle' | 'expert' | 'keyword' | 'description' | 'done' | 'error';
  currentCategory: string;
  processedCategories: string[];
  experts?: ExpertProfile[];
  currentAttribute?: string;
  message: string;
  error?: string;
}

export interface ExpertTransformationInput {
  query: string;
  categories: CategoryDefinition[];
  attributesByCategory: Record<string, string[]>;
  expertConfig: {
    expert_count: number;
    keywords_per_expert: number;
    custom_experts?: string[];
  };
}

// ===== Deduplication Agent types =====

export type DeduplicationMethod = 'embedding' | 'llm';

export interface DeduplicationRequest {
  descriptions: ExpertTransformationDescription[];
  method?: DeduplicationMethod;  // Deduplication method, default: 'embedding'
  similarity_threshold?: number;  // 0.0-1.0, default 0.85, only for embedding
  model?: string;  // Embedding/LLM model
  lang?: PromptLanguage;  // Prompt language (for LLM method)
}

export interface DescriptionGroup {
  group_id: string;
  representative: ExpertTransformationDescription;
  duplicates: ExpertTransformationDescription[];
  similarity_scores: number[];
}

export interface DeduplicationResult {
  total_input: number;
  total_groups: number;
  total_duplicates: number;
  groups: DescriptionGroup[];
  threshold_used: number;
  method_used: DeduplicationMethod;  // 使用的方法
  model_used: string;                // 使用的模型
}

export interface DeduplicationProgress {
  step: 'idle' | 'processing' | 'done' | 'error';
  message: string;
  error?: string;
}

// ===== Dual-Path types =====

export type PathId = 'A' | 'B';

export interface PathState {
  query: string;
  result: AttributeDAG | null;
  loading: boolean;
  progress: DAGProgress;
  error: string | null;
}

export interface DualPathState {
  pathA: PathState;
  pathB: PathState;
}

export interface DAGProgress {
  step: 'idle' | 'step0' | 'step1' | 'relationships' | 'done' | 'error';
  message: string;
  error?: string;
}

// ===== Attribute Crossover types =====

export interface CrossoverPair {
  id: string;
  sourcePathId: PathId;
  sourceNode: DAGNode;
  targetPathId: PathId;
  targetNode: DAGNode;
  crossType: string;  // 'material-function' | 'function-usage' | etc.
  selected: boolean;
}

export interface CrossoverConfig {
  enabledCrossTypes: string[];
  maxPairsPerType: number;
  autoGenerate: boolean;
}

export interface CrossoverResult {
  pairs: CrossoverPair[];
  totalPairs: number;
}

// ===== Expert Mode types =====

export type ExpertMode = 'shared' | 'independent';

export interface ExpertConfig {
  expert_count: number;
  keywords_per_expert: number;
  custom_experts?: string[];
  expert_source: ExpertSource;
  expert_language?: 'en' | 'zh';
}

export interface DualPathExpertConfig {
  mode: ExpertMode;
  sharedConfig?: ExpertConfig;
  independentConfig?: {
    pathA: ExpertConfig;
    pathB: ExpertConfig;
  };
}

// ===== Dual-Path Transformation types =====

export interface DualPathTransformationState {
  pathA: ExpertTransformationDAGResult | null;
  pathB: ExpertTransformationDAGResult | null;
  crossover: CrossoverTransformationResult | null;
}

export interface CrossoverTransformationResult {
  crossoverPairs: CrossoverPair[];
  experts: ExpertProfile[];
  transformedIdeas: ExpertTransformationDescription[];
}

// ===== Patent Search types (Lens.org API) =====

export interface PatentResult {
  lens_id: string;
  doc_number: string;
  jurisdiction: string;
  kind: string;
  title: string;
  abstract: string | null;
  date_published: string | null;
  applicants: string[];
  inventors: string[];
  legal_status: string | null;
  classifications_cpc: string[];
  families_simple: string[];
  url: string;
}

export interface PatentSearchRequest {
  query: string;
  max_results?: number;
}

export interface PatentSearchResponse {
  query: string;
  total_results: number;
  patents: PatentResult[];
  error?: string | null;
}

export interface BatchPatentSearchRequest {
  queries: string[];
  max_results_per_query?: number;
}

export interface BatchPatentSearchResult {
  query: string;
  total_results: number;
  patents: PatentResult[];
  error?: string | null;
}

export interface BatchPatentSearchResponse {
  results: BatchPatentSearchResult[];
  total_queries: number;
}
