/**
 * ============================================================
 * core/types.ts — 自动化流程所有类型定义
 * ============================================================
 * 包含：
 *   1. RawCsvRow        — CSV 原始行（与表头一一对应）
 *   2. LlmAnalysisResult — LLM 解析出的结构化信息
 *   3. ParsedProduct     — 中间产品（原始行 + LLM 结果合并）
 *   4. KeywordInputRow   — 关键词阶段输入行
 *   5. SearchPlanRow     — 搜索计划行
 *   6. PipelineResult    — 流水线执行结果摘要
 *   7. AiKeywordAnalysis — AI 语义关键词分析结果
 *   8–14. row-pipeline 各阶段 Supabase 行类型
 * ============================================================
 */

// ── 1. CSV 原始行：与 CSV 表头一一对应 ──────────────────────────
export type RawCsvRow = {
  发票种类: string;
  名称: string;
  规格型号: string;
  品牌: string;
  数量: string;
  单位: string;
  "备注/附件": string;
  收货地址: string;
  技术标准?: string;
  材质要求?: string;
  技术要求?: string;
  适用条件?: string;
  检验要求?: string;
  验收说明?: string;
  质保期?: string;
  交货期限?: string;
  来源文件?: string;
  批次ID?: string;
};

export type StandardizationSourceSnapshot = {
  id: string;
  batch_id: string;
  material_name: string;
  specification: string;
  quantity: number;
  unit: string;
  technical_standard: string;
  material_requirement: string;
  technical_requirement: string;
  applicable_conditions: string;
  test_requirement: string;
  acceptance_note: string;
  warranty_period: string;
  deadline: string;
  invoice_type: string;
  brand: string;
  remarks: string;
  delivery_address: string;
  source_file: string;
  created_at: string;
  created_by: string;
};

// ── 2. LLM 解析结果：从一行原始数据中提取的结构化信息 ─────────
export type LlmAnalysisResult = {
  /** 提取出的材质，如 "不锈钢"、"塑料"、"钢化夹胶玻璃" */
  material: string;
  /** 提取出的用途/应用场景，如 "预应力混凝土桥梁"、"风亭围栏" */
  usage: string;
  /** 简化后的规格参数（去掉冗余描述，留核心尺寸），如 "φ50mm"、"0.8米高" */
  simplified_spec: string;
  /** 可用于搜索的品牌简称；如果品牌字段不是可搜索品牌，则留空 */
  brand_term: string;
  /** 从所有字段中提取的关键词参数词，类型限定为规格/型号/材质/品牌/用途 */
  keyword_parameter_terms: string[];
  /** 修饰词数组，按“先删谁”的顺序排列；后续轮次将按顺序逐个删除 */
  modifier_terms: string[];
  /** AI 生成的专业替代词；放在删除轮次之后继续尝试 */
  alternative_terms: string[];
};

// ── 3. 中间解析产品：CSV 原始字段 + LLM 提取字段的合并 ────────
export type ParsedProduct = {
  /** procurement_materials.id，对应当前采购物料的稳定主键 */
  material_id: string;
  /** 原始 CSV 行数据 */
  raw: RawCsvRow;
  /** LLM 提取的结构化字段 */
  analysis: LlmAnalysisResult;
};

// ── 4. 关键词输入行：关键词阶段的中间输入结构 ─────────────────
export type KeywordInputRow = {
  id?: string;                  // uuid（Supabase 自动生成）
  batch_id: string;             // 所属批次 ID
  material_id: string;          // procurement_materials.id，唯一标识
  invoice_type: string;         // 发票种类
  name: string;                 // 商品名称
  spec: string;                 // 规格型号（原始值）
  brand: string;                // 品牌（原始值）
  quantity: string;             // 数量
  unit: string;                 // 单位
  notes: string;                // 备注/附件
  delivery_address: string;     // 收货地址
  material: string;             // LLM 提取的材质
  usage: string;                // LLM 提取的用途
  simplified_spec: string;      // LLM 简化后的规格
  standardized_brand: string;   // LLM 提取的品牌（从规格/品牌字段识别）
  created_at?: string;          // 创建时间（Supabase 自动生成）
};

// ── 5. 搜索计划行：关键词阶段生成的搜索轮次计划 ───────────────
export type SearchPlanRow = {
  id?: string;                  // uuid（Supabase 自动生成）
  batch_id: string;             // 所属批次 ID
  material_id: string;          // 外键 → procurement_materials.id
  primary_keyword: string;      // 当前轮次使用的搜索关键词
  alt_keywords: string;         // 备用搜索词（逗号分隔）
  search_round: number;         // 搜索轮次（从 1 开始，按执行顺序递增）
  search_strategy: string;      // 轮次策略：initial_full / remove_modifier / remove_brand / remove_spec / name_only / ai_alternative
  keyword_source: string;       // 关键词来源：progressive / ai_alternative
  confirmed: boolean | null;    // 识别确认状态（null=待判断）
  best_keyword: string;         // 最优关键词（初始为空）
  estimated_price_range: string; // 预估价格范围（可选）
  category: string;             // 类目判断结果（可选）
  created_at?: string;          // 创建时间
};

// ── 6. 流水线执行结果 ─────────────────────────────────────────
export type PipelineResult = {
  success: boolean;             // 是否成功
  totalRows: number;            // CSV 总行数
  keywordInputRowsGenerated: number; // 生成的关键词输入行数
  searchPlanRowsGenerated: number;   // 生成的搜索计划行数
  errors: string[];             // 错误信息
};

// ── 7. AI 语义关键词分析结果 ──────────────────────────────────
export type AiKeywordAnalysis = {
  /** AI 推理过程：逐步分析商品本质、组成和市场情况 */
  reasoning: string;
  /** AI 推荐的 1688 搜索词（5-15字，去掉采购方语境词，使用卖家视角） */
  suggested_keyword: string;
  /** 成功页和导入流程使用的备选搜索词 */
  alt_search_terms?: string[];
  /** 兼容旧字段名的备选搜索词 */
  alternative_keywords?: string[];
  /** 商品是整体系统还是零部件，如"整体系统，非零部件" */
  product_type: string;
  /** 商品结构概述，如"由不锈钢立柱和钢化玻璃面板组成的完整护栏系统" */
  structure_summary: string;
  /** 主体/组件/零部件角色，用于后续详情页参数匹配 */
  component_roles: string;
  /** 1688 上的可购买情况，如"可按规格直接购买" 或 "通常需商家定制" */
  purchase_type: string;
  /** 标准化结论：成功=可继续采购搜索，failed=缺关键采购信息需人工补充 */
  outcome: "success" | "failed";
  /** 是否可以直接在 1688 通过商品关键词搜索 */
  can_search_1688: boolean;
  /** 当前判定仍然缺失的关键采购字段 */
  missing_required_fields: string[];
  /** 失败原因，成功时留空 */
  failure_reason: string;
  /** 人工补充建议，成功时可留空 */
  human_fix_hint: string;
  /** 当前已具备的关键采购属性摘要 */
  required_attributes_summary: string;
  /** 字母/数字/型号/规范参数的采购语义解读 */
  parameter_interpretations?: ProcurementParameterInterpretation[];
  /** 型号唯一指向采购对象时由 LLM 填写的型号字符串，用于自动录入字典；否则为空字符串 */
  identified_unique_model?: string;
};

export type StandardizationExecutionMode = "online" | "offline";

export type ProcurementDictionaryTermType = "unique_model" | "parameter" | "brand" | "standard" | "general";

export type ProcurementParameterInterpretation = {
  term: string;
  term_type: ProcurementDictionaryTermType;
  product_context: string;
  interpretation: string;
  evidence: string;
};

export type OfflineCombinedStandardizationResult = {
  material: string;
  usage: string;
  simplified_spec: string;
  brand_term: string;
  keyword_parameter_terms: string[];
  modifier_terms: string[];
  alternative_terms: string[];
  reasoning: string;
  suggested_keyword: string;
  product_type: string;
  structure_summary: string;
  component_roles: string;
  purchase_type: string;
  outcome: "success" | "failed";
  can_search_1688: boolean;
  missing_required_fields: string[];
  failure_reason: string;
  human_fix_hint: string;
  required_attributes_summary: string;
  parameter_interpretations: ProcurementParameterInterpretation[];
  /** 型号唯一指向采购对象时由 LLM 填写的型号字符串，用于自动录入字典；否则为空字符串 */
  identified_unique_model?: string;
};

export type StandardizationTaskStatus = "pending" | "processing" | "stopping" | "completed" | "failed" | "stopped";

export type StandardizationTaskRow = {
  id?: string;
  batch_id: string;
  execution_mode: StandardizationExecutionMode;
  status: StandardizationTaskStatus;
  total_rows: number;
  processed_rows: number;
  success_rows: number;
  failed_rows: number;
  current_item: string;
  current_phase: string;
  error_message: string;
  created_at?: string;
  updated_at?: string;
  started_at?: string | null;
  finished_at?: string | null;
};

export type StandardizationTaskItemStatus = "pending" | "processing" | "success" | "failed";

export type StandardizationTaskItemRow = {
  id?: string;
  task_id: string;
  batch_id: string;
  source_material_id: string;
  status: StandardizationTaskItemStatus;
  source_snapshot: StandardizationSourceSnapshot;
  analysis_result: Record<string, unknown>;
  keyword_analysis: Record<string, unknown>;
  standardized_name: string;
  suggested_keyword: string;
  can_search_1688: boolean | null;
  missing_required_fields: string[];
  failure_reason: string;
  human_fix_hint: string;
  patched_fields: Record<string, unknown>;
  llm_model: string;
  retry_of_item_id: string | null;
  resolved_by_task_id: string | null;
  resolved_at?: string | null;
  created_at?: string;
  updated_at?: string;
};

export type SearchTaskStatus = "pending" | "processing" | "waiting_for_manual" | "pausing" | "paused" | "stopping" | "stopped" | "completed" | "failed";

export type SearchTaskRow = {
  id?: string;
  batch_id: string;
  account_id: string;
  pipeline_config: SearchPipelineConfig;
  contact_limit: number;
  headless: boolean;
  status: SearchTaskStatus;
  total_rows: number;
  processed_rows: number;
  completed_rows: number;
  failed_rows: number;
  stopped_rows: number;
  current_material_id?: string | null;
  current_item: string;
  error_message: string;
  errors: string[];
  result: Record<string, unknown>;
  created_at?: string;
  updated_at?: string;
  started_at?: string | null;
  paused_at?: string | null;
  finished_at?: string | null;
};

export type SearchTaskItemStatus = "pending" | "processing" | "completed" | "failed" | "stopped";

export type SearchTaskItemSnapshot = {
  material_id: string;
  name: string;
};

export type SearchTaskItemRow = {
  id?: string;
  task_id: string;
  batch_id: string;
  material_id: string;
  sort_order: number;
  material_name: string;
  status: SearchTaskItemStatus;
  item_snapshot: SearchTaskItemSnapshot;
  error_message: string;
  created_at?: string;
  updated_at?: string;
  started_at?: string | null;
  finished_at?: string | null;
};

export type StandardizedResultSourceType = "ai" | "manual";

export type StandardizedResultRow = {
  id?: string;
  batch_id: string;
  material_id: string;
  source_type: StandardizedResultSourceType;
  invoice_type: string;
  original_name: string;
  original_spec: string;
  standardized_name: string;
  category: string;
  brand: string;
  notes: string;
  delivery_address: string;
  primary_search_term: string;
  alt_search_terms: string[];
  standardized_spec: string;
  standardized_unit: string;
  quantity: number;
  product_type: string;
  llm_model: string;
  ai_reasoning: string;
  created_by?: string | null;
  updated_by?: string | null;
  created_at?: string;
  updated_at?: string;
};

// ── 8. keyword_process 行 ─────────────────────────────────────
export type KeywordProcessRow = {
  id?: string;
  batch_id: string;
  material_id: string;
  row_name: string;
  row_spec: string;
  row_brand: string;
  llm_model: string;
  ai_keyword_analysis: Record<string, unknown>;
  full_report: Record<string, unknown>;
  created_at?: string;
};

// ── 9. search_rounds 行 ──────────────────────────────────────
export type SearchRoundRow = {
  id?: string;
  task_id?: string | null;
  batch_id: string;
  material_id: string;
  search_round: number;
  run_type: "initial" | "followup";
  primary_keyword: string;
  search_strategy: string;
  stage_order?: number | null;
  stage_label?: string;
  stage_kind?: string;
  stage_main_keyword?: string;
  brand_keyword?: string;
  brand_keyword_hit_rate?: number | null;
  is_valid_search: boolean;
  visual_confidence: number | null;
  visual_reason: string;
  stop_reason: string;
  results_count: number;
  results: unknown[];
  screenshot_url: string;
  keyword_hit_rate: number | null;
  source_candidate_count?: number | null;
  qualified_result_count?: number | null;
  rejected_no_phone_count?: number | null;
  target_result_count?: number | null;
  shortage_reason?: string;
  require_phone_contact?: boolean;
  contact_enrichment_attempted?: boolean;
  contact_enrichment_skip_reason?: string;
  keyword_hit_rate_source?: string;
  keyword_hit_rate_reason?: string;
  keyword_hit_rate_sample_count?: number | null;
  created_at?: string;
};

// ── 10. best_match_images 行 ─────────────────────────────────
export type BestMatchImageRow = {
  id?: string;
  batch_id: string;
  material_id: string;
  image_url: string;
  offer_url: string;
  title: string;
  merchant_name: string;
  wangwang_url: string;
  selected_from_round: number | null;
  selected_from_keyword: string;
  method: string;
  reason: string;
  created_at?: string;
};

// ── 11. extended_best_matches 行 ─────────────────────────────
export type ExtendedBestMatchesRow = {
  id?: string;
  batch_id: string;
  material_id: string;
  report: Record<string, unknown>;
  created_at?: string;
};

// ── 12. image_search_results 行 ──────────────────────────────
export type ImageSearchResultRow = {
  id?: string;
  batch_id: string;
  material_id: string;
  is_valid_image_search: boolean;
  screenshot_url: string;
  top_titles: string[];
  similar_products: unknown[];
  text_rule: Record<string, unknown>;
  image_similarity: Record<string, unknown>;
  full_report: Record<string, unknown>;
  created_at?: string;
};

// ── 13. keyword_selections 行 ────────────────────────────────
export type KeywordSelectionRow = {
  id?: string;
  batch_id: string;
  material_id: string;
  main_keyword: string;
  judgment_reason: string;
  debug_data: Record<string, unknown>;
  created_at?: string;
};

// ── 14. final_results 行 ─────────────────────────────────────
export type FinalResultRow = {
  id?: string;
  task_id?: string | null;
  batch_id: string;
  material_id: string;
  source: string;
  main_keyword: string;
  product_count: number;
  products: unknown[];
  finished_at: string;
  created_at?: string;
};

// ── 15. final_result_products 行（父子合并展开，每条商品一行） ─
export type FinalResultProductRow = {
  id?: string;
  task_id?: string | null;
  batch_id: string;
  material_id: string;
  source: string;
  main_keyword: string;
  stage_order?: number | null;
  stage_label?: string;
  stage_kind?: string;
  stage_main_keyword?: string;
  stage_keyword_hit_rate?: number | null;
  is_placeholder?: boolean;
  placeholder_reason?: string;
  finished_at: string;
  rank: number;
  title: string;
  offer_url: string;
  image_url: string;
  merchant_name: string;
  merchant_url: string;
  wangwang_url: string;
  offer_screenshot_url: string;
  contact_page_url: string;
  detected_contacts: unknown[];
  score?: number | null;
  is_match?: boolean | null;
  reason?: string;
  has_phone_contact?: boolean;
  qualification_status?: string;
  contact_collection_reason?: string;
  created_at?: string;
};

// ── 16. extended_best_match_records 行（父子合并展开，每条记录一行） ─
export type ExtendedBestMatchRecordRow = {
  id?: string;
  batch_id: string;
  material_id: string;
  generated_at: string;
  rank: number;
  title: string;
  offer_url: string;
  image_url: string;
  merchant_name: string;
  merchant_url: string;
  wangwang_url: string;
  offer_screenshot_url: string;
  score: number | null;
  selected_from_round: number | null;
  selected_from_keyword: string;
  detected_contacts: unknown[];
  contact_page_url: string;
  created_at?: string;
};

// ── 17. 搜索管道配置（可由前端传入，控制搜索阶段和关键词组合）──
// 这些定义已抽到 `@app/shared-types` workspace，以保证前后端始终一致。
export {
  DEFAULT_SEARCH_PIPELINE_CONFIG,
  SEARCH_FIELD_LABELS,
  SEARCH_FIELD_ORDER,
  buildKeywordCombinationLabel,
  createDefaultKeywordCombination,
  normalizeKeywordCombination,
  normalizeKeywordCombinationFields,
  normalizeSearchPipelineConfig,
} from "@app/shared-types";
export type {
  KeywordCombination,
  SearchFieldType,
  SearchPipelineConfig,
} from "@app/shared-types";
