const URL_RE = /\bhttps?:\/\/[^\s<>"')\]]+|\bwww\.[^\s<>"')\]]+/gi;

export function stripUrlsForTitle(input: string): string {
  return input.replace(URL_RE, '[URL]').replace(/\s+/g, ' ').trim();
}

export function isUrlOnlyTitleInput(input: string): boolean {
  const trimmed = input.trim();
  if (!trimmed) return false;
  return stripUrlsForTitle(trimmed).replace(/\[URL\]/g, '').trim().length === 0;
}

export function buildTitleFallback(input: string): string {
  if (isUrlOnlyTitleInput(input)) return 'URLの確認';
  return stripUrlsForTitle(input).slice(0, 40).trim() || '新しい依頼';
}

/**
 * Derive a concise task title from the Mission Brief `goal` set by the agent.
 * Used at runtime (no LLM call): the agent already restates the user's
 * requirement as `goal` via MissionUpdate, so we take its first non-empty
 * line, strip markdown list/heading markers and URLs, and cap the length.
 * Returns '' when nothing usable remains so callers can skip the update.
 */
export function buildTitleFromGoal(goal: string): string {
  const firstLine = goal
    .split('\n')
    .map(l => l.trim())
    .find(l => l.length > 0) ?? '';
  const cleaned = firstLine.replace(/^#{1,6}\s*/, '').replace(/^[-*+]\s+/, '');
  if (isUrlOnlyTitleInput(cleaned)) return '';
  return stripUrlsForTitle(cleaned).slice(0, 40).trim();
}

export function buildTitlePrompt(input: string): string | null {
  if (isUrlOnlyTitleInput(input)) return null;
  const sanitized = stripUrlsForTitle(input).slice(0, 500);
  return [
    '以下の依頼内容から20文字以内の簡潔なタイトルを日本語で生成してください。',
    'URLそのものから内容を推測しないでください。URLは必要なら「URL」として扱ってください。',
    'タイトルのみ出力してください。',
    '',
    sanitized,
  ].join('\n');
}
