/**
 * AI 入口页（一级）→ AI 对话页（二级）联动契约
 *
 * ChatHomePagePattern 在 Hero ChatInput 发送或模板卡启动后，
 * 通过本模块构造 handoff payload，交给 ChatConversationPattern 承接。
 */

import { CHAT_DEMO_PLATFORM_NAME } from './chat-conversation-demo.js';

export const CHAT_HOME_CONVERSATION_FLOW_ID = 'chat-home-to-conversation';

export const CHAT_HOME_CONVERSATION_FLOW = {
  id: CHAT_HOME_CONVERSATION_FLOW_ID,
  parentPattern: 'chat-home-page',
  parentComponent: 'ChatHomePagePattern',
  childPattern: 'chat-conversation-page',
  childComponent: 'ChatConversationPattern',
  triggers: ['hero-chat-input-send', 'template-card-start'],
};

const DEFAULT_PLATFORM_NAME = CHAT_DEMO_PLATFORM_NAME;
const DEFAULT_TITLE_MAX_LEN = 24;

export function deriveConversationTitleFromPrompt(text, maxLen = DEFAULT_TITLE_MAX_LEN) {
  const trimmed = String(text || '').trim();
  if (!trimmed) return '新会话';
  if (trimmed.length <= maxLen) return trimmed;
  return `${trimmed.slice(0, maxLen)}…`;
}

export function createBootstrapSendSignal(text, seed = Date.now(), meta = {}) {
  const trimmed = String(text || '').trim();
  return {
    text: trimmed,
    seed,
    source: meta.source,
    segments: meta.segments,
    attachments: meta.attachments,
  };
}

/**
 * @param {object} params
 * @param {string} params.text — 用户首条输入
 * @param {object} [params.ctx] — ChatInput onSend 第二参数
 * @param {string} [params.platformName]
 * @param {number} [params.seed]
 */
export function buildChatHomeConversationHandoff({
  text,
  ctx = {},
  platformName = DEFAULT_PLATFORM_NAME,
  seed = Date.now(),
}) {
  const trimmed = String(text || '').trim();
  const bootstrapSendSignal = createBootstrapSendSignal(trimmed, seed, {
    source: ctx?.source || 'chat-home-hero-send',
    segments: ctx?.segments,
    attachments: ctx?.attachments,
  });

  return {
    flowId: CHAT_HOME_CONVERSATION_FLOW_ID,
    text: trimmed,
    title: deriveConversationTitleFromPrompt(trimmed),
    platformName,
    bootstrapSendSignal,
    source: ctx?.source || 'chat-home-hero-send',
    ctx,
  };
}
