import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';

import { afterEach, describe, expect, it } from 'vitest';

import {
  buildFixedRuntimeLlmContext,
  dedupeFinalResultProductRowsByMerchant,
  getKeywordStageSearchRoundIncrement,
  isUnsafeProductTitle,
  resolveFinalResultProductTitle,
  resolveImageStageOutcome,
  resolveKeywordStagePlaceholderReason,
} from './row-pipeline-sync.ts';

const tempDirs: string[] = [];

afterEach(async () => {
  await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
});

describe('getKeywordStageSearchRoundIncrement', () => {
  it('uses searchPlanRows when available', () => {
    expect(getKeywordStageSearchRoundIncrement({
      keywordResult: { searchPlanRows: [{}, {}, {}] },
      initialRounds: [{}],
    })).toBe(3);
  });

  it('falls back to initialRounds when searchPlanRows is missing', () => {
    expect(getKeywordStageSearchRoundIncrement({
      keywordResult: {},
      initialRounds: [{}, {}],
    })).toBe(2);
  });

  it('always returns at least one round', () => {
    expect(getKeywordStageSearchRoundIncrement({
      keywordResult: {},
      initialRounds: [],
    })).toBe(1);
  });

  it('marks captcha-intercepted keyword stages as placeholders', () => {
    expect(resolveKeywordStagePlaceholderReason({
      validRound: null,
      initialRounds: [{ round_failure_reason: 'captcha_intercept' }],
    } as never)).toBe('captcha_intercept');
  });

  it('ignores generic round_failed placeholder reasons', () => {
    expect(resolveKeywordStagePlaceholderReason({
      validRound: null,
      initialRounds: [{ round_failure_reason: 'round_failed' }],
    } as never)).toBe('');
  });

  it('builds fixed runtime llm context with normalized text fields', () => {
    expect(buildFixedRuntimeLlmContext({
      targetRow: {
        名称: '  地脚螺栓  ',
        品牌: '  哈光  ',
        规格型号: ' M16 x 200 ',
      },
      analysis: {
        brand_term: '  ',
        simplified_spec: '  M16   x 200  ',
        material: '  钢结构  ',
      },
      aiKeywordAnalysis: {
        suggested_keyword: '  地脚螺栓  ',
        structure_summary: '  需要匹配钢结构用地脚螺栓。  ',
        product_type: '  紧固件  ',
      },
    } as never, [
      {
        round: 1,
        label: '主搜索词',
        query: '地脚螺栓',
        status: 'success',
        failure_reason: '',
      },
    ])).toEqual({
      primary_search_term: '地脚螺栓',
      standardized_name: '地脚螺栓',
      brand: '哈光',
      standardized_spec: 'M16 x 200',
      category: '钢结构',
      ai_reasoning: '需要匹配钢结构用地脚螺栓。',
      product_type: '紧固件',
    });
  });

  it('falls back to extended best matches when image stage fails', async () => {
    const searchRunDir = await mkdtemp(path.join(os.tmpdir(), 'row-pipeline-sync-'));
    tempDirs.push(searchRunDir);

    const reportDir = path.join(searchRunDir, 'extended-best-matches');
    await mkdir(reportDir, { recursive: true });
    await writeFile(
      path.join(reportDir, 'extended-best-matches-report.json'),
      JSON.stringify({
        generated_at: new Date().toISOString(),
        records: [
          {
            title: '木胶板 2440*1220*15mm',
            offer_url: 'https://detail.1688.com/offer/test.html',
            image_url: 'https://img.example.com/test.jpg',
            merchant_name: '测试商家',
            merchant_url: 'https://shop.example.com/test',
            wangwang_url: 'https://wangwang.example.com/test',
            offer_screenshot_path: '/tmp/test.jpg',
            contact_page_url: 'https://shop.example.com/test/contact',
            detected_contacts: [{ type: 'mobile', value: '13800000000' }],
          },
        ],
      }),
      'utf8',
    );

    const outcome = await resolveImageStageOutcome({
      search: {
        searchRunDir,
        bestMatchImage: { selected_from_keyword: '木胶板 2440*1220*15mm' },
        validRound: null,
        initialRounds: [],
      },
      imageResult: null,
      limit: 5,
    });

    expect(outcome.source).toBe('extended_best_match_fallback');
    expect(outcome.mainKeyword).toBe('木胶板 2440*1220*15mm');
    expect(outcome.products).toHaveLength(1);
    expect(outcome.products[0]).toMatchObject({
      title: '木胶板 2440*1220*15mm',
      merchant_name: '测试商家',
    });
  });

  it('returns an empty extended-best-match fallback when the report is missing', async () => {
    const searchRunDir = await mkdtemp(path.join(os.tmpdir(), 'row-pipeline-sync-'));
    tempDirs.push(searchRunDir);

    const outcome = await resolveImageStageOutcome({
      search: {
        searchRunDir,
        bestMatchImage: { selected_from_keyword: '木胶板 2440*1220*15mm' },
        validRound: null,
        initialRounds: [],
      },
      imageResult: null,
      limit: 5,
    });

    expect(outcome.source).toBe('extended_best_match_fallback');
    expect(outcome.mainKeyword).toBe('木胶板 2440*1220*15mm');
    expect(outcome.products).toEqual([]);
  });
});

describe('resolveFinalResultProductTitle', () => {
  const generatedTitle = 'hO7TX2rRhkJDVqeFGucSXQ|aetU-Q|BUpWdg_0|By-uiQ|0';

  it('treats generated resource identifiers as unsafe product titles', () => {
    expect(isUnsafeProductTitle(generatedTitle)).toBe(true);
  });

  it('falls back to the candidate title-text before writing final_result_products', () => {
    expect(resolveFinalResultProductTitle({
      title: generatedTitle,
      'title-text': '1kV冷缩电缆终端头 120mm2 铝芯',
      offer_url: 'https://detail.1688.com/offer/123.html',
    })).toBe('1kV冷缩电缆终端头 120mm2 铝芯');
  });

  it('does not treat a sanitized generated resource identifier as a usable title', () => {
    expect(resolveFinalResultProductTitle({
      title: 'vZepVk9VbDxJ_LdQ9WgFhQ|aet_Kg|BUpWdg_0|By-uiQ|0',
      'title-text': '岩棉净化板湖南厂家直发阻燃防火保温车间隔断吊顶岩棉夹芯彩钢板',
      offer_url: 'https://detail.1688.com/offer/1028505114295.html',
    })).toBe('岩棉净化板湖南厂家直发阻燃防火保温车间隔断吊顶岩棉夹芯彩钢板');
  });

  it('falls back to search round results with the same offer_url when the stored title is dirty', () => {
    expect(resolveFinalResultProductTitle({
      title: generatedTitle,
      offer_url: 'https://detail.1688.com/offer/123.html?spm=a261y',
    }, [
      {
        title: '1kV冷缩电缆终端头 120mm2 铝芯',
        offer_url: 'https://detail.1688.com/offer/123.html',
      },
    ])).toBe('1kV冷缩电缆终端头 120mm2 铝芯');
  });
});

describe('dedupeFinalResultProductRowsByMerchant', () => {
  it('keeps one row per merchant before final_result_products insert', () => {
    const rows = dedupeFinalResultProductRowsByMerchant([
      {
        merchant_name: '商家 A',
        merchant_url: 'https://shop123.1688.com/?spm=a261y',
        offer_url: 'https://detail.1688.com/offer/1.html',
      },
      {
        merchant_name: '商家 A',
        merchant_url: 'http://shop123.1688.com/',
        offer_url: 'https://detail.1688.com/offer/2.html',
      },
      {
        merchant_name: '商家 B',
        merchant_url: 'https://shop456.1688.com',
        offer_url: 'https://detail.1688.com/offer/3.html',
      },
    ]);

    expect(rows.map((row) => row.offer_url)).toEqual([
      'https://detail.1688.com/offer/1.html',
      'https://detail.1688.com/offer/3.html',
    ]);
  });
});
