kaccy-ai 0.2.0

AI-powered intelligence for Kaccy Protocol - forecasting, optimization, and insights
Documentation
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
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
//! Document analysis module
//!
//! This module provides utilities for parsing and analyzing documents
//! in various formats including Markdown, HTML, and PDF.

use serde::{Deserialize, Serialize};
use std::fmt::Write as _;

/// Supported document formats
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DocumentFormat {
    /// Markdown document
    Markdown,
    /// HTML document
    Html,
    /// Plain text
    PlainText,
    /// PDF document
    Pdf,
}

impl DocumentFormat {
    /// Detect format from content
    #[must_use]
    pub fn detect(content: &str) -> Self {
        let content_lower = content.to_lowercase();

        // Check for HTML markers
        if content_lower.contains("<!doctype html")
            || content_lower.contains("<html")
            || (content_lower.contains("<head") && content_lower.contains("<body"))
            || content_lower.contains("<div")
            || content_lower.contains("<p>")
        {
            return DocumentFormat::Html;
        }

        // Check for Markdown markers
        if content.contains("# ")
            || content.contains("## ")
            || content.contains("```")
            || content.contains("**")
            || content.contains("__")
            || content.contains("](") // Markdown link pattern [text](url)
            || content.contains("![")
            || content.contains("- [ ]")
            || content.contains("- [x]")
        {
            return DocumentFormat::Markdown;
        }

        DocumentFormat::PlainText
    }

    /// Detect format from file extension
    #[must_use]
    pub fn from_extension(ext: &str) -> Self {
        match ext.to_lowercase().as_str() {
            "md" | "markdown" | "mdown" | "mkd" => DocumentFormat::Markdown,
            "html" | "htm" | "xhtml" => DocumentFormat::Html,
            "pdf" => DocumentFormat::Pdf,
            _ => DocumentFormat::PlainText,
        }
    }

    /// Detect format from binary data (for PDF detection)
    #[must_use]
    pub fn detect_from_bytes(data: &[u8]) -> Self {
        // Check for PDF magic bytes (%PDF-)
        if data.len() >= 5 && &data[0..5] == b"%PDF-" {
            return DocumentFormat::Pdf;
        }

        // Fall back to string-based detection
        if let Ok(content) = std::str::from_utf8(data) {
            Self::detect(content)
        } else {
            // Binary content that's not PDF
            DocumentFormat::PlainText
        }
    }
}

/// Extracted document structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DocumentStructure {
    /// Document format
    pub format: DocumentFormat,
    /// Title (if detected)
    pub title: Option<String>,
    /// Headings with their levels
    pub headings: Vec<Heading>,
    /// Extracted links
    pub links: Vec<Link>,
    /// Extracted images
    pub images: Vec<Image>,
    /// Code blocks
    pub code_blocks: Vec<CodeBlock>,
    /// Plain text content (HTML tags stripped)
    pub plain_text: String,
    /// Word count
    pub word_count: usize,
    /// Character count
    pub char_count: usize,
    /// Estimated reading time in minutes
    pub reading_time_minutes: u32,
    /// Key statistics
    pub stats: DocumentStats,
}

/// Document heading
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Heading {
    /// Heading level (1-6)
    pub level: u8,
    /// Heading text
    pub text: String,
    /// Anchor/ID (if available)
    pub anchor: Option<String>,
}

/// Extracted link
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Link {
    /// Link URL
    pub url: String,
    /// Link text
    pub text: String,
    /// Link title (if available)
    pub title: Option<String>,
    /// Whether this is an external link
    pub is_external: bool,
}

/// Extracted image
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Image {
    /// Image URL/path
    pub src: String,
    /// Alt text
    pub alt: String,
    /// Title (if available)
    pub title: Option<String>,
}

/// Code block
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodeBlock {
    /// Programming language (if specified)
    pub language: Option<String>,
    /// Code content
    pub code: String,
    /// Line count
    pub line_count: usize,
}

/// Document statistics
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DocumentStats {
    /// Number of headings
    pub heading_count: usize,
    /// Number of paragraphs
    pub paragraph_count: usize,
    /// Number of lists
    pub list_count: usize,
    /// Number of links
    pub link_count: usize,
    /// Number of images
    pub image_count: usize,
    /// Number of code blocks
    pub code_block_count: usize,
    /// Number of tables
    pub table_count: usize,
    /// Number of blockquotes
    pub blockquote_count: usize,
}

/// Document parser
pub struct DocumentParser;

impl DocumentParser {
    /// Parse a document and extract its structure
    #[must_use]
    pub fn parse(content: &str) -> DocumentStructure {
        let format = DocumentFormat::detect(content);

        match format {
            DocumentFormat::Markdown => Self::parse_markdown(content),
            DocumentFormat::Html => Self::parse_html(content),
            DocumentFormat::PlainText => Self::parse_plain_text(content),
            DocumentFormat::Pdf => Self::parse_plain_text(content), // PDF needs binary data
        }
    }

    /// Parse a document with explicit format
    #[must_use]
    pub fn parse_with_format(content: &str, format: DocumentFormat) -> DocumentStructure {
        match format {
            DocumentFormat::Markdown => Self::parse_markdown(content),
            DocumentFormat::Html => Self::parse_html(content),
            DocumentFormat::PlainText => Self::parse_plain_text(content),
            DocumentFormat::Pdf => Self::parse_plain_text(content), // PDF needs binary data
        }
    }

    /// Parse binary PDF data and extract its structure
    pub fn parse_pdf(data: &[u8]) -> Result<DocumentStructure, PdfParseError> {
        PdfParser::parse(data)
    }

    /// Parse binary PDF from a file path
    pub fn parse_pdf_file(path: &std::path::Path) -> Result<DocumentStructure, PdfParseError> {
        let data = std::fs::read(path).map_err(|e| PdfParseError::IoError(e.to_string()))?;
        Self::parse_pdf(&data)
    }

    /// Parse Markdown document
    fn parse_markdown(content: &str) -> DocumentStructure {
        let mut headings = Vec::new();
        let mut links = Vec::new();
        let mut images = Vec::new();
        let mut code_blocks = Vec::new();
        let mut title = None;
        let mut stats = DocumentStats::default();

        let mut in_code_block = false;
        let mut code_block_lang = None;
        let mut code_block_content = String::new();

        for line in content.lines() {
            // Handle code blocks
            if line.starts_with("```") {
                if in_code_block {
                    // End of code block
                    code_blocks.push(CodeBlock {
                        language: code_block_lang.take(),
                        line_count: code_block_content.lines().count(),
                        code: std::mem::take(&mut code_block_content),
                    });
                    stats.code_block_count += 1;
                    in_code_block = false;
                } else {
                    // Start of code block
                    let lang = line.trim_start_matches("```").trim();
                    code_block_lang = if lang.is_empty() {
                        None
                    } else {
                        Some(lang.to_string())
                    };
                    in_code_block = true;
                }
                continue;
            }

            if in_code_block {
                code_block_content.push_str(line);
                code_block_content.push('\n');
                continue;
            }

            // Parse headings
            if let Some(heading) = Self::parse_markdown_heading(line) {
                if title.is_none() && heading.level == 1 {
                    title = Some(heading.text.clone());
                }
                headings.push(heading);
                stats.heading_count += 1;
            }

            // Parse links: [text](url) or [text](url "title")
            Self::extract_markdown_links(line, &mut links);

            // Parse images: ![alt](src) or ![alt](src "title")
            Self::extract_markdown_images(line, &mut images);

            // Count lists
            if line.trim_start().starts_with("- ")
                || line.trim_start().starts_with("* ")
                || line.trim_start().starts_with("+ ")
                || line
                    .trim_start()
                    .chars()
                    .next()
                    .is_some_and(|c| c.is_ascii_digit())
                    && line.contains(". ")
            {
                stats.list_count += 1;
            }

            // Count blockquotes
            if line.trim_start().starts_with("> ") {
                stats.blockquote_count += 1;
            }

            // Count tables (simple detection)
            if line.contains('|') && line.trim().starts_with('|') {
                stats.table_count += 1;
            }
        }

        stats.link_count = links.len();
        stats.image_count = images.len();

        // Calculate plain text
        let plain_text = Self::markdown_to_plain_text(content);
        let word_count = plain_text.split_whitespace().count();
        let char_count = plain_text.chars().count();

        // Count paragraphs (blank line separated blocks)
        stats.paragraph_count = content
            .split("\n\n")
            .filter(|p| !p.trim().is_empty() && !p.trim().starts_with('#'))
            .count();

        DocumentStructure {
            format: DocumentFormat::Markdown,
            title,
            headings,
            links,
            images,
            code_blocks,
            plain_text,
            word_count,
            char_count,
            reading_time_minutes: (word_count / 200).max(1) as u32,
            stats,
        }
    }

    /// Parse a markdown heading
    fn parse_markdown_heading(line: &str) -> Option<Heading> {
        let trimmed = line.trim();
        if !trimmed.starts_with('#') {
            return None;
        }

        let mut level = 0u8;
        for c in trimmed.chars() {
            if c == '#' {
                level += 1;
            } else {
                break;
            }
        }

        if level > 6 {
            return None;
        }

        let text = trimmed.trim_start_matches('#').trim().to_string();
        if text.is_empty() {
            return None;
        }

        // Generate anchor from text
        let anchor = text
            .to_lowercase()
            .replace(' ', "-")
            .chars()
            .filter(|c| c.is_alphanumeric() || *c == '-')
            .collect::<String>();

        Some(Heading {
            level,
            text,
            anchor: Some(anchor),
        })
    }

    /// Extract markdown links from a line
    fn extract_markdown_links(line: &str, links: &mut Vec<Link>) {
        let mut remaining = line;

        while let Some(start) = remaining.find('[') {
            let after_start = &remaining[start + 1..];

            // Find closing bracket
            if let Some(close) = after_start.find(']') {
                let text = &after_start[..close];
                let after_close = &after_start[close + 1..];

                // Check for (url) or (url "title")
                if after_close.starts_with('(') {
                    if let Some(paren_close) = after_close.find(')') {
                        let url_part = &after_close[1..paren_close];

                        // Parse URL and optional title
                        let (url, title) = if let Some(quote_start) = url_part.find('"') {
                            let url = url_part[..quote_start].trim().to_string();
                            let title_part = &url_part[quote_start + 1..];
                            let title = title_part.trim_end_matches('"').to_string();
                            (url, Some(title))
                        } else {
                            (url_part.trim().to_string(), None)
                        };

                        // Skip image links (they start with !)
                        if !remaining[..start].ends_with('!') && !url.is_empty() {
                            let is_external = url.starts_with("http://")
                                || url.starts_with("https://")
                                || url.starts_with("//");

                            links.push(Link {
                                url,
                                text: text.to_string(),
                                title,
                                is_external,
                            });
                        }

                        remaining = &after_close[paren_close + 1..];
                        continue;
                    }
                }
            }

            remaining = &remaining[start + 1..];
        }
    }

    /// Extract markdown images from a line
    fn extract_markdown_images(line: &str, images: &mut Vec<Image>) {
        let mut remaining = line;

        while let Some(start) = remaining.find("![") {
            let after_start = &remaining[start + 2..];

            // Find closing bracket
            if let Some(close) = after_start.find(']') {
                let alt = &after_start[..close];
                let after_close = &after_start[close + 1..];

                // Check for (src) or (src "title")
                if after_close.starts_with('(') {
                    if let Some(paren_close) = after_close.find(')') {
                        let src_part = &after_close[1..paren_close];

                        // Parse src and optional title
                        let (src, title) = if let Some(quote_start) = src_part.find('"') {
                            let src = src_part[..quote_start].trim().to_string();
                            let title_part = &src_part[quote_start + 1..];
                            let title = title_part.trim_end_matches('"').to_string();
                            (src, Some(title))
                        } else {
                            (src_part.trim().to_string(), None)
                        };

                        if !src.is_empty() {
                            images.push(Image {
                                src,
                                alt: alt.to_string(),
                                title,
                            });
                        }

                        remaining = &after_close[paren_close + 1..];
                        continue;
                    }
                }
            }

            remaining = &remaining[start + 2..];
        }
    }

    /// Convert markdown to plain text
    fn markdown_to_plain_text(content: &str) -> String {
        let mut result = String::new();
        let mut in_code_block = false;

        for line in content.lines() {
            if line.starts_with("```") {
                in_code_block = !in_code_block;
                continue;
            }

            if in_code_block {
                continue;
            }

            // Remove headings markers
            let line = if line.starts_with('#') {
                line.trim_start_matches('#').trim()
            } else {
                line
            };

            // Remove bold/italic markers
            let line = line
                .replace("**", "")
                .replace("__", "")
                .replace(['*', '_'], "");

            // Remove inline code
            let line = Self::remove_inline_code(&line);

            // Remove links but keep text
            let line = Self::remove_markdown_links(&line);

            // Remove images
            let line = Self::remove_markdown_images(&line);

            if !line.trim().is_empty() {
                result.push_str(&line);
                result.push(' ');
            }
        }

        result.trim().to_string()
    }

    /// Remove inline code markers
    fn remove_inline_code(line: &str) -> String {
        let mut result = String::new();
        let mut in_code = false;

        for c in line.chars() {
            if c == '`' {
                in_code = !in_code;
            } else if !in_code {
                result.push(c);
            }
        }

        result
    }

    /// Remove markdown links but keep text
    fn remove_markdown_links(line: &str) -> String {
        let mut result = line.to_string();

        // Simple replacement of [text](url) with text
        while let Some(start) = result.find('[') {
            if let Some(close) = result[start..].find(']') {
                let absolute_close = start + close;
                if result.len() > absolute_close + 1
                    && result.as_bytes()[absolute_close + 1] == b'('
                {
                    if let Some(paren_close) = result[absolute_close..].find(')') {
                        let text = &result[start + 1..absolute_close];
                        let before = &result[..start];
                        let after = &result[absolute_close + paren_close + 1..];
                        result = format!("{before}{text}{after}");
                        continue;
                    }
                }
            }
            break;
        }

        result
    }

    /// Remove markdown images
    fn remove_markdown_images(line: &str) -> String {
        let mut result = line.to_string();

        while let Some(start) = result.find("![") {
            if let Some(close) = result[start..].find(']') {
                let absolute_close = start + close;
                if result.len() > absolute_close + 1
                    && result.as_bytes()[absolute_close + 1] == b'('
                {
                    if let Some(paren_close) = result[absolute_close..].find(')') {
                        let before = &result[..start];
                        let after = &result[absolute_close + paren_close + 1..];
                        result = format!("{before}{after}");
                        continue;
                    }
                }
            }
            break;
        }

        result
    }

    /// Parse HTML document
    fn parse_html(content: &str) -> DocumentStructure {
        let mut headings = Vec::new();
        let mut links = Vec::new();
        let mut images = Vec::new();
        let mut code_blocks = Vec::new();
        let mut title = None;
        let mut stats = DocumentStats::default();

        // Extract title from <title> tag
        if let Some(title_text) = Self::extract_html_tag_content(content, "title") {
            title = Some(title_text);
        }

        // Extract headings (h1-h6)
        for level in 1..=6 {
            let tag = format!("h{level}");
            for text in Self::extract_all_html_tag_contents(content, &tag) {
                if title.is_none() && level == 1 {
                    title = Some(text.clone());
                }
                headings.push(Heading {
                    level: level as u8,
                    text,
                    anchor: None,
                });
                stats.heading_count += 1;
            }
        }

        // Extract links
        Self::extract_html_links(content, &mut links);
        stats.link_count = links.len();

        // Extract images
        Self::extract_html_images(content, &mut images);
        stats.image_count = images.len();

        // Extract code blocks (<pre><code> or <code>)
        for code in Self::extract_all_html_tag_contents(content, "code") {
            code_blocks.push(CodeBlock {
                language: None,
                line_count: code.lines().count(),
                code,
            });
            stats.code_block_count += 1;
        }

        // Count other elements
        stats.paragraph_count = Self::count_html_tags(content, "p");
        stats.list_count =
            Self::count_html_tags(content, "ul") + Self::count_html_tags(content, "ol");
        stats.table_count = Self::count_html_tags(content, "table");
        stats.blockquote_count = Self::count_html_tags(content, "blockquote");

        // Get plain text
        let plain_text = Self::html_to_plain_text(content);
        let word_count = plain_text.split_whitespace().count();
        let char_count = plain_text.chars().count();

        DocumentStructure {
            format: DocumentFormat::Html,
            title,
            headings,
            links,
            images,
            code_blocks,
            plain_text,
            word_count,
            char_count,
            reading_time_minutes: (word_count / 200).max(1) as u32,
            stats,
        }
    }

    /// Extract content from an HTML tag
    fn extract_html_tag_content(content: &str, tag: &str) -> Option<String> {
        let open_tag = format!("<{tag}");
        let close_tag = format!("</{tag}>");

        let start = content.to_lowercase().find(&open_tag)?;
        let after_open = &content[start..];

        // Find the end of the opening tag
        let tag_end = after_open.find('>')?;
        let content_start = start + tag_end + 1;

        let close_pos = content[content_start..].to_lowercase().find(&close_tag)?;

        let text = &content[content_start..content_start + close_pos];
        Some(Self::html_to_plain_text(text).trim().to_string())
    }

    /// Extract all contents from HTML tags
    fn extract_all_html_tag_contents(content: &str, tag: &str) -> Vec<String> {
        let mut results = Vec::new();
        let content_lower = content.to_lowercase();
        let open_tag = format!("<{tag}");
        let close_tag = format!("</{tag}>");

        let mut search_start = 0;
        while let Some(start) = content_lower[search_start..].find(&open_tag) {
            let absolute_start = search_start + start;
            let after_open = &content[absolute_start..];

            if let Some(tag_end) = after_open.find('>') {
                let content_start = absolute_start + tag_end + 1;

                if let Some(close_pos) = content_lower[content_start..].find(&close_tag) {
                    let text = &content[content_start..content_start + close_pos];
                    let clean_text = Self::html_to_plain_text(text).trim().to_string();
                    if !clean_text.is_empty() {
                        results.push(clean_text);
                    }
                    search_start = content_start + close_pos + close_tag.len();
                    continue;
                }
            }

            search_start = absolute_start + 1;
        }

        results
    }

    /// Count occurrences of an HTML tag
    fn count_html_tags(content: &str, tag: &str) -> usize {
        let open_tag = format!("<{tag}");
        content.to_lowercase().matches(&open_tag).count()
    }

    /// Extract HTML links
    fn extract_html_links(content: &str, links: &mut Vec<Link>) {
        let content_lower = content.to_lowercase();
        let mut search_start = 0;

        while let Some(start) = content_lower[search_start..].find("<a ") {
            let absolute_start = search_start + start;
            let after_open = &content[absolute_start..];

            if let Some(tag_end) = after_open.find('>') {
                let tag_content = &after_open[..tag_end];

                // Extract href
                if let Some(href) = Self::extract_html_attribute(tag_content, "href") {
                    let close_pos = content_lower[absolute_start..].find("</a>");

                    let text = if let Some(close) = close_pos {
                        let content_start = absolute_start + tag_end + 1;
                        let content_end = absolute_start + close;
                        Self::html_to_plain_text(&content[content_start..content_end])
                            .trim()
                            .to_string()
                    } else {
                        String::new()
                    };

                    let title = Self::extract_html_attribute(tag_content, "title");
                    let is_external = href.starts_with("http://")
                        || href.starts_with("https://")
                        || href.starts_with("//");

                    links.push(Link {
                        url: href,
                        text,
                        title,
                        is_external,
                    });
                }

                search_start = absolute_start + tag_end;
            } else {
                search_start = absolute_start + 1;
            }
        }
    }

    /// Extract HTML images
    fn extract_html_images(content: &str, images: &mut Vec<Image>) {
        let content_lower = content.to_lowercase();
        let mut search_start = 0;

        while let Some(start) = content_lower[search_start..].find("<img ") {
            let absolute_start = search_start + start;
            let after_open = &content[absolute_start..];

            if let Some(tag_end) = after_open.find('>').or_else(|| after_open.find("/>")) {
                let tag_content = &after_open[..tag_end];

                if let Some(src) = Self::extract_html_attribute(tag_content, "src") {
                    let alt = Self::extract_html_attribute(tag_content, "alt").unwrap_or_default();
                    let title = Self::extract_html_attribute(tag_content, "title");

                    images.push(Image { src, alt, title });
                }

                search_start = absolute_start + tag_end;
            } else {
                search_start = absolute_start + 1;
            }
        }
    }

    /// Extract an HTML attribute value
    fn extract_html_attribute(tag_content: &str, attr: &str) -> Option<String> {
        let attr_pattern = format!("{attr}=");
        let content_lower = tag_content.to_lowercase();

        let attr_start = content_lower.find(&attr_pattern)?;
        let after_attr = &tag_content[attr_start + attr_pattern.len()..];

        // Handle quoted attribute values
        let first_char = after_attr.chars().next()?;
        if first_char == '"' || first_char == '\'' {
            let quote = first_char;
            let value_start = 1;
            let value_end = after_attr[value_start..].find(quote)?;
            return Some(after_attr[value_start..value_start + value_end].to_string());
        }

        // Handle unquoted attribute values
        let value_end = after_attr.find(|c: char| c.is_whitespace() || c == '>')?;
        Some(after_attr[..value_end].to_string())
    }

    /// Convert HTML to plain text
    fn html_to_plain_text(content: &str) -> String {
        let mut result = String::new();
        let mut in_tag = false;
        let mut in_script = false;
        let mut in_style = false;

        let content_lower = content.to_lowercase();
        let chars: Vec<char> = content.chars().collect();
        let chars_lower: Vec<char> = content_lower.chars().collect();

        let mut i = 0;
        while i < chars.len() {
            // Check for script/style tags
            if i + 7 < chars.len() {
                let slice: String = chars_lower[i..i + 7].iter().collect();
                if slice == "<script" {
                    in_script = true;
                } else if slice == "</scrip" {
                    in_script = false;
                }
            }

            if i + 6 < chars.len() {
                let slice: String = chars_lower[i..i + 6].iter().collect();
                if slice == "<style" {
                    in_style = true;
                } else if slice == "</styl" {
                    in_style = false;
                }
            }

            let c = chars[i];

            if c == '<' {
                in_tag = true;
            } else if c == '>' {
                in_tag = false;
                // Add space after certain tags
                result.push(' ');
            } else if !in_tag && !in_script && !in_style {
                result.push(c);
            }

            i += 1;
        }

        // Decode common HTML entities
        let result = result
            .replace("&nbsp;", " ")
            .replace("&amp;", "&")
            .replace("&lt;", "<")
            .replace("&gt;", ">")
            .replace("&quot;", "\"")
            .replace("&apos;", "'")
            .replace("&#39;", "'");

        // Normalize whitespace
        result.split_whitespace().collect::<Vec<_>>().join(" ")
    }

    /// Parse plain text document
    fn parse_plain_text(content: &str) -> DocumentStructure {
        let word_count = content.split_whitespace().count();
        let char_count = content.chars().count();
        let paragraph_count = content
            .split("\n\n")
            .filter(|p| !p.trim().is_empty())
            .count();

        DocumentStructure {
            format: DocumentFormat::PlainText,
            title: None,
            headings: Vec::new(),
            links: Vec::new(),
            images: Vec::new(),
            code_blocks: Vec::new(),
            plain_text: content.to_string(),
            word_count,
            char_count,
            reading_time_minutes: (word_count / 200).max(1) as u32,
            stats: DocumentStats {
                paragraph_count,
                ..Default::default()
            },
        }
    }
}

/// Document quality analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DocumentQuality {
    /// Overall quality score (0-100)
    pub overall_score: u32,
    /// Readability score (0-100)
    pub readability_score: u32,
    /// Structure score (0-100)
    pub structure_score: u32,
    /// Issues found
    pub issues: Vec<QualityIssue>,
    /// Suggestions for improvement
    pub suggestions: Vec<String>,
}

/// Quality issue
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualityIssue {
    /// Issue severity
    pub severity: IssueSeverity,
    /// Issue description
    pub description: String,
}

/// Issue severity levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum IssueSeverity {
    /// Informational note.
    Info,
    /// Non-critical issue that should be addressed.
    Warning,
    /// Critical issue that must be resolved.
    Error,
}

/// Document quality analyzer
pub struct QualityAnalyzer;

impl QualityAnalyzer {
    /// Analyze document quality
    #[must_use]
    pub fn analyze(structure: &DocumentStructure) -> DocumentQuality {
        let mut issues = Vec::new();
        let mut suggestions = Vec::new();

        // Check for title
        if structure.title.is_none() {
            issues.push(QualityIssue {
                severity: IssueSeverity::Warning,
                description: "Document has no title".to_string(),
            });
            suggestions
                .push("Add a main heading (# Title) at the start of the document".to_string());
        }

        // Check heading structure
        let mut prev_level = 0u8;
        for heading in &structure.headings {
            if heading.level > prev_level + 1 && prev_level > 0 {
                issues.push(QualityIssue {
                    severity: IssueSeverity::Warning,
                    description: format!(
                        "Heading level jumps from {} to {}: '{}'",
                        prev_level, heading.level, heading.text
                    ),
                });
            }
            prev_level = heading.level;
        }

        // Check word count
        if structure.word_count < 100 {
            issues.push(QualityIssue {
                severity: IssueSeverity::Info,
                description: "Document is very short".to_string(),
            });
        } else if structure.word_count > 5000 {
            suggestions.push("Consider breaking long documents into multiple sections".to_string());
        }

        // Check for broken/empty links
        for link in &structure.links {
            if link.url.is_empty() {
                issues.push(QualityIssue {
                    severity: IssueSeverity::Error,
                    description: format!("Empty link URL for text: '{}'", link.text),
                });
            }
            if link.text.is_empty() {
                issues.push(QualityIssue {
                    severity: IssueSeverity::Warning,
                    description: format!("Link has no text: '{}'", link.url),
                });
            }
        }

        // Check for images without alt text
        for image in &structure.images {
            if image.alt.is_empty() {
                issues.push(QualityIssue {
                    severity: IssueSeverity::Warning,
                    description: format!("Image missing alt text: '{}'", image.src),
                });
            }
        }

        // Calculate scores
        let structure_score = Self::calculate_structure_score(structure, &issues);
        let readability_score = Self::calculate_readability_score(structure);
        let overall_score = u32::midpoint(structure_score, readability_score);

        DocumentQuality {
            overall_score,
            readability_score,
            structure_score,
            issues,
            suggestions,
        }
    }

    /// Calculate structure score
    fn calculate_structure_score(structure: &DocumentStructure, issues: &[QualityIssue]) -> u32 {
        let mut score = 100u32;

        // Deduct for issues
        for issue in issues {
            match issue.severity {
                IssueSeverity::Error => score = score.saturating_sub(15),
                IssueSeverity::Warning => score = score.saturating_sub(5),
                IssueSeverity::Info => score = score.saturating_sub(2),
            }
        }

        // Bonus for good structure
        if structure.title.is_some() {
            score = score.saturating_add(5).min(100);
        }
        if !structure.headings.is_empty() {
            score = score.saturating_add(5).min(100);
        }

        score
    }

    /// Calculate readability score (simplified Flesch-Kincaid style)
    fn calculate_readability_score(structure: &DocumentStructure) -> u32 {
        let words = structure.word_count;
        if words == 0 {
            return 50;
        }

        // Count sentences (rough estimate)
        let sentence_count = structure.plain_text.matches(['.', '!', '?']).count().max(1);

        // Average words per sentence
        let avg_words_per_sentence = words as f64 / sentence_count as f64;

        // Optimal is around 15-20 words per sentence
        let score = if avg_words_per_sentence < 10.0 {
            70 + ((avg_words_per_sentence / 10.0) * 20.0) as u32
        } else if avg_words_per_sentence <= 20.0 {
            90 + (10.0 - (avg_words_per_sentence - 15.0).abs()) as u32
        } else if avg_words_per_sentence <= 30.0 {
            70 - ((avg_words_per_sentence - 20.0) * 2.0) as u32
        } else {
            50
        };

        score.min(100)
    }
}

/// Document table of contents generator
pub struct TocGenerator;

impl TocGenerator {
    /// Generate table of contents from document structure
    #[must_use]
    pub fn generate(structure: &DocumentStructure) -> Vec<TocEntry> {
        structure
            .headings
            .iter()
            .map(|h| TocEntry {
                level: h.level,
                text: h.text.clone(),
                anchor: h.anchor.clone(),
            })
            .collect()
    }

    /// Generate table of contents as markdown
    #[must_use]
    pub fn generate_markdown(structure: &DocumentStructure) -> String {
        let mut result = String::new();

        for heading in &structure.headings {
            let indent = "  ".repeat((heading.level - 1) as usize);
            let anchor = heading
                .anchor
                .as_ref()
                .map(|a| format!("#{a}"))
                .unwrap_or_default();

            let _ = writeln!(result, "{}- [{}]({})", indent, heading.text, anchor);
        }

        result
    }
}

/// Table of contents entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TocEntry {
    /// Heading level
    pub level: u8,
    /// Heading text
    pub text: String,
    /// Anchor link
    pub anchor: Option<String>,
}

/// Document metadata extractor
pub struct MetadataExtractor;

impl MetadataExtractor {
    /// Extract metadata from document
    #[must_use]
    pub fn extract(content: &str) -> DocumentMetadata {
        let structure = DocumentParser::parse(content);
        let quality = QualityAnalyzer::analyze(&structure);

        DocumentMetadata {
            format: structure.format,
            title: structure.title,
            word_count: structure.word_count,
            char_count: structure.char_count,
            reading_time_minutes: structure.reading_time_minutes,
            heading_count: structure.stats.heading_count,
            link_count: structure.stats.link_count,
            image_count: structure.stats.image_count,
            code_block_count: structure.stats.code_block_count,
            quality_score: quality.overall_score,
            external_links: structure.links.iter().filter(|l| l.is_external).count(),
            internal_links: structure.links.iter().filter(|l| !l.is_external).count(),
        }
    }
}

/// Document metadata summary
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DocumentMetadata {
    /// Document format
    pub format: DocumentFormat,
    /// Document title
    pub title: Option<String>,
    /// Word count
    pub word_count: usize,
    /// Character count
    pub char_count: usize,
    /// Estimated reading time
    pub reading_time_minutes: u32,
    /// Number of headings
    pub heading_count: usize,
    /// Number of links
    pub link_count: usize,
    /// Number of images
    pub image_count: usize,
    /// Number of code blocks
    pub code_block_count: usize,
    /// Quality score
    pub quality_score: u32,
    /// External link count
    pub external_links: usize,
    /// Internal link count
    pub internal_links: usize,
}

/// Error type for PDF parsing
#[derive(Debug, Clone)]
pub enum PdfParseError {
    /// IO error reading PDF
    IoError(String),
    /// Invalid PDF format
    InvalidFormat(String),
    /// PDF parsing failed
    ParseError(String),
    /// Text extraction failed
    ExtractionError(String),
}

impl std::fmt::Display for PdfParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PdfParseError::IoError(e) => write!(f, "IO error: {e}"),
            PdfParseError::InvalidFormat(e) => write!(f, "Invalid PDF format: {e}"),
            PdfParseError::ParseError(e) => write!(f, "Parse error: {e}"),
            PdfParseError::ExtractionError(e) => write!(f, "Extraction error: {e}"),
        }
    }
}

impl std::error::Error for PdfParseError {}

/// PDF document parser
pub struct PdfParser;

impl PdfParser {
    /// Parse a PDF document from binary data
    pub fn parse(data: &[u8]) -> Result<DocumentStructure, PdfParseError> {
        use lopdf::Document;

        let doc = Document::load_mem(data).map_err(|e| PdfParseError::ParseError(e.to_string()))?;

        let mut all_text = String::new();
        let mut page_count = 0;

        // Extract text from all pages
        let pages = doc.get_pages();
        for (page_num, _) in &pages {
            page_count += 1;
            if let Ok(text) = Self::extract_page_text(&doc, *page_num) {
                all_text.push_str(&text);
                all_text.push('\n');
            }
        }

        let plain_text = Self::clean_extracted_text(&all_text);
        let word_count = plain_text.split_whitespace().count();
        let char_count = plain_text.chars().count();

        // Try to extract title from metadata or first heading
        let title = Self::extract_title(&doc, &plain_text);

        // Extract headings (based on text analysis)
        let headings = Self::detect_headings(&plain_text);
        let heading_count = headings.len();

        // Extract links from PDF
        let links = Self::extract_links(&doc);
        let link_count = links.len();

        Ok(DocumentStructure {
            format: DocumentFormat::Pdf,
            title,
            headings,
            links,
            images: Vec::new(), // PDF image extraction is complex
            code_blocks: Vec::new(),
            plain_text,
            word_count,
            char_count,
            reading_time_minutes: (word_count / 200).max(1) as u32,
            stats: DocumentStats {
                heading_count,
                paragraph_count: page_count,
                link_count,
                ..Default::default()
            },
        })
    }

    /// Extract text from a specific page
    fn extract_page_text(doc: &lopdf::Document, page_num: u32) -> Result<String, PdfParseError> {
        let page_id = doc
            .page_iter()
            .nth((page_num - 1) as usize)
            .ok_or_else(|| PdfParseError::ExtractionError(format!("Page {page_num} not found")))?;

        let content = doc
            .get_page_content(page_id)
            .map_err(|e| PdfParseError::ExtractionError(e.to_string()))?;

        // Parse content stream for text
        let text = Self::parse_content_stream(&content, doc);
        Ok(text)
    }

    /// Parse PDF content stream to extract text
    fn parse_content_stream(content: &[u8], doc: &lopdf::Document) -> String {
        use lopdf::content::Content;

        let mut text = String::new();

        if let Ok(content_obj) = Content::decode(content) {
            for operation in content_obj.operations {
                match operation.operator.as_str() {
                    "Tj" | "TJ" => {
                        // Text showing operators
                        for operand in &operation.operands {
                            Self::extract_text_from_object(operand, doc, &mut text);
                        }
                    }
                    "'" | "\"" => {
                        // Text with newline
                        text.push('\n');
                        for operand in &operation.operands {
                            Self::extract_text_from_object(operand, doc, &mut text);
                        }
                    }
                    _ => {}
                }
            }
        }

        text
    }

    /// Extract text from a PDF object
    fn extract_text_from_object(obj: &lopdf::Object, _doc: &lopdf::Document, text: &mut String) {
        use lopdf::Object;

        match obj {
            Object::String(bytes, _) => {
                // Try UTF-8 first, then PDFDocEncoding (Latin-1)
                if let Ok(s) = std::str::from_utf8(bytes) {
                    text.push_str(s);
                } else {
                    // Fall back to Latin-1
                    let s: String = bytes.iter().map(|&b| b as char).collect();
                    text.push_str(&s);
                }
            }
            Object::Array(arr) => {
                for item in arr {
                    match item {
                        Object::String(bytes, _) => {
                            if let Ok(s) = std::str::from_utf8(bytes) {
                                text.push_str(s);
                            } else {
                                let s: String = bytes.iter().map(|&b| b as char).collect();
                                text.push_str(&s);
                            }
                        }
                        Object::Integer(n) => {
                            // Negative numbers indicate kerning/spacing
                            if *n < -100 {
                                text.push(' ');
                            }
                        }
                        Object::Real(n) => {
                            if *n < -100.0 {
                                text.push(' ');
                            }
                        }
                        _ => {}
                    }
                }
            }
            _ => {}
        }
    }

    /// Clean extracted text
    fn clean_extracted_text(text: &str) -> String {
        // Remove excessive whitespace and normalize
        let mut result = String::new();
        let mut last_was_space = true;
        let mut last_was_newline = true;

        for c in text.chars() {
            if c == '\n' || c == '\r' {
                if !last_was_newline {
                    result.push('\n');
                    last_was_newline = true;
                    last_was_space = true;
                }
            } else if c.is_whitespace() {
                if !last_was_space {
                    result.push(' ');
                    last_was_space = true;
                }
            } else if c.is_control() {
                // Skip control characters
            } else {
                result.push(c);
                last_was_space = false;
                last_was_newline = false;
            }
        }

        result.trim().to_string()
    }

    /// Extract title from PDF metadata or content
    fn extract_title(doc: &lopdf::Document, text: &str) -> Option<String> {
        // Try to get title from PDF metadata
        if let Ok(info) = doc.trailer.get(b"Info") {
            if let Ok(lopdf::Object::Dictionary(dict)) = doc.get_object(info.as_reference().ok()?) {
                if let Ok(lopdf::Object::String(bytes, _)) = dict.get(b"Title") {
                    if let Ok(s) = std::str::from_utf8(bytes) {
                        let title = s.trim();
                        if !title.is_empty() {
                            return Some(title.to_string());
                        }
                    }
                }
            }
        }

        // Fall back to first line that looks like a title
        for line in text.lines().take(10) {
            let trimmed = line.trim();
            if trimmed.len() > 3 && trimmed.len() < 200 {
                // Likely a title if it's reasonably sized and not a full paragraph
                let word_count = trimmed.split_whitespace().count();
                if word_count <= 15 && !trimmed.ends_with('.') {
                    return Some(trimmed.to_string());
                }
            }
        }

        None
    }

    /// Detect headings from text structure
    fn detect_headings(text: &str) -> Vec<Heading> {
        let mut headings = Vec::new();
        let lines: Vec<&str> = text.lines().collect();
        let numbered_heading = regex::Regex::new(r"^(\d+\.)+\d*\s+[A-Z]").ok();

        for (i, line) in lines.iter().enumerate() {
            let trimmed = line.trim();

            // Skip empty or very long lines
            if trimmed.is_empty() || trimmed.len() > 200 {
                continue;
            }

            // Detect numbered headings (e.g., "1. Introduction", "1.2.3 Methods")
            if let Some(re) = &numbered_heading {
                if re.is_match(trimmed) {
                    let depth = trimmed.matches('.').count();
                    let level = (depth.min(5) + 1) as u8;
                    headings.push(Heading {
                        level,
                        text: trimmed.to_string(),
                        anchor: None,
                    });
                    continue;
                }
            }

            // Detect ALL CAPS headings (common in PDFs)
            let word_count = trimmed.split_whitespace().count();
            if (1..=10).contains(&word_count)
                && trimmed
                    .chars()
                    .filter(|c| c.is_alphabetic())
                    .all(char::is_uppercase)
                && trimmed.chars().any(char::is_alphabetic)
            {
                headings.push(Heading {
                    level: 2,
                    text: trimmed.to_string(),
                    anchor: None,
                });
                continue;
            }

            // Detect headings followed by blank line or significantly shorter
            if i + 1 < lines.len() {
                let next_line = lines[i + 1].trim();
                if next_line.is_empty() && word_count <= 8 && !trimmed.ends_with('.') {
                    // Check if it's capitalized like a title
                    if trimmed.chars().next().is_some_and(char::is_uppercase) {
                        headings.push(Heading {
                            level: 3,
                            text: trimmed.to_string(),
                            anchor: None,
                        });
                    }
                }
            }
        }

        headings
    }

    /// Extract links from PDF annotations
    fn extract_links(doc: &lopdf::Document) -> Vec<Link> {
        let mut links = Vec::new();

        for (_page_num, page_id) in doc.get_pages() {
            if let Ok(lopdf::Object::Dictionary(dict)) = doc.get_object(page_id) {
                if let Ok(annots) = dict.get(b"Annots") {
                    Self::extract_links_from_annotations(doc, annots, &mut links);
                }
            }
        }

        links
    }

    /// Extract links from annotation array
    fn extract_links_from_annotations(
        doc: &lopdf::Document,
        annots: &lopdf::Object,
        links: &mut Vec<Link>,
    ) {
        let annot_refs = match annots {
            lopdf::Object::Array(arr) => arr.clone(),
            lopdf::Object::Reference(r) => {
                if let Ok(lopdf::Object::Array(arr)) = doc.get_object(*r) {
                    arr.clone()
                } else {
                    return;
                }
            }
            _ => return,
        };

        for annot_ref in annot_refs {
            let annot = match &annot_ref {
                lopdf::Object::Reference(r) => doc.get_object(*r).ok().cloned(),
                obj => Some(obj.clone()),
            };

            if let Some(lopdf::Object::Dictionary(dict)) = annot {
                // Check if it's a link annotation
                if let Ok(lopdf::Object::Name(subtype)) = dict.get(b"Subtype") {
                    if subtype == b"Link" {
                        // Extract URL from action
                        if let Ok(action) = dict.get(b"A") {
                            Self::extract_url_from_action(doc, action, links);
                        }
                    }
                }
            }
        }
    }

    /// Extract URL from PDF action
    fn extract_url_from_action(
        doc: &lopdf::Document,
        action: &lopdf::Object,
        links: &mut Vec<Link>,
    ) {
        let action_dict = match action {
            lopdf::Object::Dictionary(dict) => dict.clone(),
            lopdf::Object::Reference(r) => {
                if let Ok(lopdf::Object::Dictionary(dict)) = doc.get_object(*r) {
                    dict.clone()
                } else {
                    return;
                }
            }
            _ => return,
        };

        // Check for URI action
        if let Ok(lopdf::Object::Name(s)) = action_dict.get(b"S") {
            if s == b"URI" {
                if let Ok(lopdf::Object::String(bytes, _)) = action_dict.get(b"URI") {
                    if let Ok(url) = std::str::from_utf8(bytes) {
                        let is_external = url.starts_with("http://")
                            || url.starts_with("https://")
                            || url.starts_with("mailto:");
                        links.push(Link {
                            url: url.to_string(),
                            text: String::new(), // PDF links often don't have separate text
                            title: None,
                            is_external,
                        });
                    }
                }
            }
        }
    }
}

/// PDF document metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PdfMetadata {
    /// PDF version
    pub version: String,
    /// Page count
    pub page_count: usize,
    /// Document title
    pub title: Option<String>,
    /// Document author
    pub author: Option<String>,
    /// Document subject
    pub subject: Option<String>,
    /// Document keywords
    pub keywords: Option<String>,
    /// Creator application
    pub creator: Option<String>,
    /// Producer application
    pub producer: Option<String>,
    /// Creation date
    pub creation_date: Option<String>,
    /// Modification date
    pub modification_date: Option<String>,
    /// Whether the PDF is encrypted
    pub is_encrypted: bool,
}

impl PdfParser {
    /// Extract metadata from PDF
    pub fn extract_metadata(data: &[u8]) -> Result<PdfMetadata, PdfParseError> {
        use lopdf::Document;

        let doc = Document::load_mem(data).map_err(|e| PdfParseError::ParseError(e.to_string()))?;

        let page_count = doc.get_pages().len();
        let version = doc.version.clone();
        let is_encrypted = doc.is_encrypted();

        let mut metadata = PdfMetadata {
            version,
            page_count,
            title: None,
            author: None,
            subject: None,
            keywords: None,
            creator: None,
            producer: None,
            creation_date: None,
            modification_date: None,
            is_encrypted,
        };

        // Extract info dictionary
        if let Ok(info_ref) = doc.trailer.get(b"Info") {
            if let Ok(r) = info_ref.as_reference() {
                if let Ok(lopdf::Object::Dictionary(dict)) = doc.get_object(r) {
                    metadata.title = Self::get_string_from_dict(dict, b"Title");
                    metadata.author = Self::get_string_from_dict(dict, b"Author");
                    metadata.subject = Self::get_string_from_dict(dict, b"Subject");
                    metadata.keywords = Self::get_string_from_dict(dict, b"Keywords");
                    metadata.creator = Self::get_string_from_dict(dict, b"Creator");
                    metadata.producer = Self::get_string_from_dict(dict, b"Producer");
                    metadata.creation_date = Self::get_string_from_dict(dict, b"CreationDate");
                    metadata.modification_date = Self::get_string_from_dict(dict, b"ModDate");
                }
            }
        }

        Ok(metadata)
    }

    /// Get string value from dictionary
    fn get_string_from_dict(dict: &lopdf::Dictionary, key: &[u8]) -> Option<String> {
        if let Ok(lopdf::Object::String(bytes, _)) = dict.get(key) {
            if let Ok(s) = std::str::from_utf8(bytes) {
                let trimmed = s.trim();
                if !trimmed.is_empty() {
                    return Some(trimmed.to_string());
                }
            }
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_format_detection_markdown() {
        let content = "# Hello World\n\nThis is a **test** document.";
        assert_eq!(DocumentFormat::detect(content), DocumentFormat::Markdown);
    }

    #[test]
    fn test_format_detection_html() {
        let content = "<!DOCTYPE html><html><body><p>Hello</p></body></html>";
        assert_eq!(DocumentFormat::detect(content), DocumentFormat::Html);
    }

    #[test]
    fn test_markdown_heading_parsing() {
        let content = "# Title\n\n## Section 1\n\n### Subsection\n\nSome text.";
        let structure = DocumentParser::parse(content);

        assert_eq!(structure.headings.len(), 3);
        assert_eq!(structure.headings[0].level, 1);
        assert_eq!(structure.headings[0].text, "Title");
        assert_eq!(structure.headings[1].level, 2);
        assert_eq!(structure.headings[2].level, 3);
    }

    #[test]
    fn test_markdown_link_extraction() {
        let content = "Check out [Rust](https://rust-lang.org) and [this](./local.md).";
        let structure = DocumentParser::parse(content);

        assert_eq!(structure.links.len(), 2);
        assert!(structure.links[0].is_external);
        assert!(!structure.links[1].is_external);
    }

    #[test]
    fn test_markdown_image_extraction() {
        let content = "![Alt text](image.png \"Title\")";
        let structure = DocumentParser::parse(content);

        assert_eq!(structure.images.len(), 1);
        assert_eq!(structure.images[0].alt, "Alt text");
        assert_eq!(structure.images[0].src, "image.png");
    }

    #[test]
    fn test_markdown_code_block_extraction() {
        let content = "```rust\nfn main() {}\n```";
        let structure = DocumentParser::parse(content);

        assert_eq!(structure.code_blocks.len(), 1);
        assert_eq!(structure.code_blocks[0].language, Some("rust".to_string()));
    }

    #[test]
    fn test_html_to_plain_text() {
        let html = "<p>Hello <strong>world</strong>!</p>";
        let plain = DocumentParser::html_to_plain_text(html);
        assert_eq!(plain, "Hello world !");
    }

    #[test]
    fn test_quality_analysis() {
        let content = "# My Document\n\nThis is a test document with some content.\n\n## Section\n\nMore content here.";
        let structure = DocumentParser::parse(content);
        let quality = QualityAnalyzer::analyze(&structure);

        assert!(quality.overall_score > 70);
        assert!(
            quality.issues.is_empty()
                || quality
                    .issues
                    .iter()
                    .all(|i| i.severity != IssueSeverity::Error)
        );
    }
}