File size: 4,347 Bytes
2dfd598
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
502e615
2dfd598
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/**
 * Utility for parsing, segmenting, and reconstructing Markdown (.md) files.
 * Preserves section headers, lists, links, bold/italic markup, and spacing.
 */

/**
 * Splits a Markdown document into section-level translatable chunks.
 * Groups content by major headers (###) or logical section blocks.
 * Reduces 280 tiny fragments down to ~15 complete section chunks!
 */
export function parseMarkdownToSegments(mdContent) {
  if (!mdContent || typeof mdContent !== 'string') {
    return { segments: [], structureMap: [] };
  }

  const normalized = mdContent.replace(/\r\n/g, '\n').trim();
  if (!normalized) return { segments: [], structureMap: [] };

  // Split by section headers (### or ## or #)
  const lines = normalized.split('\n');
  const sections = [];
  let currentSection = { header: '', bodyLines: [] };

  lines.forEach(line => {
    const headerMatch = line.match(/^(#{1,6}\s+.*)/);
    if (headerMatch) {
      if (currentSection.header || currentSection.bodyLines.length > 0) {
        sections.push(currentSection);
      }
      currentSection = { header: line.trim(), bodyLines: [] };
    } else {
      currentSection.bodyLines.push(line);
    }
  });

  if (currentSection.header || currentSection.bodyLines.length > 0) {
    sections.push(currentSection);
  }

  // Build segments and structureMap from sections
  const segments = [];
  const structureMap = [];

  sections.forEach((sec, idx) => {
    const fullText = [sec.header, sec.bodyLines.join('\n')].filter(Boolean).join('\n\n').trim();
    if (!fullText) return;

    const segId = `md_section_${idx + 1}`;
    segments.push({
      id: segId,
      original: fullText,
      type: 'section',
      headerTitle: sec.header ? sec.header.replace(/[\*#]/g, '').trim() : `Section ${idx + 1}`
    });

    structureMap.push({
      id: segId,
      type: 'section'
    });
  });

  return { segments, structureMap };
}

/**
 * Generates an optimized, token-efficient Knowledge Base context for a specific segment.
 */
export function extractSmartMarkdownContext(currentSegmentIndex, segments) {
  if (!segments || segments.length === 0) return '';

  const currentSeg = segments[currentSegmentIndex];
  if (!currentSeg) return '';

  const topHeaders = segments
    .slice(0, 6)
    .map(s => s.headerTitle || '')
    .filter(Boolean)
    .join(' | ');

  const prevTitle = segments[currentSegmentIndex - 1]?.headerTitle || '';
  const nextTitle = segments[currentSegmentIndex + 1]?.headerTitle || '';

  return `Document Knowledge Base Topics: [${topHeaders}]
Current Section: "${currentSeg.headerTitle || 'General FAQ'}"
Context Neighbors: "${prevTitle ? 'Prev: ' + prevTitle : ''} ${nextTitle ? '| Next: ' + nextTitle : ''}"`;
}

/**
 * Automatically compacts user-provided custom Knowledge Base text if it's long.
 */
export function compactUserContext(text, maxChars = 1200) {
  if (!text || typeof text !== 'string') return '';
  const trimmed = text.trim();
  if (trimmed.length <= maxChars) return trimmed;

  const lines = trimmed.split('\n').map(l => l.trim()).filter(Boolean);
  
  const keyLines = lines.filter(line => {
    const l = line.toLowerCase();
    return l.includes('brand') || l.includes('brend') || l.includes('rule') || l.includes('qayda') ||
           l.includes('term') || l.includes('sözlü') || l.includes('ton') || l.includes('voice') ||
           l.includes('do not') || l.includes('etmə') || l.includes('always') || l.includes('həmişə') ||
           l.includes('never') || l.includes('qətiyyən') || l.includes(':') || l.includes('->');
  });

  if (keyLines.length >= 2 && keyLines.join('\n').length <= maxChars) {
    return `[COMPACT KNOWLEDGE SUMMARY]:\n${keyLines.join('\n')}`;
  }

  return `${trimmed.slice(0, maxChars)}...\n[User context automatically compacted from ${trimmed.length} characters to ${maxChars}]`;
}

/**
 * Reconstructs a Markdown document from translated section chunks.
 */
export function reconstructMarkdown(structureMap, translatedSegmentsMap) {
  const reconstructedSections = [];

  structureMap.forEach(item => {
    const segData = translatedSegmentsMap[item.id];
    if (segData) {
      const translatedText = segData.claude || segData.translation || segData.original;
      reconstructedSections.push(translatedText.trim());
    }
  });

  return reconstructedSections.join('\n\n');
}