import type { ChatMessage } from '../../agent';
import { escapeYamlString, summarizeForTitle, summarizeTextForWiki } from './textHelpers';

/**
 * "Wiki raw data" 마크다운 빌더 — 사용자가 현재 chat 을 active brain 의
 * `raw-data/` 디렉토리에 저장할 때 쓰는 통합 markdown 포맷.
 *
 * 구조: YAML frontmatter (title, category, created_at, source, brain, status) +
 * Category / What This Contains / Expected Value / Discovery Process /
 * Conclusion / Coding Implementation Notes / Source Brain / Raw Conversation
 * Transcript 섹션. assistant 메시지 중 `rationale` 메타가 있는 것들은 "Process
 * Note" 로 따로 모아 *발견 과정* 섹션에 표시.
 *
 * Stateless — sidebarProvider 의 옛 private 메서드를 그대로 추출. 의존: textHelpers
 * 의 escape/summary 헬퍼들 + ChatMessage 타입.
 */
export function buildWikiRawMarkdown(history: ChatMessage[], meta: {
    category: string;
    expectedValue: string;
    activeBrainName: string;
    activeBrainPath: string;
    createdAt: string;
}): string {
    const firstUserMessage = history.find((message) => message.role === 'user')?.content || '';
    const latestUserMessage = [...history].reverse().find((message) => message.role === 'user')?.content || '';
    const latestAssistantMessage = [...history].reverse().find((message) => message.role === 'assistant')?.content || '';

    const rationaleNotes = history
        .filter((message) => message.role === 'assistant' && message.rationale)
        .map((message, index) => [
            `### Process Note ${index + 1}`,
            message.rationale?.problem ? `- Problem: ${message.rationale.problem}` : '',
            message.rationale?.goal ? `- Goal: ${message.rationale.goal}` : '',
            message.rationale?.reasoning ? `- Reasoning: ${message.rationale.reasoning}` : '',
        ].filter(Boolean).join('\n'))
        .join('\n\n');

    const transcript = history
        .map((message, index) => [
            `### ${index + 1}. ${message.role.toUpperCase()}`,
            '',
            message.content.trim() || '(empty)',
        ].join('\n'))
        .join('\n\n');

    return [
        '---',
        `title: "${escapeYamlString(summarizeForTitle(firstUserMessage))}"`,
        `category: "${escapeYamlString(meta.category)}"`,
        `created_at: "${meta.createdAt}"`,
        `source: "Astra conversation"`,
        `brain: "${escapeYamlString(meta.activeBrainName)}"`,
        'status: raw',
        '---',
        '',
        `# ${summarizeForTitle(firstUserMessage)}`,
        '',
        '## Category',
        meta.category,
        '',
        '## What This Contains',
        summarizeTextForWiki(latestAssistantMessage || firstUserMessage),
        '',
        '## Expected Value',
        meta.expectedValue,
        '',
        '## Discovery Process',
        rationaleNotes || 'No explicit rationale metadata was captured. Use the transcript below to reconstruct the reasoning path.',
        '',
        '## Conclusion',
        [
            'This conclusion was derived from the latest user request and assistant response.',
            '',
            `- Latest user request: ${summarizeTextForWiki(latestUserMessage)}`,
            `- Latest assistant conclusion: ${summarizeTextForWiki(latestAssistantMessage)}`,
        ].join('\n'),
        '',
        '## Coding Implementation Notes',
        'Use this section to turn the raw transcript into a wiki-ready implementation note. Capture which files changed, why they changed, and what verification was run.',
        '',
        '## Source Brain',
        `- Name: ${meta.activeBrainName}`,
        `- Path: ${meta.activeBrainPath}`,
        '',
        '## Raw Conversation Transcript',
        transcript,
        '',
    ].join('\n');
}

/**
 * 파일명 안전 timestamp — ISO 문자열의 `:` 와 `.` 을 `-` 로, `T` 를 `_` 로,
 * 끝의 `Z` 제거. 결과: `2026-05-24_14-30-45-123` 같은 패턴.
 */
export function formatTimestampForFile(date: Date): string {
    return date.toISOString().replace(/[:.]/g, '-').replace('T', '_').replace('Z', '');
}
