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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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
#!/usr/bin/env python3
"""
Document Segmentation MCP Server

This MCP server provides intelligent document segmentation and retrieval functions for handling
large research papers and technical documents that exceed LLM token limits.

==== CORE FUNCTIONALITY ====
1. Analyze document structure and type using semantic content analysis
2. Create intelligent segments based on content semantics, not just structure
3. Provide query-aware segment retrieval with relevance scoring
4. Support both structured (papers with headers) and unstructured documents
5. Configurable segmentation strategies based on document complexity

==== MCP TOOLS PROVIDED ====

📄 analyze_and_segment_document(paper_dir: str, force_refresh: bool = False)
   Purpose: Analyzes document structure and creates intelligent segments
   - Detects document type (research paper, technical doc, algorithm-focused, etc.)
   - Selects optimal segmentation strategy based on content analysis
   - Creates semantic segments preserving algorithm and concept integrity
   - Stores segmentation index for efficient retrieval
   - Returns: JSON with segmentation status, strategy used, and segment count

📖 read_document_segments(paper_dir: str, query_type: str, keywords: List[str] = None,
                         max_segments: int = 3, max_total_chars: int = None)
   Purpose: Intelligently retrieves relevant document segments based on query context
   - query_type: "concept_analysis", "algorithm_extraction", or "code_planning"
   - Uses semantic relevance scoring to rank segments
   - Applies query-specific filtering and keyword matching
   - Dynamically calculates optimal character limits based on content complexity
   - Returns: JSON with selected segments optimized for the specific query type

📋 get_document_overview(paper_dir: str)
   Purpose: Provides high-level overview of document structure and available segments
   - Shows document type and segmentation strategy used
   - Lists all segments with titles, content types, and relevance scores
   - Displays segment statistics (character counts, keyword summaries)
   - Returns: JSON with complete document analysis metadata

==== SEGMENTATION STRATEGIES ====
- semantic_research_focused: For academic papers with complex algorithmic content
- algorithm_preserve_integrity: Maintains algorithm blocks and formula chains intact
- concept_implementation_hybrid: Merges related concepts with implementation details
- semantic_chunking_enhanced: Advanced boundary detection for long documents
- content_aware_segmentation: Adaptive chunking based on content density

==== INTELLIGENT FEATURES ====
- Semantic boundary detection (not just structural)
- Algorithm block identification and preservation
- Formula chain recognition and grouping
- Concept-implementation relationship mapping
- Multi-level relevance scoring (content type, importance, keyword matching)
- Backward compatibility with existing document indexes
- Configurable via mcp_agent.config.yaml (enabled/disabled, size thresholds)

Usage:
python tools/document_segmentation_server.py
"""

import os
import re
import json
import sys
import io
from typing import Dict, List, Tuple
import hashlib
import logging
from datetime import datetime
from dataclasses import dataclass, asdict

# Set standard output encoding to UTF-8
if sys.stdout.encoding != "utf-8":
    try:
        if hasattr(sys.stdout, "reconfigure"):
            sys.stdout.reconfigure(encoding="utf-8")
            sys.stderr.reconfigure(encoding="utf-8")
        else:
            sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding="utf-8")
            sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding="utf-8")
    except Exception as e:
        print(f"Warning: Could not set UTF-8 encoding: {e}")

# Import MCP related modules
from mcp.server.fastmcp import FastMCP

# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Create FastMCP server instance
mcp = FastMCP("document-segmentation-server")


@dataclass
class DocumentSegment:
    """Represents a document segment with metadata"""

    id: str
    title: str
    content: str
    content_type: str  # "introduction", "methodology", "algorithm", "results", etc.
    keywords: List[str]
    char_start: int
    char_end: int
    char_count: int
    relevance_scores: Dict[str, float]  # Scores for different query types
    section_path: str  # e.g., "3.2.1" for nested sections


@dataclass
class DocumentIndex:
    """Document index containing all segments and metadata"""

    document_path: str
    document_type: str  # "academic_paper", "technical_doc", "code_doc", "general"
    segmentation_strategy: str
    total_segments: int
    total_chars: int
    segments: List[DocumentSegment]
    created_at: str


class DocumentAnalyzer:
    """Enhanced document analyzer using semantic content analysis instead of mechanical structure detection"""

    # More precise semantic indicators, weighted by importance
    ALGORITHM_INDICATORS = {
        "high": [
            "algorithm",
            "procedure",
            "method",
            "approach",
            "technique",
            "framework",
        ],
        "medium": ["step", "process", "implementation", "computation", "calculation"],
        "low": ["example", "illustration", "demonstration"],
    }

    TECHNICAL_CONCEPT_INDICATORS = {
        "high": ["formula", "equation", "theorem", "lemma", "proof", "definition"],
        "medium": ["parameter", "variable", "function", "model", "architecture"],
        "low": ["notation", "symbol", "term"],
    }

    IMPLEMENTATION_INDICATORS = {
        "high": ["code", "implementation", "programming", "software", "system"],
        "medium": ["design", "structure", "module", "component", "interface"],
        "low": ["tool", "library", "package"],
    }

    # Semantic features of document types (not just based on titles)
    RESEARCH_PAPER_PATTERNS = [
        r"(?i)\babstract\b.*?\n.*?(introduction|motivation|background)",
        r"(?i)(methodology|method).*?(experiment|evaluation|result)",
        r"(?i)(conclusion|future work|limitation).*?(reference|bibliography)",
        r"(?i)(related work|literature review|prior art)",
    ]

    TECHNICAL_DOC_PATTERNS = [
        r"(?i)(getting started|installation|setup).*?(usage|example)",
        r"(?i)(api|interface|specification).*?(parameter|endpoint)",
        r"(?i)(tutorial|guide|walkthrough).*?(step|instruction)",
        r"(?i)(troubleshooting|faq|common issues)",
    ]

    def analyze_document_type(self, content: str) -> Tuple[str, float]:
        """
        Enhanced document type analysis based on semantic content patterns

        Returns:
            Tuple[str, float]: (document_type, confidence_score)
        """
        content_lower = content.lower()

        # Calculate weighted semantic indicator scores
        algorithm_score = self._calculate_weighted_score(
            content_lower, self.ALGORITHM_INDICATORS
        )
        concept_score = self._calculate_weighted_score(
            content_lower, self.TECHNICAL_CONCEPT_INDICATORS
        )
        implementation_score = self._calculate_weighted_score(
            content_lower, self.IMPLEMENTATION_INDICATORS
        )

        # Detect semantic patterns of document types
        research_pattern_score = self._detect_pattern_score(
            content, self.RESEARCH_PAPER_PATTERNS
        )
        technical_pattern_score = self._detect_pattern_score(
            content, self.TECHNICAL_DOC_PATTERNS
        )

        # Comprehensive evaluation of document type
        total_research_score = (
            algorithm_score + concept_score + research_pattern_score * 2
        )
        total_technical_score = implementation_score + technical_pattern_score * 2

        # Determine document type based on content density and pattern matching
        if research_pattern_score > 0.5 and total_research_score > 3.0:
            return "research_paper", min(0.95, 0.6 + research_pattern_score * 0.35)
        elif algorithm_score > 2.0 and concept_score > 1.5:
            return "algorithm_focused", 0.85
        elif total_technical_score > 2.5:
            return "technical_doc", 0.8
        elif implementation_score > 1.5:
            return "implementation_guide", 0.75
        else:
            return "general_document", 0.5

    def _calculate_weighted_score(
        self, content: str, indicators: Dict[str, List[str]]
    ) -> float:
        """Calculate weighted semantic indicator scores"""
        score = 0.0
        for weight_level, terms in indicators.items():
            weight = {"high": 3.0, "medium": 2.0, "low": 1.0}[weight_level]
            for term in terms:
                if term in content:
                    score += weight * (
                        content.count(term) * 0.5 + 1
                    )  # Consider term frequency
        return score

    def _detect_pattern_score(self, content: str, patterns: List[str]) -> float:
        """Detect semantic pattern matching scores"""
        matches = 0
        for pattern in patterns:
            if re.search(pattern, content, re.DOTALL):
                matches += 1
        return matches / len(patterns)

    def detect_segmentation_strategy(self, content: str, doc_type: str) -> str:
        """
        Intelligently determine the best segmentation strategy based on content semantics rather than mechanical structure
        """
        # Analyze content characteristics
        algorithm_density = self._calculate_algorithm_density(content)
        concept_complexity = self._calculate_concept_complexity(content)
        implementation_detail_level = self._calculate_implementation_detail_level(
            content
        )

        # Select strategy based on document type and content characteristics
        if doc_type == "research_paper" and algorithm_density > 0.3:
            return "semantic_research_focused"
        elif doc_type == "algorithm_focused" or algorithm_density > 0.5:
            return "algorithm_preserve_integrity"
        elif concept_complexity > 0.4 and implementation_detail_level > 0.3:
            return "concept_implementation_hybrid"
        elif len(content) > 15000:  # Long documents
            return "semantic_chunking_enhanced"
        else:
            return "content_aware_segmentation"

    def _calculate_algorithm_density(self, content: str) -> float:
        """Calculate algorithm content density"""
        total_chars = len(content)
        algorithm_chars = 0

        # Identify algorithm blocks
        algorithm_patterns = [
            r"(?i)(algorithm\s+\d+|procedure\s+\d+)",
            r"(?i)(step\s+\d+|phase\s+\d+)",
            r"(?i)(input:|output:|return:|initialize:)",
            r"(?i)(for\s+each|while|if.*then|else)",
            r"(?i)(function|method|procedure).*\(",
        ]

        for pattern in algorithm_patterns:
            matches = re.finditer(pattern, content)
            for match in matches:
                # Estimate algorithm block size (expand forward and backward from match point)
                start = max(0, match.start() - 200)
                end = min(len(content), match.end() + 800)
                algorithm_chars += end - start

        return min(1.0, algorithm_chars / total_chars)

    def _calculate_concept_complexity(self, content: str) -> float:
        """Calculate concept complexity"""
        concept_indicators = self.TECHNICAL_CONCEPT_INDICATORS
        complexity_score = 0.0

        for level, terms in concept_indicators.items():
            weight = {"high": 3.0, "medium": 2.0, "low": 1.0}[level]
            for term in terms:
                complexity_score += content.lower().count(term) * weight

        # Normalize to 0-1 range
        return min(1.0, complexity_score / 100)

    def _calculate_implementation_detail_level(self, content: str) -> float:
        """Calculate implementation detail level"""
        implementation_patterns = [
            r"(?i)(code|implementation|programming)",
            r"(?i)(class|function|method|variable)",
            r"(?i)(import|include|library)",
            r"(?i)(parameter|argument|return)",
            r"(?i)(example|demo|tutorial)",
        ]

        detail_score = 0
        for pattern in implementation_patterns:
            detail_score += len(re.findall(pattern, content))

        return min(1.0, detail_score / 50)


class DocumentSegmenter:
    """Creates intelligent segments from documents"""

    def __init__(self):
        self.analyzer = DocumentAnalyzer()

    def segment_document(self, content: str, strategy: str) -> List[DocumentSegment]:
        """
        Perform intelligent segmentation using the specified strategy
        """
        if strategy == "semantic_research_focused":
            return self._segment_research_paper_semantically(content)
        elif strategy == "algorithm_preserve_integrity":
            return self._segment_preserve_algorithm_integrity(content)
        elif strategy == "concept_implementation_hybrid":
            return self._segment_concept_implementation_hybrid(content)
        elif strategy == "semantic_chunking_enhanced":
            return self._segment_by_enhanced_semantic_chunks(content)
        elif strategy == "content_aware_segmentation":
            return self._segment_content_aware(content)
        else:
            # Compatibility with legacy strategies
            return self._segment_by_enhanced_semantic_chunks(content)

    def _segment_by_headers(self, content: str) -> List[DocumentSegment]:
        """Segment document based on markdown headers"""
        segments = []
        lines = content.split("\n")
        current_segment = []
        current_header = None
        char_pos = 0

        for line in lines:
            line_with_newline = line + "\n"

            # Check if line is a header
            header_match = re.match(r"^(#{1,6})\s+(.+)$", line)

            if header_match:
                # Save previous segment if exists
                if current_segment and current_header:
                    segment_content = "\n".join(current_segment).strip()
                    if segment_content:
                        # Analyze content type and importance
                        content_type = self._classify_content_type(
                            current_header, segment_content
                        )
                        importance_score = (
                            0.8 if content_type in ["algorithm", "formula"] else 0.7
                        )

                        segment = self._create_enhanced_segment(
                            segment_content,
                            current_header,
                            char_pos - len(segment_content.encode("utf-8")),
                            char_pos,
                            importance_score,
                            content_type,
                        )
                        segments.append(segment)

                # Start new segment
                current_header = header_match.group(2).strip()
                current_segment = [line]
            else:
                if current_segment is not None:
                    current_segment.append(line)

            char_pos += len(line_with_newline.encode("utf-8"))

        # Add final segment
        if current_segment and current_header:
            segment_content = "\n".join(current_segment).strip()
            if segment_content:
                # Analyze content type and importance
                content_type = self._classify_content_type(
                    current_header, segment_content
                )
                importance_score = (
                    0.8 if content_type in ["algorithm", "formula"] else 0.7
                )

                segment = self._create_enhanced_segment(
                    segment_content,
                    current_header,
                    char_pos - len(segment_content.encode("utf-8")),
                    char_pos,
                    importance_score,
                    content_type,
                )
                segments.append(segment)

        return segments

    def _segment_preserve_algorithm_integrity(
        self, content: str
    ) -> List[DocumentSegment]:
        """Smart segmentation strategy that preserves algorithm integrity"""
        segments = []

        # 1. Identify algorithm blocks and related descriptions
        algorithm_blocks = self._identify_algorithm_blocks(content)

        # 2. Identify concept definition groups
        concept_groups = self._identify_concept_groups(content)

        # 3. Identify formula derivation chains
        formula_chains = self._identify_formula_chains(content)

        # 4. Merge related content blocks to ensure integrity
        content_blocks = self._merge_related_content_blocks(
            algorithm_blocks, concept_groups, formula_chains, content
        )

        # 5. Convert to DocumentSegment
        for i, block in enumerate(content_blocks):
            segment = self._create_enhanced_segment(
                block["content"],
                block["title"],
                block["start_pos"],
                block["end_pos"],
                block["importance_score"],
                block["content_type"],
            )
            segments.append(segment)

        return segments

    def _segment_research_paper_semantically(
        self, content: str
    ) -> List[DocumentSegment]:
        """Semantic segmentation specifically for research papers"""
        segments = []

        # Identify semantic structure of research papers
        paper_sections = self._identify_research_paper_sections(content)

        for section in paper_sections:
            # Ensure each section contains sufficient context
            enhanced_content = self._enhance_section_with_context(section, content)

            segment = self._create_enhanced_segment(
                enhanced_content["content"],
                enhanced_content["title"],
                enhanced_content["start_pos"],
                enhanced_content["end_pos"],
                enhanced_content["importance_score"],
                enhanced_content["content_type"],
            )
            segments.append(segment)

        return segments

    def _segment_concept_implementation_hybrid(
        self, content: str
    ) -> List[DocumentSegment]:
        """Intelligent segmentation combining concepts and implementation"""
        segments = []

        # Identify concept-implementation correspondence
        concept_impl_pairs = self._identify_concept_implementation_pairs(content)

        for pair in concept_impl_pairs:
            # Merge related concepts and implementations into one segment
            merged_content = self._merge_concept_with_implementation(pair, content)

            segment = self._create_enhanced_segment(
                merged_content["content"],
                merged_content["title"],
                merged_content["start_pos"],
                merged_content["end_pos"],
                merged_content["importance_score"],
                merged_content["content_type"],
            )
            segments.append(segment)

        return segments

    def _segment_by_enhanced_semantic_chunks(
        self, content: str
    ) -> List[DocumentSegment]:
        """Enhanced semantic chunk segmentation"""
        segments = []

        # Use improved semantic boundary detection
        semantic_boundaries = self._detect_semantic_boundaries(content)

        current_start = 0
        for i, boundary in enumerate(semantic_boundaries):
            chunk_content = content[current_start : boundary["position"]]

            if len(chunk_content.strip()) > 200:  # Minimum content threshold
                segment = self._create_enhanced_segment(
                    chunk_content,
                    boundary["suggested_title"],
                    current_start,
                    boundary["position"],
                    boundary["importance_score"],
                    boundary["content_type"],
                )
                segments.append(segment)

            current_start = boundary["position"]

        # Handle the final segment
        if current_start < len(content):
            final_content = content[current_start:]
            if len(final_content.strip()) > 200:
                segment = self._create_enhanced_segment(
                    final_content,
                    "Final Section",
                    current_start,
                    len(content),
                    0.7,
                    "general",
                )
                segments.append(segment)

        return segments

    def _segment_content_aware(self, content: str) -> List[DocumentSegment]:
        """Content-aware intelligent segmentation"""
        segments = []

        # Adaptive segmentation size
        optimal_chunk_size = self._calculate_optimal_chunk_size(content)

        # Segment based on content density
        content_chunks = self._create_content_aware_chunks(content, optimal_chunk_size)

        for chunk in content_chunks:
            segment = self._create_enhanced_segment(
                chunk["content"],
                chunk["title"],
                chunk["start_pos"],
                chunk["end_pos"],
                chunk["importance_score"],
                chunk["content_type"],
            )
            segments.append(segment)

        return segments

    def _segment_academic_paper(self, content: str) -> List[DocumentSegment]:
        """Segment academic paper using semantic understanding"""
        # First try header-based segmentation
        headers = re.findall(r"^(#{1,6})\s+(.+)$", content, re.MULTILINE)
        if len(headers) >= 2:
            return self._segment_by_headers(content)

        # Fallback to semantic detection of academic sections
        sections = self._detect_academic_sections(content)
        segments = []

        for section in sections:
            # Determine importance based on section type
            section_type = section.get("type", "general")
            content_type = (
                section_type
                if section_type
                in ["algorithm", "formula", "introduction", "conclusion"]
                else "general"
            )
            importance_score = {
                "algorithm": 0.95,
                "formula": 0.9,
                "introduction": 0.85,
                "conclusion": 0.8,
            }.get(content_type, 0.7)

            segment = self._create_enhanced_segment(
                section["content"],
                section["title"],
                section["start_pos"],
                section["end_pos"],
                importance_score,
                content_type,
            )
            segments.append(segment)

        return segments

    def _detect_academic_sections(self, content: str) -> List[Dict]:
        """Detect academic paper sections even without clear headers"""
        sections = []

        # Common academic section patterns
        section_patterns = [
            (r"(?i)(abstract|摘要)", "introduction"),
            (r"(?i)(introduction|引言|简介)", "introduction"),
            (r"(?i)(related work|相关工作|背景)", "background"),
            (r"(?i)(method|methodology|approach|方法)", "methodology"),
            (r"(?i)(algorithm|算法)", "algorithm"),
            (r"(?i)(experiment|实验|evaluation|评估)", "experiment"),
            (r"(?i)(result|结果|finding)", "results"),
            (r"(?i)(conclusion|结论|总结)", "conclusion"),
            (r"(?i)(reference|参考文献|bibliography)", "references"),
        ]

        current_pos = 0
        for i, (pattern, section_type) in enumerate(section_patterns):
            match = re.search(pattern, content[current_pos:], re.IGNORECASE)
            if match:
                start_pos = current_pos + match.start()

                # Find end position (next section or end of document)
                next_pos = len(content)
                for next_pattern, _ in section_patterns[i + 1 :]:
                    next_match = re.search(
                        next_pattern, content[start_pos + 100 :], re.IGNORECASE
                    )
                    if next_match:
                        next_pos = start_pos + 100 + next_match.start()
                        break

                section_content = content[start_pos:next_pos].strip()
                if len(section_content) > 50:  # Minimum content length
                    # Calculate importance score and content type
                    importance_score = self._calculate_paragraph_importance(
                        section_content, section_type
                    )
                    content_type = self._classify_content_type(
                        match.group(1), section_content
                    )

                    sections.append(
                        {
                            "title": match.group(1),
                            "content": section_content,
                            "start_pos": start_pos,
                            "end_pos": next_pos,
                            "type": section_type,
                            "importance_score": importance_score,
                            "content_type": content_type,
                        }
                    )

                current_pos = next_pos

        return sections

    def _segment_by_semantic_chunks(self, content: str) -> List[DocumentSegment]:
        """Segment long documents into semantic chunks"""
        # Split into paragraphs first
        paragraphs = [p.strip() for p in content.split("\n\n") if p.strip()]

        segments = []
        current_chunk = []
        current_chunk_size = 0
        chunk_size_limit = 3000  # characters
        overlap_size = 200

        char_pos = 0

        for para in paragraphs:
            para_size = len(para)

            # If adding this paragraph exceeds limit, create a segment
            if current_chunk_size + para_size > chunk_size_limit and current_chunk:
                chunk_content = "\n\n".join(current_chunk)
                # Analyze semantic chunk content type
                content_type = self._classify_paragraph_type(chunk_content)
                importance_score = self._calculate_paragraph_importance(
                    chunk_content, content_type
                )

                segment = self._create_enhanced_segment(
                    chunk_content,
                    f"Section {len(segments) + 1}",
                    char_pos - len(chunk_content.encode("utf-8")),
                    char_pos,
                    importance_score,
                    content_type,
                )
                segments.append(segment)

                # Keep last part for overlap
                overlap_content = (
                    chunk_content[-overlap_size:]
                    if len(chunk_content) > overlap_size
                    else ""
                )
                current_chunk = [overlap_content, para] if overlap_content else [para]
                current_chunk_size = len(overlap_content) + para_size
            else:
                current_chunk.append(para)
                current_chunk_size += para_size

            char_pos += para_size + 2  # +2 for \n\n

        # Add final chunk
        if current_chunk:
            chunk_content = "\n\n".join(current_chunk)
            # Analyze final chunk content type
            content_type = self._classify_paragraph_type(chunk_content)
            importance_score = self._calculate_paragraph_importance(
                chunk_content, content_type
            )

            segment = self._create_enhanced_segment(
                chunk_content,
                f"Section {len(segments) + 1}",
                char_pos - len(chunk_content.encode("utf-8")),
                char_pos,
                importance_score,
                content_type,
            )
            segments.append(segment)

        return segments

    def _segment_by_paragraphs(self, content: str) -> List[DocumentSegment]:
        """Simple paragraph-based segmentation for short documents"""
        paragraphs = [p.strip() for p in content.split("\n\n") if p.strip()]
        segments = []
        char_pos = 0

        for i, para in enumerate(paragraphs):
            if len(para) > 100:  # Only include substantial paragraphs
                # Analyze paragraph type and importance
                content_type = self._classify_paragraph_type(para)
                importance_score = self._calculate_paragraph_importance(
                    para, content_type
                )

                segment = self._create_enhanced_segment(
                    para,
                    f"Paragraph {i + 1}",
                    char_pos,
                    char_pos + len(para.encode("utf-8")),
                    importance_score,
                    content_type,
                )
                segments.append(segment)
            char_pos += len(para.encode("utf-8")) + 2

        return segments

    # =============== Enhanced intelligent segmentation helper methods ===============

    def _identify_algorithm_blocks(self, content: str) -> List[Dict]:
        """Identify algorithm blocks and related descriptions"""
        algorithm_blocks = []

        # Algorithm block identification patterns
        algorithm_patterns = [
            r"(?i)(algorithm\s+\d+|procedure\s+\d+|method\s+\d+).*?(?=algorithm\s+\d+|procedure\s+\d+|method\s+\d+|$)",
            r"(?i)(input:|output:|returns?:|require:|ensure:).*?(?=\n\s*\n|\n\s*(?:input:|output:|returns?:|require:|ensure:)|$)",
            r"(?i)(for\s+each|while|if.*then|repeat.*until).*?(?=\n\s*\n|$)",
            r"(?i)(step\s+\d+|phase\s+\d+).*?(?=step\s+\d+|phase\s+\d+|\n\s*\n|$)",
        ]

        for pattern in algorithm_patterns:
            matches = re.finditer(pattern, content, re.DOTALL)
            for match in matches:
                # Expand context to include complete descriptions
                start = max(0, match.start() - 300)
                end = min(len(content), match.end() + 500)

                # Find natural boundaries
                while start > 0 and content[start] not in "\n.!?":
                    start -= 1
                while end < len(content) and content[end] not in "\n.!?":
                    end += 1

                algorithm_blocks.append(
                    {
                        "start_pos": start,
                        "end_pos": end,
                        "content": content[start:end].strip(),
                        "title": self._extract_algorithm_title(
                            content[match.start() : match.end()]
                        ),
                        "importance_score": 0.95,  # High importance for algorithm blocks
                        "content_type": "algorithm",
                    }
                )

        return algorithm_blocks

    def _identify_concept_groups(self, content: str) -> List[Dict]:
        """Identify concept definition groups"""
        concept_groups = []

        # Concept definition patterns
        concept_patterns = [
            r"(?i)(definition|define|let|denote|given).*?(?=\n\s*\n|definition|define|let|denote|$)",
            r"(?i)(theorem|lemma|proposition|corollary).*?(?=\n\s*\n|theorem|lemma|proposition|corollary|$)",
            r"(?i)(notation|symbol|parameter).*?(?=\n\s*\n|notation|symbol|parameter|$)",
        ]

        for pattern in concept_patterns:
            matches = re.finditer(pattern, content, re.DOTALL)
            for match in matches:
                # Expand context
                start = max(0, match.start() - 200)
                end = min(len(content), match.end() + 300)

                concept_groups.append(
                    {
                        "start_pos": start,
                        "end_pos": end,
                        "content": content[start:end].strip(),
                        "title": self._extract_concept_title(
                            content[match.start() : match.end()]
                        ),
                        "importance_score": 0.85,
                        "content_type": "concept",
                    }
                )

        return concept_groups

    def _identify_formula_chains(self, content: str) -> List[Dict]:
        """Identify formula derivation chains"""
        formula_chains = []

        # Formula patterns
        formula_patterns = [
            r"\$\$.*?\$\$",  # Block-level mathematical formulas
            r"\$[^$]+\$",  # Inline mathematical formulas
            r"(?i)(equation|formula).*?(?=\n\s*\n|equation|formula|$)",
            r"(?i)(where|such that|given that).*?(?=\n\s*\n|where|such that|given that|$)",
        ]

        # Find dense formula regions
        formula_positions = []
        for pattern in formula_patterns:
            matches = re.finditer(pattern, content, re.DOTALL)
            for match in matches:
                formula_positions.append((match.start(), match.end()))

        # Merge nearby formulas into formula chains
        formula_positions.sort()
        if formula_positions:
            current_chain_start = formula_positions[0][0]
            current_chain_end = formula_positions[0][1]

            for start, end in formula_positions[1:]:
                if (
                    start - current_chain_end < 500
                ):  # Merge formulas within 500 characters
                    current_chain_end = end
                else:
                    # Save current chain
                    formula_chains.append(
                        {
                            "start_pos": max(0, current_chain_start - 200),
                            "end_pos": min(len(content), current_chain_end + 200),
                            "content": content[
                                max(0, current_chain_start - 200) : min(
                                    len(content), current_chain_end + 200
                                )
                            ].strip(),
                            "title": "Mathematical Formulation",
                            "importance_score": 0.9,
                            "content_type": "formula",
                        }
                    )
                    current_chain_start = start
                    current_chain_end = end

            # Add the last chain
            formula_chains.append(
                {
                    "start_pos": max(0, current_chain_start - 200),
                    "end_pos": min(len(content), current_chain_end + 200),
                    "content": content[
                        max(0, current_chain_start - 200) : min(
                            len(content), current_chain_end + 200
                        )
                    ].strip(),
                    "title": "Mathematical Formulation",
                    "importance_score": 0.9,
                    "content_type": "formula",
                }
            )

        return formula_chains

    def _merge_related_content_blocks(
        self,
        algorithm_blocks: List[Dict],
        concept_groups: List[Dict],
        formula_chains: List[Dict],
        content: str,
    ) -> List[Dict]:
        """Merge related content blocks to ensure integrity"""
        all_blocks = algorithm_blocks + concept_groups + formula_chains
        all_blocks.sort(key=lambda x: x["start_pos"])

        merged_blocks = []
        i = 0

        while i < len(all_blocks):
            current_block = all_blocks[i]

            # Check if can merge with the next block
            while i + 1 < len(all_blocks):
                next_block = all_blocks[i + 1]

                # If blocks are close or content related, merge them
                if next_block["start_pos"] - current_block[
                    "end_pos"
                ] < 300 or self._are_blocks_related(current_block, next_block):
                    # Merge blocks
                    merged_content = content[
                        current_block["start_pos"] : next_block["end_pos"]
                    ]
                    current_block = {
                        "start_pos": current_block["start_pos"],
                        "end_pos": next_block["end_pos"],
                        "content": merged_content.strip(),
                        "title": f"{current_block['title']} & {next_block['title']}",
                        "importance_score": max(
                            current_block["importance_score"],
                            next_block["importance_score"],
                        ),
                        "content_type": "merged",
                    }
                    i += 1
                else:
                    break

            merged_blocks.append(current_block)
            i += 1

        return merged_blocks

    def _are_blocks_related(self, block1: Dict, block2: Dict) -> bool:
        """Determine if two content blocks are related"""
        # Check content type associations
        related_types = [
            ("algorithm", "formula"),
            ("concept", "algorithm"),
            ("formula", "concept"),
        ]

        for type1, type2 in related_types:
            if (
                block1["content_type"] == type1 and block2["content_type"] == type2
            ) or (block1["content_type"] == type2 and block2["content_type"] == type1):
                return True

        return False

    def _extract_algorithm_title(self, text: str) -> str:
        """Extract title from algorithm text"""
        lines = text.split("\n")[:3]  # First 3 lines
        for line in lines:
            line = line.strip()
            if line and len(line) < 100:  # Reasonable title length
                # Clean title
                title = re.sub(r"[^\w\s-]", "", line)
                if title:
                    return title[:50]  # Limit title length
        return "Algorithm Block"

    def _extract_concept_title(self, text: str) -> str:
        """Extract title from concept text"""
        lines = text.split("\n")[:2]
        for line in lines:
            line = line.strip()
            if line and len(line) < 80:
                title = re.sub(r"[^\w\s-]", "", line)
                if title:
                    return title[:50]
        return "Concept Definition"

    def _create_enhanced_segment(
        self,
        content: str,
        title: str,
        start_pos: int,
        end_pos: int,
        importance_score: float,
        content_type: str,
    ) -> DocumentSegment:
        """Create enhanced document segment"""
        # Generate unique ID
        segment_id = hashlib.md5(
            f"{title}_{start_pos}_{end_pos}_{importance_score}".encode()
        ).hexdigest()[:8]

        # Extract keywords
        keywords = self._extract_enhanced_keywords(content, content_type)

        # Calculate enhanced relevance scores
        relevance_scores = self._calculate_enhanced_relevance_scores(
            content, content_type, importance_score
        )

        return DocumentSegment(
            id=segment_id,
            title=title,
            content=content,
            content_type=content_type,
            keywords=keywords,
            char_start=start_pos,
            char_end=end_pos,
            char_count=len(content),
            relevance_scores=relevance_scores,
            section_path=title,
        )

    def _extract_enhanced_keywords(self, content: str, content_type: str) -> List[str]:
        """Extract enhanced keywords based on content type"""
        words = re.findall(r"\b[a-zA-Z]{3,}\b", content.lower())

        # Adjust stopwords based on content type
        if content_type == "algorithm":
            algorithm_stopwords = {
                "step",
                "then",
                "else",
                "end",
                "begin",
                "start",
                "stop",
            }
            words = [w for w in words if w not in algorithm_stopwords]
        elif content_type == "formula":
            formula_keywords = ["equation", "formula", "where", "given", "such", "that"]
            words.extend(formula_keywords)

        # General stopwords
        general_stopwords = {
            "the",
            "and",
            "for",
            "are",
            "but",
            "not",
            "you",
            "all",
            "can",
            "her",
            "was",
            "one",
            "our",
            "had",
            "but",
            "have",
            "this",
            "that",
            "with",
            "from",
            "they",
            "she",
            "been",
            "were",
            "said",
            "each",
            "which",
            "their",
        }

        keywords = [w for w in set(words) if w not in general_stopwords and len(w) > 3]
        return keywords[:25]  # Increase keyword count

    def _calculate_enhanced_relevance_scores(
        self, content: str, content_type: str, importance_score: float
    ) -> Dict[str, float]:
        """Calculate enhanced relevance scores"""
        content_lower = content.lower()

        base_scores = {
            "concept_analysis": 0.5,
            "algorithm_extraction": 0.5,
            "code_planning": 0.5,
        }

        # Adjust base scores based on content type and importance
        if content_type == "algorithm":
            base_scores["algorithm_extraction"] = importance_score
            base_scores["code_planning"] = importance_score * 0.9
            base_scores["concept_analysis"] = importance_score * 0.7
        elif content_type == "concept":
            base_scores["concept_analysis"] = importance_score
            base_scores["algorithm_extraction"] = importance_score * 0.8
            base_scores["code_planning"] = importance_score * 0.6
        elif content_type == "formula":
            base_scores["algorithm_extraction"] = importance_score
            base_scores["concept_analysis"] = importance_score * 0.8
            base_scores["code_planning"] = importance_score * 0.9
        elif content_type == "merged":
            # Merged content is usually important
            base_scores = {k: importance_score * 0.95 for k in base_scores}

        # Additional bonus based on content density
        algorithm_indicators = ["algorithm", "method", "procedure", "step", "process"]
        concept_indicators = ["definition", "concept", "framework", "approach"]
        implementation_indicators = ["implementation", "code", "function", "design"]

        for query_type, indicators in [
            ("algorithm_extraction", algorithm_indicators),
            ("concept_analysis", concept_indicators),
            ("code_planning", implementation_indicators),
        ]:
            density_bonus = (
                sum(1 for indicator in indicators if indicator in content_lower) * 0.1
            )
            base_scores[query_type] = min(1.0, base_scores[query_type] + density_bonus)

        return base_scores

    # Placeholder methods - can be further implemented later
    def _identify_research_paper_sections(self, content: str) -> List[Dict]:
        """Identify research paper sections - simplified implementation"""
        # Temporarily use improved semantic detection
        return self._detect_academic_sections(content)

    def _enhance_section_with_context(self, section: Dict, content: str) -> Dict:
        """Add context to sections - simplified implementation"""
        return section

    def _identify_concept_implementation_pairs(self, content: str) -> List[Dict]:
        """Identify concept-implementation pairs - simplified implementation"""
        return []

    def _merge_concept_with_implementation(self, pair: Dict, content: str) -> Dict:
        """Merge concepts with implementation - simplified implementation"""
        return pair

    def _detect_semantic_boundaries(self, content: str) -> List[Dict]:
        """Detect semantic boundaries - based on paragraphs and logical separators"""
        boundaries = []

        # Split paragraphs by double line breaks
        paragraphs = content.split("\n\n")
        current_pos = 0

        for i, para in enumerate(paragraphs):
            if len(para.strip()) > 100:  # Valid paragraph
                # Analyze paragraph type
                content_type = self._classify_paragraph_type(para)
                importance_score = self._calculate_paragraph_importance(
                    para, content_type
                )

                boundaries.append(
                    {
                        "position": current_pos + len(para),
                        "suggested_title": self._extract_paragraph_title(para, i + 1),
                        "importance_score": importance_score,
                        "content_type": content_type,
                    }
                )

            current_pos += len(para) + 2  # +2 for \n\n

        return boundaries

    def _classify_paragraph_type(self, paragraph: str) -> str:
        """Classify paragraph type"""
        para_lower = paragraph.lower()

        if "algorithm" in para_lower or "procedure" in para_lower:
            return "algorithm"
        elif "formula" in para_lower or "$$" in paragraph:
            return "formula"
        elif any(
            word in para_lower for word in ["introduction", "overview", "abstract"]
        ):
            return "introduction"
        elif any(word in para_lower for word in ["conclusion", "summary", "result"]):
            return "conclusion"
        else:
            return "general"

    def _calculate_paragraph_importance(
        self, paragraph: str, content_type: str
    ) -> float:
        """Calculate paragraph importance"""
        if content_type == "algorithm":
            return 0.95
        elif content_type == "formula":
            return 0.9
        elif content_type == "introduction":
            return 0.85
        elif content_type == "conclusion":
            return 0.8
        else:
            return 0.7

    def _extract_paragraph_title(self, paragraph: str, index: int) -> str:
        """Extract paragraph title"""
        lines = paragraph.split("\n")
        for line in lines[:2]:
            if line.startswith("#"):
                return line.strip("# ")
            elif len(line) < 80 and line.strip():
                return line.strip()
        return f"Section {index}"

    def _calculate_optimal_chunk_size(self, content: str) -> int:
        """Calculate optimal chunk size"""
        # Dynamically adjust based on content complexity
        complexity = self.analyzer._calculate_concept_complexity(content)
        if complexity > 0.7:
            return 4000  # Complex content needs larger chunks
        elif complexity > 0.4:
            return 3000
        else:
            return 2000

    def _create_content_aware_chunks(self, content: str, chunk_size: int) -> List[Dict]:
        """Create content-aware chunks - simplified implementation"""
        chunks = []
        paragraphs = [p.strip() for p in content.split("\n\n") if p.strip()]

        current_chunk = []
        current_size = 0
        start_pos = 0

        for para in paragraphs:
            para_size = len(para)

            if current_size + para_size > chunk_size and current_chunk:
                chunk_content = "\n\n".join(current_chunk)
                chunks.append(
                    {
                        "content": chunk_content,
                        "title": f"Section {len(chunks) + 1}",
                        "start_pos": start_pos,
                        "end_pos": start_pos + len(chunk_content),
                        "importance_score": 0.7,
                        "content_type": "general",
                    }
                )

                current_chunk = [para]
                current_size = para_size
                start_pos += len(chunk_content) + 2
            else:
                current_chunk.append(para)
                current_size += para_size

        # Add the last chunk
        if current_chunk:
            chunk_content = "\n\n".join(current_chunk)
            chunks.append(
                {
                    "content": chunk_content,
                    "title": f"Section {len(chunks) + 1}",
                    "start_pos": start_pos,
                    "end_pos": start_pos + len(chunk_content),
                    "importance_score": 0.7,
                    "content_type": "general",
                }
            )

        return chunks

    def _create_segment(
        self, content: str, title: str, start_pos: int, end_pos: int
    ) -> DocumentSegment:
        """Create a DocumentSegment with metadata"""
        # Generate unique ID
        segment_id = hashlib.md5(f"{title}_{start_pos}_{end_pos}".encode()).hexdigest()[
            :8
        ]

        # Extract keywords from content
        keywords = self._extract_keywords(content)

        # Determine content type
        content_type = self._classify_content_type(title, content)

        # Calculate relevance scores for different query types
        relevance_scores = self._calculate_relevance_scores(content, content_type)

        return DocumentSegment(
            id=segment_id,
            title=title,
            content=content,
            content_type=content_type,
            keywords=keywords,
            char_start=start_pos,
            char_end=end_pos,
            char_count=len(content),
            relevance_scores=relevance_scores,
            section_path=title,  # Simplified for now
        )

    def _extract_keywords(self, content: str) -> List[str]:
        """Extract relevant keywords from content"""
        # Simple keyword extraction - could be enhanced with NLP
        words = re.findall(r"\b[a-zA-Z]{3,}\b", content.lower())

        # Remove common words
        stopwords = {
            "the",
            "and",
            "for",
            "are",
            "but",
            "not",
            "you",
            "all",
            "can",
            "her",
            "was",
            "one",
            "our",
            "had",
            "but",
            "have",
            "this",
            "that",
            "with",
            "from",
            "they",
            "she",
            "been",
            "were",
            "said",
            "each",
            "which",
            "their",
        }

        keywords = [w for w in set(words) if w not in stopwords and len(w) > 3]
        return keywords[:20]  # Top 20 keywords

    def _classify_content_type(self, title: str, content: str) -> str:
        """Classify the type of content based on title and content"""
        title_lower = title.lower()
        content_lower = content.lower()

        if any(
            word in title_lower for word in ["introduction", "abstract", "overview"]
        ):
            return "introduction"
        elif any(word in title_lower for word in ["method", "approach", "algorithm"]):
            return "methodology"
        elif any(
            word in title_lower for word in ["experiment", "evaluation", "result"]
        ):
            return "experiment"
        elif any(
            word in title_lower for word in ["conclusion", "discussion", "summary"]
        ):
            return "conclusion"
        elif any(word in title_lower for word in ["reference", "bibliography"]):
            return "references"
        elif "algorithm" in content_lower or "procedure" in content_lower:
            return "algorithm"
        else:
            return "general"

    def _calculate_relevance_scores(
        self, content: str, content_type: str
    ) -> Dict[str, float]:
        """Calculate relevance scores for different query types"""
        content_lower = content.lower()

        scores = {
            "concept_analysis": 0.5,
            "algorithm_extraction": 0.5,
            "code_planning": 0.5,
        }

        # Concept analysis relevance
        concept_indicators = [
            "introduction",
            "overview",
            "architecture",
            "system",
            "framework",
            "concept",
            "approach",
        ]
        concept_score = sum(
            1 for indicator in concept_indicators if indicator in content_lower
        ) / len(concept_indicators)
        scores["concept_analysis"] = min(
            1.0, concept_score + (0.8 if content_type == "introduction" else 0)
        )

        # Algorithm extraction relevance
        algorithm_indicators = [
            "algorithm",
            "method",
            "procedure",
            "formula",
            "equation",
            "step",
            "process",
        ]
        algorithm_score = sum(
            1 for indicator in algorithm_indicators if indicator in content_lower
        ) / len(algorithm_indicators)
        scores["algorithm_extraction"] = min(
            1.0, algorithm_score + (0.9 if content_type == "methodology" else 0)
        )

        # Code planning relevance
        code_indicators = [
            "implementation",
            "code",
            "function",
            "class",
            "module",
            "structure",
            "design",
        ]
        code_score = sum(
            1 for indicator in code_indicators if indicator in content_lower
        ) / len(code_indicators)
        scores["code_planning"] = min(
            1.0,
            code_score + (0.7 if content_type in ["methodology", "algorithm"] else 0),
        )

        return scores


# Global variables
DOCUMENT_INDEXES: Dict[str, DocumentIndex] = {}
segmenter = DocumentSegmenter()


def get_segments_dir(paper_dir: str) -> str:
    """Get the segments directory path"""
    return os.path.join(paper_dir, "document_segments")


def ensure_segments_dir_exists(segments_dir: str):
    """Ensure segments directory exists"""
    os.makedirs(segments_dir, exist_ok=True)


@mcp.tool()
async def analyze_and_segment_document(
    paper_dir: str, force_refresh: bool = False
) -> str:
    """
    Analyze document structure and create intelligent segments

    Args:
        paper_dir: Path to the paper directory
        force_refresh: Whether to force re-analysis even if segments exist

    Returns:
        JSON string with segmentation results
    """
    try:
        # Find markdown file in paper directory
        md_files = [f for f in os.listdir(paper_dir) if f.endswith(".md")]
        if not md_files:
            return json.dumps(
                {
                    "status": "error",
                    "message": f"No markdown file found in {paper_dir}",
                },
                ensure_ascii=False,
                indent=2,
            )

        md_file_path = os.path.join(paper_dir, md_files[0])
        segments_dir = get_segments_dir(paper_dir)
        index_file_path = os.path.join(segments_dir, "document_index.json")

        # Check if analysis already exists and is recent
        if not force_refresh and os.path.exists(index_file_path):
            try:
                with open(index_file_path, "r", encoding="utf-8") as f:
                    existing_index = json.load(f)

                    # Compatibility handling: ensure segments data structure is correct
                    if "segments" in existing_index:
                        segments_data = []
                        for seg_data in existing_index["segments"]:
                            # Ensure all required fields exist
                            segment_dict = dict(seg_data)

                            if "content_type" not in segment_dict:
                                segment_dict["content_type"] = "general"
                            if "keywords" not in segment_dict:
                                segment_dict["keywords"] = []
                            if "relevance_scores" not in segment_dict:
                                segment_dict["relevance_scores"] = {
                                    "concept_analysis": 0.5,
                                    "algorithm_extraction": 0.5,
                                    "code_planning": 0.5,
                                }
                            if "section_path" not in segment_dict:
                                segment_dict["section_path"] = segment_dict.get(
                                    "title", "Unknown"
                                )

                            segments_data.append(DocumentSegment(**segment_dict))

                        existing_index["segments"] = segments_data

                    DOCUMENT_INDEXES[paper_dir] = DocumentIndex(**existing_index)
                return json.dumps(
                    {
                        "status": "success",
                        "message": "Using existing document analysis",
                        "segments_dir": segments_dir,
                        "total_segments": existing_index["total_segments"],
                    },
                    ensure_ascii=False,
                    indent=2,
                )

            except Exception as e:
                logger.error(f"Failed to load existing index: {e}")
                logger.info("Will perform fresh analysis instead")
                # Remove corrupted index file and continue with new analysis
                try:
                    os.remove(index_file_path)
                except Exception as e:
                    pass

        # Read document content
        with open(md_file_path, "r", encoding="utf-8") as f:
            content = f.read()

        # Analyze document
        analyzer = DocumentAnalyzer()
        doc_type, confidence = analyzer.analyze_document_type(content)
        strategy = analyzer.detect_segmentation_strategy(content, doc_type)

        # Create segments
        segments = segmenter.segment_document(content, strategy)

        # Create document index
        document_index = DocumentIndex(
            document_path=md_file_path,
            document_type=doc_type,
            segmentation_strategy=strategy,
            total_segments=len(segments),
            total_chars=len(content),
            segments=segments,
            created_at=datetime.now().isoformat(),
        )

        # Save segments
        ensure_segments_dir_exists(segments_dir)

        # Save document index
        with open(index_file_path, "w", encoding="utf-8") as f:
            json.dump(
                asdict(document_index), f, ensure_ascii=False, indent=2, default=str
            )

        # Save individual segment files for fallback
        for segment in segments:
            segment_file_path = os.path.join(segments_dir, f"segment_{segment.id}.md")
            with open(segment_file_path, "w", encoding="utf-8") as f:
                f.write(f"# {segment.title}\n\n")
                f.write(f"**Content Type:** {segment.content_type}\n")
                f.write(f"**Keywords:** {', '.join(segment.keywords[:10])}\n\n")
                f.write(segment.content)

        # Store in memory
        DOCUMENT_INDEXES[paper_dir] = document_index

        logger.info(
            f"Document segmentation completed: {len(segments)} segments created"
        )

        return json.dumps(
            {
                "status": "success",
                "message": f"Document analysis completed with {strategy} strategy",
                "document_type": doc_type,
                "segmentation_strategy": strategy,
                "segments_dir": segments_dir,
                "total_segments": len(segments),
                "total_chars": len(content),
            },
            ensure_ascii=False,
            indent=2,
        )

    except Exception as e:
        logger.error(f"Error in analyze_and_segment_document: {e}")
        return json.dumps(
            {"status": "error", "message": f"Failed to analyze document: {str(e)}"},
            ensure_ascii=False,
            indent=2,
        )


@mcp.tool()
async def read_document_segments(
    paper_dir: str,
    query_type: str,
    keywords: List[str] = None,
    max_segments: int = 3,
    max_total_chars: int = None,
) -> str:
    """
    Intelligently retrieve relevant document segments based on query type

    Args:
        paper_dir: Path to the paper directory
        query_type: Type of query - "concept_analysis", "algorithm_extraction", or "code_planning"
        keywords: Optional list of keywords to search for
        max_segments: Maximum number of segments to return
        max_total_chars: Maximum total characters to return

    Returns:
        JSON string with selected segments
    """
    try:
        # Ensure document is analyzed
        if paper_dir not in DOCUMENT_INDEXES:
            segments_dir = get_segments_dir(paper_dir)
            index_file_path = os.path.join(segments_dir, "document_index.json")

            if os.path.exists(index_file_path):
                with open(index_file_path, "r", encoding="utf-8") as f:
                    index_data = json.load(f)
                    # Convert dict back to DocumentIndex with backward compatibility
                    segments_data = []
                    for seg_data in index_data.get("segments", []):
                        # Ensure all required fields exist, provide default values
                        segment_dict = dict(seg_data)

                        # Compatibility handling: add missing fields
                        if "content_type" not in segment_dict:
                            segment_dict["content_type"] = "general"
                        if "keywords" not in segment_dict:
                            segment_dict["keywords"] = []
                        if "relevance_scores" not in segment_dict:
                            segment_dict["relevance_scores"] = {
                                "concept_analysis": 0.5,
                                "algorithm_extraction": 0.5,
                                "code_planning": 0.5,
                            }
                        if "section_path" not in segment_dict:
                            segment_dict["section_path"] = segment_dict.get(
                                "title", "Unknown"
                            )

                        segment = DocumentSegment(**segment_dict)
                        segments_data.append(segment)

                    index_data["segments"] = segments_data
                    DOCUMENT_INDEXES[paper_dir] = DocumentIndex(**index_data)
            else:
                # Auto-analyze if not found
                await analyze_and_segment_document(paper_dir)

        document_index = DOCUMENT_INDEXES[paper_dir]

        # Dynamically calculate character limit
        if max_total_chars is None:
            max_total_chars = _calculate_adaptive_char_limit(document_index, query_type)

        # Score and rank segments with enhanced algorithm
        scored_segments = []
        for segment in document_index.segments:
            # Base relevance score (already enhanced in new system)
            relevance_score = segment.relevance_scores.get(query_type, 0.5)

            # Enhanced keyword matching with position weighting
            if keywords:
                keyword_score = _calculate_enhanced_keyword_score(segment, keywords)
                relevance_score += keyword_score

            # Content completeness bonus
            completeness_bonus = _calculate_completeness_bonus(segment, document_index)
            relevance_score += completeness_bonus

            scored_segments.append((segment, relevance_score))

        # Sort by enhanced relevance score
        scored_segments.sort(key=lambda x: x[1], reverse=True)

        # Intelligent segment selection with integrity preservation
        selected_segments = _select_segments_with_integrity(
            scored_segments, max_segments, max_total_chars, query_type
        )

        total_chars = sum(seg["char_count"] for seg in selected_segments)

        logger.info(
            f"Selected {len(selected_segments)} segments for {query_type} query"
        )

        return json.dumps(
            {
                "status": "success",
                "query_type": query_type,
                "keywords": keywords or [],
                "total_segments_available": len(document_index.segments),
                "segments_selected": len(selected_segments),
                "total_chars": total_chars,
                "max_chars_used": max_total_chars,
                "segments": selected_segments,
            },
            ensure_ascii=False,
            indent=2,
        )

    except Exception as e:
        logger.error(f"Error in read_document_segments: {e}")
        return json.dumps(
            {
                "status": "error",
                "message": f"Failed to read document segments: {str(e)}",
            },
            ensure_ascii=False,
            indent=2,
        )


@mcp.tool()
async def get_document_overview(paper_dir: str) -> str:
    """
    Get overview of document structure and available segments

    Args:
        paper_dir: Path to the paper directory

    Returns:
        JSON string with document overview
    """
    try:
        # Ensure document is analyzed
        if paper_dir not in DOCUMENT_INDEXES:
            await analyze_and_segment_document(paper_dir)

        document_index = DOCUMENT_INDEXES[paper_dir]

        # Create overview
        segment_summaries = []
        for segment in document_index.segments:
            segment_summaries.append(
                {
                    "id": segment.id,
                    "title": segment.title,
                    "content_type": segment.content_type,
                    "char_count": segment.char_count,
                    "keywords": segment.keywords[:5],  # Top 5 keywords
                    "relevance_scores": segment.relevance_scores,
                }
            )

        return json.dumps(
            {
                "status": "success",
                "document_path": document_index.document_path,
                "document_type": document_index.document_type,
                "segmentation_strategy": document_index.segmentation_strategy,
                "total_segments": document_index.total_segments,
                "total_chars": document_index.total_chars,
                "created_at": document_index.created_at,
                "segments_overview": segment_summaries,
            },
            ensure_ascii=False,
            indent=2,
        )

    except Exception as e:
        logger.error(f"Error in get_document_overview: {e}")
        return json.dumps(
            {
                "status": "error",
                "message": f"Failed to get document overview: {str(e)}",
            },
            ensure_ascii=False,
            indent=2,
        )


# =============== Enhanced retrieval system helper methods ===============


def _calculate_adaptive_char_limit(
    document_index: DocumentIndex, query_type: str
) -> int:
    """Dynamically calculate character limit based on document complexity and query type"""
    base_limit = 6000

    # Adjust based on document type
    if document_index.document_type == "research_paper":
        base_limit = 10000
    elif document_index.document_type == "algorithm_focused":
        base_limit = 12000
    elif document_index.segmentation_strategy == "algorithm_preserve_integrity":
        base_limit = 15000

    # Adjust based on query type
    query_multipliers = {
        "algorithm_extraction": 1.5,  # Algorithms need more context
        "concept_analysis": 1.2,
        "code_planning": 1.3,
    }

    multiplier = query_multipliers.get(query_type, 1.0)
    return int(base_limit * multiplier)


def _calculate_enhanced_keyword_score(
    segment: DocumentSegment, keywords: List[str]
) -> float:
    """Calculate enhanced keyword matching score"""
    score = 0.0
    content_lower = segment.content.lower()
    title_lower = segment.title.lower()

    for keyword in keywords:
        keyword_lower = keyword.lower()

        # Title matching has higher weight
        if keyword_lower in title_lower:
            score += 0.3

        # Content matching
        content_matches = content_lower.count(keyword_lower)
        if content_matches > 0:
            # Consider term frequency and position
            frequency_score = min(0.2, content_matches * 0.05)

            # Check if in important position (first 25% of content)
            early_content = content_lower[: len(content_lower) // 4]
            if keyword_lower in early_content:
                frequency_score += 0.1

            score += frequency_score

    return min(0.6, score)  # Limit maximum bonus


def _calculate_completeness_bonus(
    segment: DocumentSegment, document_index: DocumentIndex
) -> float:
    """Calculate content completeness bonus"""
    bonus = 0.0

    # Completeness bonus for algorithm and formula content
    if segment.content_type in ["algorithm", "formula", "merged"]:
        bonus += 0.2

    # Long paragraphs usually contain more complete information
    if segment.char_count > 2000:
        bonus += 0.1
    elif segment.char_count > 4000:
        bonus += 0.15

    # High importance paragraph bonus
    if segment.relevance_scores.get("algorithm_extraction", 0) > 0.8:
        bonus += 0.1

    return min(0.3, bonus)


def _select_segments_with_integrity(
    scored_segments: List[Tuple],
    max_segments: int,
    max_total_chars: int,
    query_type: str,
) -> List[Dict]:
    """Intelligently select segments while maintaining content integrity"""
    selected_segments = []
    total_chars = 0

    # First select the highest scoring segments
    for segment, score in scored_segments:
        if len(selected_segments) >= max_segments:
            break

        if total_chars + segment.char_count <= max_total_chars:
            selected_segments.append(
                {
                    "id": segment.id,
                    "title": segment.title,
                    "content": segment.content,
                    "content_type": segment.content_type,
                    "relevance_score": score,
                    "char_count": segment.char_count,
                }
            )
            total_chars += segment.char_count
        elif len(selected_segments) == 0:
            # If the first segment exceeds the limit, truncate but preserve it
            truncated_content = (
                segment.content[: max_total_chars - 200]
                + "\n\n[Content truncated for length...]"
            )
            selected_segments.append(
                {
                    "id": segment.id,
                    "title": segment.title,
                    "content": truncated_content,
                    "content_type": segment.content_type,
                    "relevance_score": score,
                    "char_count": len(truncated_content),
                }
            )
            break

    # If there's remaining space, try to add relevant small segments
    remaining_chars = max_total_chars - total_chars
    if remaining_chars > 500 and len(selected_segments) < max_segments:
        for segment, score in scored_segments[len(selected_segments) :]:
            if (
                segment.char_count <= remaining_chars
                and len(selected_segments) < max_segments
            ):
                selected_segments.append(
                    {
                        "id": segment.id,
                        "title": segment.title,
                        "content": segment.content,
                        "content_type": segment.content_type,
                        "relevance_score": score,
                        "char_count": segment.char_count,
                    }
                )
                remaining_chars -= segment.char_count

    return selected_segments


if __name__ == "__main__":
    # Run the MCP server
    mcp.run()