import { describe, expect, it } from "vitest";

import type { SearchPipelineConfig } from "../core/types.ts";
import {
  annotateStageProducts,
  buildMerchantKey,
  buildPlaceholderStageProduct,
  buildSearchExecutionStages,
  filterProductsWithDetectedPhoneContacts,
  mergeStageProducts,
} from "./multi-stage-results.ts";

describe("buildSearchExecutionStages", () => {
  it("always uses a single fixed-runtime keyword stage regardless of configured combinations", () => {
    const config: SearchPipelineConfig = {
      keywordSearchEnabled: true,
      imageSearchEnabled: true,
      keywordCombinations: [
        { fields: ["standardized_name", "standardized_spec"], label: "标准化名称+标准化规格" },
        { fields: ["standardized_name", "brand"], label: "标准化名称+品牌" },
      ],
      includeAiKeyword: true,
    };

    const stages = buildSearchExecutionStages(config);

    expect(stages).toHaveLength(1);
    expect(stages[0]).toMatchObject({ kind: "keyword", label: "关键词搜索（AI 自动多轮）", stageOrder: 1 });

    if (stages[0]?.kind === "keyword") {
      expect(stages[0].pipelineConfig.includeAiKeyword).toBe(false);
      expect(stages[0].pipelineConfig.keywordCombinations).toEqual([]);
      expect(stages[0].mode).toBe("fixed_runtime");
      expect(stages[0].fields).toEqual([]);
      expect(stages[0].requiresBrandHitGuard).toBe(false);
    }
  });

  it("returns a single fixed-runtime keyword stage when keyword search is enabled", () => {
    const config: SearchPipelineConfig = {
      keywordSearchEnabled: true,
      imageSearchEnabled: false,
      keywordCombinations: [],
      includeAiKeyword: true,
    };

    const stages = buildSearchExecutionStages(config);

    expect(stages).toHaveLength(1);
    expect(stages[0]).toMatchObject({ kind: "keyword", label: "关键词搜索（AI 自动多轮）", stageOrder: 1 });
    if (stages[0]?.kind === "keyword") {
      expect(stages[0].pipelineConfig.includeAiKeyword).toBe(false);
      expect(stages[0].pipelineConfig.keywordCombinations).toEqual([]);
      expect(stages[0].mode).toBe("fixed_runtime");
      expect(stages[0].requiresBrandHitGuard).toBe(false);
    }
  });
});

describe("mergeStageProducts", () => {
  it("normalizes merchant identity before falling back to offer urls", () => {
    expect(buildMerchantKey({
      merchant_url: "https://shop123.1688.com/?spm=a261y",
      contact_page_url: "",
      merchant_name: "商家 A",
      offer_url: "https://detail.1688.com/offer/1.html",
      title: "商品 1",
    })).toBe("merchant_url:shop123.1688.com");

    expect(buildMerchantKey({
      merchant_url: "http://shop123.1688.com/",
      contact_page_url: "",
      merchant_name: "商家 A",
      offer_url: "https://detail.1688.com/offer/2.html",
      title: "商品 2",
    })).toBe("merchant_url:shop123.1688.com");

    expect(buildMerchantKey({
      merchant_url: "",
      contact_page_url: "",
      merchant_name: "",
      wangwang_url: "https://air.1688.com/app/ocms-fusion-components-1688/def_cbu_web_im/index.html?touid=cnalichn%E6%B5%8B%E8%AF%95%E5%95%86%E5%AE%B6&siteid=cnalichn#/",
      offer_url: "https://detail.1688.com/offer/3.html",
      title: "商品 3",
    })).toBe("wangwang:cnalichn测试商家");
  });

  it("keeps stage order while deduplicating repeated merchants across stages", () => {
    const stageOne = annotateStageProducts(
      [
        {
          index: 1,
          title: "商家 A 商品",
          offer_url: "https://detail.1688.com/offer/a-1.html",
          image_url: "",
          merchant_name: "商家 A",
          merchant_url: "https://shop.1688.com/a",
          wangwang_url: "",
          offer_screenshot_path: "",
          contact_page_url: "https://shop.1688.com/a/contact",
          detected_contacts: [],
        },
        {
          index: 2,
          title: "商家 B 商品",
          offer_url: "https://detail.1688.com/offer/b-1.html",
          image_url: "",
          merchant_name: "商家 B",
          merchant_url: "https://shop.1688.com/b",
          wangwang_url: "",
          offer_screenshot_path: "",
          contact_page_url: "https://shop.1688.com/b/contact",
          detected_contacts: [],
        },
      ],
      {
        source: "keyword_search",
        mainKeyword: "名称+型号",
        stageLabel: "名称+型号",
        stageOrder: 1,
        stageKind: "keyword",
        stageKeywordHitRate: 0.75,
      },
    );

    const stageTwo = annotateStageProducts(
      [
        {
          index: 1,
          title: "商家 B 另一商品",
          offer_url: "https://detail.1688.com/offer/b-2.html",
          image_url: "",
          merchant_name: "商家 B",
          merchant_url: "https://shop.1688.com/b",
          wangwang_url: "",
          offer_screenshot_path: "",
          contact_page_url: "https://shop.1688.com/b/contact",
          detected_contacts: [],
        },
        {
          index: 2,
          title: "商家 C 商品",
          offer_url: "https://detail.1688.com/offer/c-1.html",
          image_url: "",
          merchant_name: "商家 C",
          merchant_url: "https://shop.1688.com/c",
          wangwang_url: "",
          offer_screenshot_path: "",
          contact_page_url: "https://shop.1688.com/c/contact",
          detected_contacts: [],
        },
      ],
      {
        source: "keyword_search",
        mainKeyword: "名称+品牌",
        stageLabel: "名称+品牌",
        stageOrder: 2,
        stageKind: "keyword",
        stageKeywordHitRate: 0.4,
      },
    );

    const result = mergeStageProducts(stageOne, stageTwo);

    expect(result.insertedCount).toBe(1);
    expect(result.duplicateCount).toBe(1);
    expect(result.inserted).toHaveLength(1);
    expect(result.merged).toHaveLength(3);
    expect(result.merged.map((product) => product.merchant_name)).toEqual(["商家 A", "商家 B", "商家 C"]);
    expect(result.merged.map((product) => product.main_keyword)).toEqual(["名称+型号", "名称+型号", "名称+品牌"]);
    expect(result.inserted[0]?.stage_keyword_hit_rate).toBe(0.4);
  });

  it("treats same merchant with different offer urls as one final merchant", () => {
    const stageOne = annotateStageProducts(
      [
        {
          index: 1,
          title: "商家 A 商品 1",
          offer_url: "https://detail.1688.com/offer/a-1.html",
          image_url: "",
          merchant_name: "商家 A",
          merchant_url: "https://shop.1688.com/a?spm=a261y",
          wangwang_url: "",
          offer_screenshot_path: "",
          contact_page_url: "",
          detected_contacts: [],
        },
      ],
      {
        source: "keyword_search",
        mainKeyword: "名称+型号",
        stageLabel: "名称+型号",
        stageOrder: 1,
        stageKind: "keyword",
        stageKeywordHitRate: 0.75,
      },
    );

    const stageTwo = annotateStageProducts(
      [
        {
          index: 1,
          title: "商家 A 商品 2",
          offer_url: "https://detail.1688.com/offer/a-2.html",
          image_url: "",
          merchant_name: "商家 A",
          merchant_url: "http://shop.1688.com/a/",
          wangwang_url: "",
          offer_screenshot_path: "",
          contact_page_url: "",
          detected_contacts: [],
        },
        {
          index: 2,
          title: "商家 B 商品",
          offer_url: "https://detail.1688.com/offer/b-1.html",
          image_url: "",
          merchant_name: "商家 B",
          merchant_url: "https://shop.1688.com/b",
          wangwang_url: "",
          offer_screenshot_path: "",
          contact_page_url: "",
          detected_contacts: [],
        },
      ],
      {
        source: "keyword_search",
        mainKeyword: "名称+品牌",
        stageLabel: "名称+品牌",
        stageOrder: 2,
        stageKind: "keyword",
        stageKeywordHitRate: 0.4,
      },
    );

    const result = mergeStageProducts(stageOne, stageTwo);

    expect(result.duplicateCount).toBe(1);
    expect(result.inserted.map((product) => product.merchant_name)).toEqual(["商家 B"]);
    expect(result.merged.map((product) => product.offer_url)).toEqual([
      "https://detail.1688.com/offer/a-1.html",
      "https://detail.1688.com/offer/b-1.html",
    ]);
  });

  it("builds a placeholder stage row for brand zero-hit stop", () => {
    const placeholder = buildPlaceholderStageProduct({
      source: "keyword_search",
      mainKeyword: "球墨铸铁井盖 沪工",
      stageLabel: "名称+品牌",
      stageOrder: 2,
      stageKind: "keyword",
      stageKeywordHitRate: 0,
      placeholderReason: "brand_zero_hit_stop",
    });

    expect(placeholder.is_placeholder).toBe(true);
    expect(placeholder.placeholder_reason).toBe("brand_zero_hit_stop");
    expect(placeholder.stage_main_keyword).toBe("球墨铸铁井盖 沪工");
    expect(placeholder.stage_keyword_hit_rate).toBe(0);
    expect(placeholder.title).toContain("品牌命中率为 0%");
  });

  it("drops merchants that do not contain phone or mobile contacts", () => {
    const filtered = filterProductsWithDetectedPhoneContacts([
      {
        index: 1,
        title: "商家 A 商品",
        offer_url: "https://detail.1688.com/offer/a-1.html",
        image_url: "",
        merchant_name: "商家 A",
        merchant_url: "https://shop.1688.com/a",
        wangwang_url: "",
        offer_screenshot_path: "",
        contact_page_url: "https://shop.1688.com/a/contact",
        detected_contacts: [],
      },
      {
        index: 2,
        title: "商家 B 商品",
        offer_url: "https://detail.1688.com/offer/b-1.html",
        image_url: "",
        merchant_name: "商家 B",
        merchant_url: "https://shop.1688.com/b",
        wangwang_url: "",
        offer_screenshot_path: "",
        contact_page_url: "https://shop.1688.com/b/contact",
        detected_contacts: [{ type: "email", value: "sales@example.com" }],
      },
      {
        index: 3,
        title: "商家 C 商品",
        offer_url: "https://detail.1688.com/offer/c-1.html",
        image_url: "",
        merchant_name: "商家 C",
        merchant_url: "https://shop.1688.com/c",
        wangwang_url: "",
        offer_screenshot_path: "",
        contact_page_url: "https://shop.1688.com/c/contact",
        detected_contacts: [{ type: "mobile", value: "17736998988" }],
      },
      {
        index: 4,
        title: "商家 D 商品",
        offer_url: "https://detail.1688.com/offer/d-1.html",
        image_url: "",
        merchant_name: "商家 D",
        merchant_url: "https://shop.1688.com/d",
        wangwang_url: "",
        offer_screenshot_path: "",
        contact_page_url: "https://shop.1688.com/d/contact",
        detected_contacts: [{ type: "mobile", value: "86" }],
      },
    ]);

    expect(filtered.droppedCount).toBe(3);
    expect(filtered.filtered).toHaveLength(1);
    expect(filtered.filtered[0]?.merchant_name).toBe("商家 C");
  });
});
