import { describe, expect, it } from 'vitest';
import {
  buildTitleFallback,
  buildTitleFromGoal,
  buildTitlePrompt,
  isUrlOnlyTitleInput,
  stripUrlsForTitle,
} from './title-generation.js';

describe('title generation helpers', () => {
  it('detects URL-only input', () => {
    expect(isUrlOnlyTitleInput('https://example.com/articles/123')).toBe(true);
    expect(isUrlOnlyTitleInput('  https://example.com/a\nhttps://example.com/b  ')).toBe(true);
    expect(isUrlOnlyTitleInput('このURLを調べて https://example.com/articles/123')).toBe(false);
  });

  it('does not pass URL-only input to the LLM prompt', () => {
    expect(buildTitlePrompt('https://example.com/articles/123')).toBeNull();
    expect(buildTitleFallback('https://example.com/articles/123')).toBe('URLの確認');
  });

  it('masks URLs before building the prompt and fallback', () => {
    const input = 'このページを要約して https://example.com/secret/path?token=abc';

    expect(stripUrlsForTitle(input)).toBe('このページを要約して [URL]');
    expect(buildTitleFallback(input)).toBe('このページを要約して [URL]');
    expect(buildTitlePrompt(input)).toContain('このページを要約して [URL]');
    expect(buildTitlePrompt(input)).not.toContain('example.com');
  });
});

describe('buildTitleFromGoal', () => {
  it('uses the first non-empty line of the goal', () => {
    expect(buildTitleFromGoal('議事録を作成する\n\n詳細な背景説明...')).toBe('議事録を作成する');
  });

  it('strips markdown heading and list markers', () => {
    expect(buildTitleFromGoal('## 売上レポートをまとめる')).toBe('売上レポートをまとめる');
    expect(buildTitleFromGoal('- 顧客リストを整理する')).toBe('顧客リストを整理する');
  });

  it('caps length at 40 chars', () => {
    const long = 'あ'.repeat(80);
    expect(buildTitleFromGoal(long).length).toBe(40);
  });

  it('masks URLs and returns empty for URL-only goals', () => {
    expect(buildTitleFromGoal('https://example.com/x')).toBe('');
    expect(buildTitleFromGoal('要約して https://example.com/x')).toBe('要約して [URL]');
  });

  it('returns empty string for blank goal so callers skip the update', () => {
    expect(buildTitleFromGoal('')).toBe('');
    expect(buildTitleFromGoal('   \n  ')).toBe('');
  });
});
