optirs-core 0.3.2

OptiRS core optimization algorithms and utilities
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
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
// Citation management and bibliographic tools
//
// This module provides comprehensive citation management, BibTeX parsing,
// and automated reference generation for academic publications.

use crate::error::{OptimError, Result};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Citation manager for handling bibliographic references
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CitationManager {
    /// Citation database
    pub citations: HashMap<String, Citation>,
    /// Citation styles
    pub styles: HashMap<String, CitationStyle>,
    /// Default citation style
    pub default_style: String,
    /// Citation groups/categories
    pub groups: HashMap<String, CitationGroup>,
    /// Import/export settings
    pub settings: CitationSettings,
    /// Last modified timestamp
    pub modified_at: DateTime<Utc>,
}

/// Individual citation record
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Citation {
    /// Citation key/identifier
    pub key: String,
    /// Publication type
    pub publication_type: PublicationType,
    /// Title
    pub title: String,
    /// Authors
    pub authors: Vec<Author>,
    /// Publication year
    pub year: Option<u32>,
    /// Journal/Conference/Publisher
    pub venue: Option<String>,
    /// Volume number
    pub volume: Option<String>,
    /// Issue/Number
    pub issue: Option<String>,
    /// Page numbers
    pub pages: Option<String>,
    /// DOI
    pub doi: Option<String>,
    /// URL
    pub url: Option<String>,
    /// Abstract
    pub abstracttext: Option<String>,
    /// Keywords
    pub keywords: Vec<String>,
    /// Notes
    pub notes: Option<String>,
    /// Custom fields
    pub custom_fields: HashMap<String, String>,
    /// File attachments
    pub attachments: Vec<String>,
    /// Citation groups
    pub groups: Vec<String>,
    /// Import source
    pub import_source: Option<String>,
    /// Creation timestamp
    pub created_at: DateTime<Utc>,
    /// Last modified timestamp
    pub modified_at: DateTime<Utc>,
}

/// Publication types for citations
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum PublicationType {
    /// Journal article
    Article,
    /// Conference paper
    InProceedings,
    /// Book
    Book,
    /// Book chapter
    InCollection,
    /// PhD thesis
    PhDThesis,
    /// Master's thesis
    MastersThesis,
    /// Technical report
    TechReport,
    /// Manual
    Manual,
    /// Miscellaneous
    Misc,
    /// Unpublished work
    Unpublished,
    /// Preprint
    Preprint,
    /// Patent
    Patent,
    /// Software
    Software,
    /// Dataset
    Dataset,
}

/// Author information for citations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Author {
    /// First name
    pub first_name: String,
    /// Last name
    pub last_name: String,
    /// Middle name/initial
    pub middle_name: Option<String>,
    /// Name suffix (Jr., Sr., etc.)
    pub suffix: Option<String>,
    /// ORCID identifier
    pub orcid: Option<String>,
    /// Author affiliation
    pub affiliation: Option<String>,
}

/// Citation style definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CitationStyle {
    /// Style name
    pub name: String,
    /// Style description
    pub description: String,
    /// In-text citation format
    pub intext_format: InTextFormat,
    /// Bibliography format
    pub bibliography_format: BibliographyFormat,
    /// Formatting rules
    pub formatting_rules: FormattingRules,
    /// Sorting rules
    pub sorting_rules: SortingRules,
}

/// In-text citation formats
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum InTextFormat {
    /// Author-year format: (Smith, 2023)
    AuthorYear,
    /// Numbered format: \[1\]
    Numbered,
    /// Superscript format: ¹
    Superscript,
    /// Author-number format: Smith \[1\]
    AuthorNumber,
    /// Footnote format
    Footnote,
}

/// Bibliography formatting
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BibliographyFormat {
    /// Entry separator
    pub entry_separator: String,
    /// Field separators
    pub field_separators: HashMap<String, String>,
    /// Name formatting
    pub name_format: NameFormat,
    /// Title formatting
    pub title_format: TitleFormat,
    /// Date formatting
    pub date_format: DateFormat,
    /// Punctuation rules
    pub punctuation: PunctuationRules,
}

/// Name formatting options
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum NameFormat {
    /// Last, First Middle
    LastFirstMiddle,
    /// First Middle Last
    FirstMiddleLast,
    /// Last, F. M.
    LastFirstInitial,
    /// F. M. Last
    FirstInitialLast,
    /// Last, F.M.
    LastFirstInitialNoSpace,
}

/// Title formatting options
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum TitleFormat {
    /// Title Case
    TitleCase,
    /// Sentence case
    SentenceCase,
    /// UPPERCASE
    Uppercase,
    /// lowercase
    Lowercase,
    /// As entered
    AsEntered,
}

/// Date formatting options
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum DateFormat {
    /// 2023
    Year,
    /// December 2023
    MonthYear,
    /// Dec. 2023
    MonthAbbrevYear,
    /// December 15, 2023
    FullDate,
    /// 2023-12-15
    ISODate,
}

/// Punctuation rules
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PunctuationRules {
    /// Use periods after abbreviations
    pub periods_after_abbreviations: bool,
    /// Use commas between fields
    pub commas_between_fields: bool,
    /// Use parentheses around year
    pub parentheses_around_year: bool,
    /// Quote titles
    pub quote_titles: bool,
    /// Italicize journal names
    pub italicize_journals: bool,
}

/// Formatting rules for citations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FormattingRules {
    /// Maximum authors to show
    pub max_authors: Option<usize>,
    /// Text to use for "et al."
    pub et_altext: String,
    /// Minimum authors before using et al.
    pub et_al_threshold: usize,
    /// Use title case for titles
    pub title_case: bool,
    /// Abbreviate journal names
    pub abbreviate_journals: bool,
    /// Include DOI
    pub include_doi: bool,
    /// Include URL
    pub include_url: bool,
}

/// Sorting rules for bibliography
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SortingRules {
    /// Primary sort field
    pub primary_sort: SortField,
    /// Secondary sort field
    pub secondary_sort: Option<SortField>,
    /// Sort direction
    pub sort_direction: SortDirection,
    /// Group by type
    pub group_by_type: bool,
}

/// Sort fields
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum SortField {
    /// Author last name
    Author,
    /// Publication year
    Year,
    /// Title
    Title,
    /// Journal/venue
    Venue,
    /// Citation key
    Key,
    /// Date added
    DateAdded,
}

/// Sort direction
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum SortDirection {
    /// Ascending order
    Ascending,
    /// Descending order
    Descending,
}

/// Citation group for organizing references
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CitationGroup {
    /// Group name
    pub name: String,
    /// Group description
    pub description: String,
    /// Group color (for UI)
    pub color: Option<String>,
    /// Citation keys in this group
    pub citation_keys: Vec<String>,
    /// Creation timestamp
    pub created_at: DateTime<Utc>,
}

/// Citation manager settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CitationSettings {
    /// Auto-generate keys
    pub auto_generate_keys: bool,
    /// Key generation pattern
    pub key_pattern: String,
    /// Auto-import from DOI
    pub auto_import_doi: bool,
    /// Auto-import from URL
    pub auto_import_url: bool,
    /// Duplicate detection
    pub duplicate_detection: bool,
    /// Backup settings
    pub backup_enabled: bool,
    /// Export formats
    pub export_formats: Vec<ExportFormat>,
}

/// Export formats
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ExportFormat {
    /// BibTeX format
    BibTeX,
    /// RIS format
    RIS,
    /// EndNote XML
    EndNote,
    /// JSON format
    JSON,
    /// CSV format
    CSV,
    /// Word bibliography
    Word,
}

/// BibTeX parser and exporter
#[derive(Debug)]
pub struct BibTeXProcessor {
    /// Parser settings
    settings: BibTeXSettings,
}

/// BibTeX processing settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BibTeXSettings {
    /// Preserve case in titles
    pub preserve_case: bool,
    /// Convert to UTF-8
    pub utf8_conversion: bool,
    /// Clean up formatting
    pub cleanup_formatting: bool,
    /// Validate entries
    pub validate_entries: bool,
}

/// Citation search and discovery
#[derive(Debug)]
pub struct CitationDiscovery {
    /// Search engines configuration
    search_engines: Vec<SearchEngine>,
    /// API keys for services
    api_keys: HashMap<String, String>,
}

impl CitationDiscovery {
    /// Create a discovery service with no search engines registered yet.
    pub fn new() -> Self {
        Self {
            search_engines: Vec::new(),
            api_keys: HashMap::new(),
        }
    }

    /// Register a search engine (builder style).
    pub fn with_search_engine(mut self, engine: SearchEngine) -> Self {
        self.search_engines.push(engine);
        self
    }

    /// Register a search engine on an existing instance.
    pub fn add_search_engine(&mut self, engine: SearchEngine) {
        self.search_engines.push(engine);
    }

    /// Store the API key/token used to authenticate against `engine_name`.
    pub fn set_api_key(&mut self, engine_name: &str, key: &str) {
        self.api_keys
            .insert(engine_name.to_string(), key.to_string());
    }

    /// All currently registered search engines.
    pub fn search_engines(&self) -> &[SearchEngine] {
        &self.search_engines
    }

    /// Whether an API key/token has been configured for `engine_name`.
    pub fn has_credentials(&self, engine_name: &str) -> bool {
        self.api_keys.contains_key(engine_name)
    }

    /// The registered engines that advertise support for `query_type`,
    /// ordered by ascending rate limit (most conservative first) so callers
    /// naturally prefer the engine least likely to be throttled.
    ///
    /// This performs no network I/O: `CitationDiscovery` only tracks engine
    /// configuration and routes queries to the right engine locally. Issuing
    /// the actual HTTP request against the selected engine's `endpoint` is
    /// left to the caller.
    pub fn engines_for(&self, query_type: &QueryType) -> Vec<&SearchEngine> {
        let mut engines: Vec<&SearchEngine> = self
            .search_engines
            .iter()
            .filter(|engine| engine.query_types.contains(query_type))
            .collect();
        engines.sort_by(|a, b| {
            a.rate_limit
                .partial_cmp(&b.rate_limit)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        engines
    }
}

impl Default for CitationDiscovery {
    fn default() -> Self {
        Self::new()
    }
}

/// Search engine configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchEngine {
    /// Engine name
    pub name: String,
    /// API endpoint
    pub endpoint: String,
    /// Rate limit (requests per second)
    pub rate_limit: f64,
    /// Supported query types
    pub query_types: Vec<QueryType>,
}

/// Query types for citation search
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum QueryType {
    /// DOI lookup
    DOI,
    /// Title search
    Title,
    /// Author search
    Author,
    /// ArXiv ID
    ArXiv,
    /// PubMed ID
    PubMed,
    /// ISBN
    ISBN,
    /// Free text search
    FreeText,
}

/// Citation network analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CitationNetwork {
    /// Citations in the network
    pub citations: Vec<String>,
    /// Citation relationships
    pub relationships: Vec<CitationRelationship>,
    /// Network metrics
    pub metrics: NetworkMetrics,
}

/// Citation relationship
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CitationRelationship {
    /// Citing paper
    pub citing: String,
    /// Cited paper
    pub cited: String,
    /// Relationship type
    pub relationship_type: RelationshipType,
    /// Relationship strength
    pub strength: f64,
}

/// Relationship types between citations
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum RelationshipType {
    /// Direct citation
    DirectCitation,
    /// Co-citation (cited together)
    CoCitation,
    /// Bibliographic coupling (share references)
    BibliographicCoupling,
    /// Same author
    SameAuthor,
    /// Same venue
    SameVenue,
    /// Similar topic
    SimilarTopic,
}

/// Network analysis metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkMetrics {
    /// Total nodes (papers)
    pub total_nodes: usize,
    /// Total edges (relationships)
    pub total_edges: usize,
    /// Network density
    pub density: f64,
    /// Average clustering coefficient
    pub clustering_coefficient: f64,
    /// Most cited papers
    pub most_cited: Vec<(String, usize)>,
    /// Most influential authors
    pub most_influential_authors: Vec<(String, f64)>,
}

impl Default for CitationManager {
    fn default() -> Self {
        Self::new()
    }
}

impl CitationManager {
    /// Create a new citation manager
    pub fn new() -> Self {
        let mut styles = HashMap::new();
        styles.insert("APA".to_string(), Self::create_apa_style());
        styles.insert("IEEE".to_string(), Self::create_ieee_style());
        styles.insert("ACM".to_string(), Self::create_acm_style());

        Self {
            citations: HashMap::new(),
            styles,
            default_style: "APA".to_string(),
            groups: HashMap::new(),
            settings: CitationSettings::default(),
            modified_at: Utc::now(),
        }
    }

    /// Add a citation to the database
    pub fn add_citation(&mut self, citation: Citation) -> Result<()> {
        if self.citations.contains_key(&citation.key) {
            return Err(OptimError::InvalidConfig(format!(
                "Citation with key '{}' already exists",
                citation.key
            )));
        }

        self.citations.insert(citation.key.clone(), citation);
        self.modified_at = Utc::now();
        Ok(())
    }

    /// Get a citation by key
    pub fn get_citation(&self, key: &str) -> Option<&Citation> {
        self.citations.get(key)
    }

    /// Update an existing citation
    pub fn update_citation(&mut self, key: &str, citation: Citation) -> Result<()> {
        if !self.citations.contains_key(key) {
            return Err(OptimError::InvalidConfig(format!(
                "Citation with key '{}' not found",
                key
            )));
        }

        self.citations.insert(key.to_string(), citation);
        self.modified_at = Utc::now();
        Ok(())
    }

    /// Remove a citation
    pub fn remove_citation(&mut self, key: &str) -> Result<()> {
        if self.citations.remove(key).is_none() {
            return Err(OptimError::InvalidConfig(format!(
                "Citation with key '{}' not found",
                key
            )));
        }

        self.modified_at = Utc::now();
        Ok(())
    }

    /// Search citations by various criteria
    pub fn search_citations(&self, query: &str) -> Vec<&Citation> {
        let query_lower = query.to_lowercase();

        self.citations
            .values()
            .filter(|citation| {
                citation.title.to_lowercase().contains(&query_lower)
                    || citation.authors.iter().any(|author| {
                        author.last_name.to_lowercase().contains(&query_lower)
                            || author.first_name.to_lowercase().contains(&query_lower)
                    })
                    || citation
                        .keywords
                        .iter()
                        .any(|keyword| keyword.to_lowercase().contains(&query_lower))
                    || citation
                        .venue
                        .as_ref()
                        .is_some_and(|venue| venue.to_lowercase().contains(&query_lower))
            })
            .collect()
    }

    /// Generate formatted citation in specified style.
    ///
    /// For numbered/superscript/author-number in-text styles, the citation's
    /// ordinal number is only well-defined relative to a bibliography (the
    /// order it appears in). Called in isolation like this, it is formatted
    /// as position 1; to get correct, distinct numbers for a set of
    /// citations use [`Self::generate_bibliography`], which assigns each
    /// citation its real position in the (sorted) list.
    pub fn format_citation(&self, key: &str, style: Option<&str>) -> Result<String> {
        let citation = self
            .get_citation(key)
            .ok_or_else(|| OptimError::InvalidConfig(format!("Citation '{}' not found", key)))?;

        let style_name = style.unwrap_or(&self.default_style);
        let citation_style = self.styles.get(style_name).ok_or_else(|| {
            OptimError::InvalidConfig(format!("Style '{}' not found", style_name))
        })?;

        self.format_citation_with_style(citation, citation_style, 1)
    }

    /// Generate bibliography for multiple citations
    pub fn generate_bibliography(
        &self,
        citation_keys: &[String],
        style: Option<&str>,
    ) -> Result<String> {
        let style_name = style.unwrap_or(&self.default_style);
        let citation_style = self.styles.get(style_name).ok_or_else(|| {
            OptimError::InvalidConfig(format!("Style '{}' not found", style_name))
        })?;

        let mut citations: Vec<&Citation> = citation_keys
            .iter()
            .filter_map(|key| self.citations.get(key))
            .collect();

        // Sort citations according to style rules
        self.sort_citations(&mut citations, &citation_style.sorting_rules);

        let mut bibliography = String::new();
        for (index, citation) in citations.into_iter().enumerate() {
            let formatted = self.format_citation_with_style(citation, citation_style, index + 1)?;
            bibliography.push_str(&formatted);
            bibliography.push('\n');
        }

        Ok(bibliography)
    }

    /// Export citations to BibTeX format
    pub fn export_bibtex(&self, citation_keys: Option<&[String]>) -> String {
        let citations: Vec<&Citation> = if let Some(_keys) = citation_keys {
            _keys
                .iter()
                .filter_map(|key| self.citations.get(key))
                .collect()
        } else {
            self.citations.values().collect()
        };

        let mut bibtex = String::new();
        for citation in citations {
            bibtex.push_str(&self.citation_to_bibtex(citation));
            bibtex.push('\n');
        }

        bibtex
    }

    /// Import citations from BibTeX
    pub fn import_bibtex(&mut self, bibtex_content: &str) -> Result<usize> {
        let processor = BibTeXProcessor::new(BibTeXSettings::default());
        let citations = processor.parse_bibtex(bibtex_content)?;

        let mut imported_count = 0;
        for citation in citations {
            if !self.citations.contains_key(&citation.key) {
                self.citations.insert(citation.key.clone(), citation);
                imported_count += 1;
            }
        }

        self.modified_at = Utc::now();
        Ok(imported_count)
    }

    /// Create a citation group
    pub fn create_group(&mut self, name: &str, description: &str) -> String {
        let group_id = uuid::Uuid::new_v4().to_string();
        let group = CitationGroup {
            name: name.to_string(),
            description: description.to_string(),
            color: None,
            citation_keys: Vec::new(),
            created_at: Utc::now(),
        };

        self.groups.insert(group_id.clone(), group);
        group_id
    }

    /// Add citation to group
    pub fn add_to_group(&mut self, group_id: &str, citation_key: &str) -> Result<()> {
        let group = self
            .groups
            .get_mut(group_id)
            .ok_or_else(|| OptimError::InvalidConfig(format!("Group '{}' not found", group_id)))?;

        if !group.citation_keys.contains(&citation_key.to_string()) {
            group.citation_keys.push(citation_key.to_string());
        }

        Ok(())
    }

    fn format_citation_with_style(
        &self,
        citation: &Citation,
        style: &CitationStyle,
        position: usize,
    ) -> Result<String> {
        match style.intext_format {
            InTextFormat::AuthorYear => self.format_author_year(citation, style),
            InTextFormat::Numbered => self.format_numbered(citation, style, position),
            InTextFormat::Superscript => self.format_superscript(citation, style, position),
            InTextFormat::AuthorNumber => self.format_author_number(citation, style, position),
            InTextFormat::Footnote => self.format_footnote(citation, style),
        }
    }

    fn format_author_year(&self, citation: &Citation, style: &CitationStyle) -> Result<String> {
        let authors = self.format_authors(&citation.authors, &style.formatting_rules);
        let year = citation
            .year
            .map(|y| y.to_string())
            .unwrap_or_else(|| "n.d.".to_string());

        Ok(format!("({}, {})", authors, year))
    }

    fn format_numbered(
        &self,
        _citation: &Citation,
        _style: &CitationStyle,
        position: usize,
    ) -> Result<String> {
        Ok(format!("[{position}]"))
    }

    fn format_superscript(
        &self,
        _citation: &Citation,
        _style: &CitationStyle,
        position: usize,
    ) -> Result<String> {
        Ok(to_superscript(position))
    }

    fn format_author_number(
        &self,
        citation: &Citation,
        style: &CitationStyle,
        position: usize,
    ) -> Result<String> {
        let authors = self.format_authors(&citation.authors, &style.formatting_rules);
        Ok(format!("{authors} [{position}]"))
    }

    fn format_footnote(&self, citation: &Citation, style: &CitationStyle) -> Result<String> {
        self.format_full_citation(citation, style)
    }

    fn format_full_citation(&self, citation: &Citation, style: &CitationStyle) -> Result<String> {
        let mut formatted = String::new();

        // Authors
        let authors = self.format_authors(&citation.authors, &style.formatting_rules);
        formatted.push_str(&authors);

        // Title
        let title = self.format_title(&citation.title, &style.bibliography_format.title_format);
        formatted.push_str(&format!(". {}.", title));

        // Venue
        if let Some(venue) = &citation.venue {
            let venue_formatted = if style.bibliography_format.punctuation.italicize_journals {
                format!(" *{}*", venue)
            } else {
                format!(" {venue}")
            };
            formatted.push_str(&venue_formatted);
        }

        // Year
        if let Some(year) = citation.year {
            if style
                .bibliography_format
                .punctuation
                .parentheses_around_year
            {
                formatted.push_str(&format!(" ({})", year));
            } else {
                formatted.push_str(&format!(" {year}"));
            }
        }

        // DOI
        if style.formatting_rules.include_doi {
            if let Some(doi) = &citation.doi {
                formatted.push_str(&format!(". DOI: {doi}"));
            }
        }

        Ok(formatted)
    }

    fn format_authors(&self, authors: &[Author], rules: &FormattingRules) -> String {
        if authors.is_empty() {
            return "Anonymous".to_string();
        }

        let max_authors = rules.max_authors.unwrap_or(authors.len());
        let display_authors = if authors.len() > max_authors && max_authors > 0 {
            &authors[..max_authors]
        } else {
            authors
        };

        let mut formatted_authors = Vec::new();
        for author in display_authors {
            let formatted = format!("{}, {}", author.last_name, author.first_name);
            formatted_authors.push(formatted);
        }

        let mut result = formatted_authors.join(", ");

        if authors.len() > max_authors {
            result.push_str(&format!(", {}", rules.et_altext));
        }

        result
    }

    fn format_title(&self, title: &str, format: &TitleFormat) -> String {
        match format {
            TitleFormat::TitleCase => self.to_title_case(title),
            TitleFormat::SentenceCase => self.to_sentence_case(title),
            TitleFormat::Uppercase => title.to_uppercase(),
            TitleFormat::Lowercase => title.to_lowercase(),
            TitleFormat::AsEntered => title.to_string(),
        }
    }

    fn to_title_case(&self, s: &str) -> String {
        s.split_whitespace()
            .map(|word| {
                let mut chars = word.chars();
                match chars.next() {
                    None => String::new(),
                    Some(first) => {
                        first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase()
                    }
                }
            })
            .collect::<Vec<_>>()
            .join(" ")
    }

    fn to_sentence_case(&self, s: &str) -> String {
        if s.is_empty() {
            return String::new();
        }

        let mut chars = s.chars();
        // The emptiness guard above makes `next()` a `Some`, but reading it out
        // fallibly means a future change to that guard cannot turn this into a
        // panic.
        let Some(leading) = chars.next() else {
            return String::new();
        };
        let first = leading.to_uppercase().collect::<String>();
        first + &chars.as_str().to_lowercase()
    }

    fn sort_citations(&self, citations: &mut Vec<&Citation>, rules: &SortingRules) {
        citations.sort_by(|a, b| {
            let primary_cmp = self.compare_by_field(a, b, &rules.primary_sort);
            if primary_cmp == std::cmp::Ordering::Equal {
                if let Some(secondary) = &rules.secondary_sort {
                    self.compare_by_field(a, b, secondary)
                } else {
                    std::cmp::Ordering::Equal
                }
            } else {
                primary_cmp
            }
        });

        if rules.sort_direction == SortDirection::Descending {
            citations.reverse();
        }
    }

    fn compare_by_field(
        &self,
        a: &Citation,
        b: &Citation,
        field: &SortField,
    ) -> std::cmp::Ordering {
        match field {
            SortField::Author => {
                let a_author = a
                    .authors
                    .first()
                    .map(|au| au.last_name.as_str())
                    .unwrap_or("");
                let b_author = b
                    .authors
                    .first()
                    .map(|au| au.last_name.as_str())
                    .unwrap_or("");
                a_author.cmp(b_author)
            }
            SortField::Year => a.year.cmp(&b.year),
            SortField::Title => a.title.cmp(&b.title),
            SortField::Venue => a.venue.cmp(&b.venue),
            SortField::Key => a.key.cmp(&b.key),
            SortField::DateAdded => a.created_at.cmp(&b.created_at),
        }
    }

    fn citation_to_bibtex(&self, citation: &Citation) -> String {
        let mut bibtex = format!(
            "@{}{{{},\n",
            self.publication_type_to_bibtex(&citation.publication_type),
            citation.key
        );

        bibtex.push_str(&format!("  title = {{{}}},\n", citation.title));

        if !citation.authors.is_empty() {
            let authors = citation
                .authors
                .iter()
                .map(|a| format!("{} {}", a.first_name, a.last_name))
                .collect::<Vec<_>>()
                .join(" and ");
            bibtex.push_str(&format!("  author = {{{}}},\n", authors));
        }

        if let Some(year) = citation.year {
            bibtex.push_str(&format!("  year = {{{}}},\n", year));
        }

        if let Some(venue) = &citation.venue {
            let field_name = match citation.publication_type {
                PublicationType::Article => "journal",
                PublicationType::InProceedings => "booktitle",
                PublicationType::Book => "publisher",
                PublicationType::InCollection => "booktitle",
                PublicationType::PhDThesis => "school",
                PublicationType::MastersThesis => "school",
                PublicationType::TechReport => "institution",
                PublicationType::Manual => "organization",
                PublicationType::Misc => "howpublished",
                PublicationType::Unpublished => "note",
                PublicationType::Preprint => "archivePrefix",
                PublicationType::Patent => "assignee",
                PublicationType::Software => "url",
                PublicationType::Dataset => "url",
            };
            bibtex.push_str(&format!("  {} = {{{}}},\n", field_name, venue));
        }

        if let Some(volume) = &citation.volume {
            bibtex.push_str(&format!("  volume = {{{}}},\n", volume));
        }

        if let Some(pages) = &citation.pages {
            bibtex.push_str(&format!("  pages = {{{}}},\n", pages));
        }

        if let Some(doi) = &citation.doi {
            bibtex.push_str(&format!("  doi = {{{}}},\n", doi));
        }

        bibtex.push_str("}\n");
        bibtex
    }

    fn publication_type_to_bibtex(&self, pub_type: &PublicationType) -> &'static str {
        match pub_type {
            PublicationType::Article => "article",
            PublicationType::InProceedings => "inproceedings",
            PublicationType::Book => "book",
            PublicationType::InCollection => "incollection",
            PublicationType::PhDThesis => "phdthesis",
            PublicationType::MastersThesis => "mastersthesis",
            PublicationType::TechReport => "techreport",
            PublicationType::Manual => "manual",
            PublicationType::Misc => "misc",
            PublicationType::Unpublished => "unpublished",
            PublicationType::Preprint => "misc",
            PublicationType::Patent => "misc",
            PublicationType::Software => "misc",
            PublicationType::Dataset => "misc",
        }
    }

    fn create_apa_style() -> CitationStyle {
        CitationStyle {
            name: "APA".to_string(),
            description: "American Psychological Association style".to_string(),
            intext_format: InTextFormat::AuthorYear,
            bibliography_format: BibliographyFormat {
                entry_separator: "\n".to_string(),
                field_separators: {
                    let mut separators = HashMap::new();
                    separators.insert("author_title".to_string(), ". ".to_string());
                    separators.insert("title_venue".to_string(), ". ".to_string());
                    separators
                },
                name_format: NameFormat::LastFirstInitial,
                title_format: TitleFormat::SentenceCase,
                date_format: DateFormat::Year,
                punctuation: PunctuationRules {
                    periods_after_abbreviations: true,
                    commas_between_fields: true,
                    parentheses_around_year: true,
                    quote_titles: false,
                    italicize_journals: true,
                },
            },
            formatting_rules: FormattingRules {
                max_authors: Some(7),
                et_altext: "et al.".to_string(),
                et_al_threshold: 8,
                title_case: false,
                abbreviate_journals: false,
                include_doi: true,
                include_url: false,
            },
            sorting_rules: SortingRules {
                primary_sort: SortField::Author,
                secondary_sort: Some(SortField::Year),
                sort_direction: SortDirection::Ascending,
                group_by_type: false,
            },
        }
    }

    fn create_ieee_style() -> CitationStyle {
        CitationStyle {
            name: "IEEE".to_string(),
            description: "Institute of Electrical and Electronics Engineers style".to_string(),
            intext_format: InTextFormat::Numbered,
            bibliography_format: BibliographyFormat {
                entry_separator: "\n".to_string(),
                field_separators: HashMap::new(),
                name_format: NameFormat::FirstInitialLast,
                title_format: TitleFormat::AsEntered,
                date_format: DateFormat::Year,
                punctuation: PunctuationRules {
                    periods_after_abbreviations: true,
                    commas_between_fields: true,
                    parentheses_around_year: false,
                    quote_titles: true,
                    italicize_journals: true,
                },
            },
            formatting_rules: FormattingRules {
                max_authors: None,
                et_altext: "et al.".to_string(),
                et_al_threshold: 7,
                title_case: false,
                abbreviate_journals: true,
                include_doi: true,
                include_url: false,
            },
            sorting_rules: SortingRules {
                primary_sort: SortField::Year,
                secondary_sort: Some(SortField::Author),
                sort_direction: SortDirection::Ascending,
                group_by_type: false,
            },
        }
    }

    fn create_acm_style() -> CitationStyle {
        CitationStyle {
            name: "ACM".to_string(),
            description: "Association for Computing Machinery style".to_string(),
            intext_format: InTextFormat::Numbered,
            bibliography_format: BibliographyFormat {
                entry_separator: "\n".to_string(),
                field_separators: HashMap::new(),
                name_format: NameFormat::FirstMiddleLast,
                title_format: TitleFormat::TitleCase,
                date_format: DateFormat::Year,
                punctuation: PunctuationRules {
                    periods_after_abbreviations: true,
                    commas_between_fields: true,
                    parentheses_around_year: false,
                    quote_titles: false,
                    italicize_journals: true,
                },
            },
            formatting_rules: FormattingRules {
                max_authors: None,
                et_altext: "et al.".to_string(),
                et_al_threshold: 3,
                title_case: true,
                abbreviate_journals: false,
                include_doi: true,
                include_url: true,
            },
            sorting_rules: SortingRules {
                primary_sort: SortField::Author,
                secondary_sort: Some(SortField::Year),
                sort_direction: SortDirection::Ascending,
                group_by_type: false,
            },
        }
    }
}

/// Render a 1-based citation position as Unicode superscript digits, e.g.
/// `12` -> `"¹²"`. Used by the [`InTextFormat::Superscript`] citation style.
fn to_superscript(position: usize) -> String {
    const DIGITS: [char; 10] = ['', '¹', '²', '³', '', '', '', '', '', ''];
    position
        .to_string()
        .chars()
        .map(|c| c.to_digit(10).map(|d| DIGITS[d as usize]).unwrap_or(c))
        .collect()
}

/// Split raw BibTeX source into `(entry_type, key, fields)` tuples.
///
/// This is a brace-depth-aware tokenizer rather than a line-oriented scanner:
/// it walks the input character by character so that field values spanning
/// multiple physical lines and values containing nested braces (both
/// extremely common in real-world `.bib` files) are captured correctly. It
/// is shared by [`BibTeXProcessor::parse_bibtex`] and
/// [`crate::research::publications::Bibliography::parse_bibtex`] so the
/// parsing logic has a single source of truth.
pub(crate) fn parse_bibtex_entries(
    content: &str,
) -> Vec<(String, String, HashMap<String, String>)> {
    let chars: Vec<char> = content.chars().collect();
    let n = chars.len();
    let mut i = 0;
    let mut entries = Vec::new();

    while i < n {
        while i < n && chars[i] != '@' {
            i += 1;
        }
        if i >= n {
            break;
        }
        i += 1; // skip '@'

        let type_start = i;
        while i < n && chars[i] != '{' && chars[i] != '(' {
            i += 1;
        }
        if i >= n {
            break;
        }
        let entry_type: String = chars[type_start..i]
            .iter()
            .collect::<String>()
            .trim()
            .to_lowercase();
        let open_char = chars[i];
        let close_char = if open_char == '{' { '}' } else { ')' };
        i += 1; // skip opening delimiter

        let body_start = i;
        let mut depth = 1usize;
        while i < n && depth > 0 {
            if chars[i] == open_char {
                depth += 1;
            } else if chars[i] == close_char {
                depth -= 1;
                if depth == 0 {
                    break;
                }
            }
            i += 1;
        }
        let body: String = chars[body_start..i].iter().collect();
        if i < n {
            i += 1; // skip closing delimiter
        }

        if entry_type.is_empty() {
            continue;
        }

        if let Some(comma_pos) = body.find(',') {
            let key = body[..comma_pos].trim().to_string();
            let fields = parse_bibtex_fields(&body[comma_pos + 1..]);
            if !key.is_empty() {
                entries.push((entry_type, key, fields));
            }
        }
    }

    entries
}

/// Parse the `field = value, field = value, ...` body of a single BibTeX
/// entry into a name -> value map, honoring brace-delimited values (with
/// nesting), quote-delimited values, and bare (unquoted) values such as
/// `year = 2024`. Internal line breaks inside a value are collapsed to a
/// single space, matching how BibTeX treats whitespace as insignificant.
fn parse_bibtex_fields(body: &str) -> HashMap<String, String> {
    let chars: Vec<char> = body.chars().collect();
    let n = chars.len();
    let mut i = 0;
    let mut fields = HashMap::new();

    while i < n {
        while i < n && (chars[i].is_whitespace() || chars[i] == ',') {
            i += 1;
        }
        if i >= n {
            break;
        }

        let name_start = i;
        while i < n && chars[i] != '=' {
            i += 1;
        }
        if i >= n {
            break;
        }
        let field_name = chars[name_start..i]
            .iter()
            .collect::<String>()
            .trim()
            .to_lowercase();
        i += 1; // skip '='
        while i < n && chars[i].is_whitespace() {
            i += 1;
        }
        if i >= n {
            break;
        }

        let raw_value: String = if chars[i] == '{' {
            i += 1;
            let val_start = i;
            let mut depth = 1usize;
            while i < n && depth > 0 {
                match chars[i] {
                    '{' => depth += 1,
                    '}' => {
                        depth -= 1;
                        if depth == 0 {
                            break;
                        }
                    }
                    _ => {}
                }
                i += 1;
            }
            let value = chars[val_start..i].iter().collect();
            if i < n {
                i += 1; // skip closing '}'
            }
            value
        } else if chars[i] == '"' {
            i += 1;
            let val_start = i;
            while i < n && chars[i] != '"' {
                i += 1;
            }
            let value = chars[val_start..i].iter().collect();
            if i < n {
                i += 1; // skip closing '"'
            }
            value
        } else {
            let val_start = i;
            while i < n && chars[i] != ',' {
                i += 1;
            }
            chars[val_start..i].iter().collect::<String>()
        };

        if !field_name.is_empty() {
            let normalized = raw_value.split_whitespace().collect::<Vec<_>>().join(" ");
            fields.insert(field_name, normalized);
        }

        while i < n && chars[i] != ',' {
            i += 1;
        }
    }

    fields
}

impl BibTeXProcessor {
    /// Create a new BibTeX processor
    pub fn new(settings: BibTeXSettings) -> Self {
        Self { settings }
    }

    /// The settings this processor applies.
    pub fn settings(&self) -> &BibTeXSettings {
        &self.settings
    }

    /// Normalise a BibTeX field value according to the configured settings.
    ///
    /// * `preserve_case == false` strips BibTeX's protective braces (`{DNA}`
    ///   becomes `DNA`), which is what makes a style's own capitalisation rules
    ///   apply. With it set, the braces are kept verbatim.
    /// * `utf8_conversion` decodes the common LaTeX accent escapes into the
    ///   characters they denote, so a parsed citation is usable outside LaTeX.
    fn apply_settings(&self, value: String) -> String {
        let mut value = if self.settings.preserve_case {
            value
        } else {
            value.replace(['{', '}'], "")
        };
        if self.settings.utf8_conversion {
            for (escape, replacement) in [
                ("\\\"a", "ä"),
                ("\\\"o", "ö"),
                ("\\\"u", "ü"),
                ("\\'e", "é"),
                ("\\'a", "á"),
                ("\\`e", "è"),
                ("\\^o", "ô"),
                ("\\~n", "ñ"),
                ("\\c c", "ç"),
                ("\\ss", "ß"),
                ("---", "\u{2014}"),
                ("--", "\u{2013}"),
            ] {
                value = value.replace(escape, replacement);
            }
        }
        value
    }

    /// Parse BibTeX content into citations.
    ///
    /// Unlike a line-oriented scanner, this walks the input character by
    /// character and tracks brace depth, so field values that span multiple
    /// physical lines (very common for `abstract`/`note` fields) or that
    /// contain nested braces (e.g. `title = {The {Quick} Brown Fox}`) are
    /// captured in full instead of being truncated at the first newline.
    pub fn parse_bibtex(&self, content: &str) -> Result<Vec<Citation>> {
        let mut citations = Vec::new();

        for (entry_type, key, fields) in parse_bibtex_entries(content) {
            if matches!(entry_type.as_str(), "comment" | "string" | "preamble") {
                continue;
            }
            let pub_type = self.bibtex_type_to_publication_type(&entry_type);
            if let Ok(citation) = self.fields_to_citation(key, pub_type, fields) {
                citations.push(citation);
            }
        }

        Ok(citations)
    }

    fn bibtex_type_to_publication_type(&self, bibtex_type: &str) -> PublicationType {
        match bibtex_type {
            "article" => PublicationType::Article,
            "inproceedings" | "conference" => PublicationType::InProceedings,
            "book" => PublicationType::Book,
            "incollection" | "inbook" => PublicationType::InCollection,
            "phdthesis" => PublicationType::PhDThesis,
            "mastersthesis" => PublicationType::MastersThesis,
            "techreport" => PublicationType::TechReport,
            "manual" => PublicationType::Manual,
            "unpublished" => PublicationType::Unpublished,
            _ => PublicationType::Misc,
        }
    }

    fn fields_to_citation(
        &self,
        key: String,
        pub_type: PublicationType,
        fields: HashMap<String, String>,
    ) -> Result<Citation> {
        // `settings` actually shapes the parse now. Until 0.3.2 it was stored
        // by `new` and never read, so `preserve_case` and `utf8_conversion`
        // were inert: a title's protective braces survived into the rendered
        // citation and LaTeX escapes were never decoded.
        let title = self.apply_settings(fields.get("title").cloned().unwrap_or_default());

        // Parse authors
        let authors = if let Some(author_str) = fields.get("author") {
            self.parse_authors(author_str)
        } else {
            Vec::new()
        };

        // Parse year
        let year = fields.get("year").and_then(|y| y.parse().ok());

        // Determine venue field based on publication type
        let venue = match pub_type {
            PublicationType::Article => fields.get("journal").cloned(),
            PublicationType::InProceedings => fields.get("booktitle").cloned(),
            PublicationType::Book => fields.get("publisher").cloned(),
            PublicationType::InCollection => fields.get("booktitle").cloned(),
            PublicationType::PhDThesis => fields.get("school").cloned(),
            PublicationType::MastersThesis => fields.get("school").cloned(),
            PublicationType::TechReport => fields.get("institution").cloned(),
            PublicationType::Manual => fields.get("organization").cloned(),
            PublicationType::Misc => fields.get("howpublished").cloned(),
            PublicationType::Unpublished => fields.get("note").cloned(),
            PublicationType::Preprint => fields.get("archivePrefix").cloned(),
            PublicationType::Patent => fields.get("assignee").cloned(),
            PublicationType::Software => fields.get("url").cloned(),
            PublicationType::Dataset => fields.get("url").cloned(),
        };

        let now = Utc::now();

        Ok(Citation {
            key,
            publication_type: pub_type,
            title,
            authors,
            year,
            venue,
            volume: fields.get("volume").cloned(),
            issue: fields.get("number").cloned(),
            pages: fields.get("pages").cloned(),
            doi: fields.get("doi").cloned(),
            url: fields.get("url").cloned(),
            abstracttext: fields.get("abstract").cloned(),
            keywords: Vec::new(),
            notes: fields.get("note").cloned(),
            custom_fields: HashMap::new(),
            attachments: Vec::new(),
            groups: Vec::new(),
            import_source: Some("BibTeX".to_string()),
            created_at: now,
            modified_at: now,
        })
    }

    fn parse_authors(&self, author_str: &str) -> Vec<Author> {
        author_str
            .split(" and ")
            .map(|author_part| {
                let author_part = author_part.trim();
                if let Some(comma_pos) = author_part.find(',') {
                    // "Last, First" format
                    let last_name = author_part[..comma_pos].trim().to_string();
                    let first_name = author_part[comma_pos + 1..].trim().to_string();
                    Author {
                        first_name,
                        last_name,
                        middle_name: None,
                        suffix: None,
                        orcid: None,
                        affiliation: None,
                    }
                } else {
                    // "First Last" format
                    let parts: Vec<&str> = author_part.split_whitespace().collect();
                    if parts.len() >= 2 {
                        let first_name = parts[0].to_string();
                        let last_name = parts[parts.len() - 1].to_string();
                        let middle_name = if parts.len() > 2 {
                            Some(parts[1..parts.len() - 1].join(" "))
                        } else {
                            None
                        };
                        Author {
                            first_name,
                            last_name,
                            middle_name,
                            suffix: None,
                            orcid: None,
                            affiliation: None,
                        }
                    } else {
                        // Single name
                        Author {
                            first_name: String::new(),
                            last_name: author_part.to_string(),
                            middle_name: None,
                            suffix: None,
                            orcid: None,
                            affiliation: None,
                        }
                    }
                }
            })
            .collect()
    }
}

impl Default for CitationSettings {
    fn default() -> Self {
        Self {
            auto_generate_keys: true,
            key_pattern: "{author}{year}".to_string(),
            auto_import_doi: true,
            auto_import_url: false,
            duplicate_detection: true,
            backup_enabled: true,
            export_formats: vec![ExportFormat::BibTeX, ExportFormat::RIS],
        }
    }
}

impl Default for BibTeXSettings {
    fn default() -> Self {
        Self {
            preserve_case: true,
            utf8_conversion: true,
            cleanup_formatting: true,
            validate_entries: true,
        }
    }
}

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

    #[test]
    fn test_citation_manager_creation() {
        let manager = CitationManager::new();

        assert!(manager.styles.contains_key("APA"));
        assert!(manager.styles.contains_key("IEEE"));
        assert!(manager.styles.contains_key("ACM"));
        assert_eq!(manager.default_style, "APA");
    }

    #[test]
    fn test_add_citation() {
        let mut manager = CitationManager::new();

        let citation = Citation {
            key: "test2023".to_string(),
            publication_type: PublicationType::Article,
            title: "Test Article".to_string(),
            authors: vec![Author {
                first_name: "John".to_string(),
                last_name: "Doe".to_string(),
                middle_name: None,
                suffix: None,
                orcid: None,
                affiliation: None,
            }],
            year: Some(2023),
            venue: Some("Test Journal".to_string()),
            volume: None,
            issue: None,
            pages: None,
            doi: None,
            url: None,
            abstracttext: None,
            keywords: Vec::new(),
            notes: None,
            custom_fields: HashMap::new(),
            attachments: Vec::new(),
            groups: Vec::new(),
            import_source: None,
            created_at: Utc::now(),
            modified_at: Utc::now(),
        };

        assert!(manager.add_citation(citation).is_ok());
        assert!(manager.citations.contains_key("test2023"));
    }

    #[test]
    fn test_search_citations() {
        let mut manager = CitationManager::new();

        let citation = Citation {
            key: "test2023".to_string(),
            publication_type: PublicationType::Article,
            title: "Machine Learning Optimization".to_string(),
            authors: vec![Author {
                first_name: "Jane".to_string(),
                last_name: "Smith".to_string(),
                middle_name: None,
                suffix: None,
                orcid: None,
                affiliation: None,
            }],
            year: Some(2023),
            venue: None,
            volume: None,
            issue: None,
            pages: None,
            doi: None,
            url: None,
            abstracttext: None,
            keywords: vec!["optimization".to_string(), "machine learning".to_string()],
            notes: None,
            custom_fields: HashMap::new(),
            attachments: Vec::new(),
            groups: Vec::new(),
            import_source: None,
            created_at: Utc::now(),
            modified_at: Utc::now(),
        };

        manager.add_citation(citation).expect("unwrap failed");

        let results = manager.search_citations("optimization");
        assert_eq!(results.len(), 1);

        let results = manager.search_citations("Smith");
        assert_eq!(results.len(), 1);
    }

    // Regression test for F77: the previous line-oriented BibTeX parser
    // truncated any field value that spanned multiple physical lines (very
    // common for `abstract`/`note` fields) at the first newline, and mangled
    // values containing nested braces.
    #[test]
    fn test_parse_bibtex_handles_multiline_and_nested_braces() {
        let processor = BibTeXProcessor::new(BibTeXSettings::default());
        let bibtex = r#"
@article{smith2023multiline,
  title = {The {Quick} Brown Fox},
  author = {Smith, John and Doe, Jane},
  year = {2023},
  journal = {Journal of Testing},
  abstract = {This abstract deliberately spans
              multiple physical lines to verify
              that continuation lines are not dropped.},
}
"#;

        let citations = processor
            .parse_bibtex(bibtex)
            .expect("parse should succeed");
        assert_eq!(citations.len(), 1);
        let citation = &citations[0];
        assert_eq!(citation.key, "smith2023multiline");
        assert_eq!(citation.title, "The {Quick} Brown Fox");
        assert_eq!(citation.year, Some(2023));
        assert_eq!(citation.authors.len(), 2);

        let abstract_text = citation
            .abstracttext
            .as_ref()
            .expect("abstract should be captured");
        assert!(
            abstract_text.contains("multiple physical lines"),
            "continuation lines were dropped: {abstract_text:?}"
        );
        assert!(
            !abstract_text.contains('\n'),
            "internal newlines should be normalized to spaces: {abstract_text:?}"
        );
    }

    #[test]
    fn test_parse_bibtex_handles_multiple_entries() {
        let processor = BibTeXProcessor::new(BibTeXSettings::default());
        let bibtex = "@article{first2020,\n  title = {First},\n  year = {2020},\n}\n\
@inproceedings{second2021,\n  title = {Second},\n  year = {2021},\n}\n";

        let citations = processor
            .parse_bibtex(bibtex)
            .expect("parse should succeed");
        assert_eq!(citations.len(), 2);
        assert_eq!(citations[0].key, "first2020");
        assert_eq!(citations[1].key, "second2021");
        assert_eq!(
            citations[1].publication_type,
            PublicationType::InProceedings
        );
    }

    // Regression test for F24: `CitationDiscovery` was exported with fully
    // private fields and zero methods (not even a constructor).
    #[test]
    fn test_citation_discovery_is_constructible_and_routes_queries() {
        let doi_engine = SearchEngine {
            name: "crossref".to_string(),
            endpoint: "https://api.crossref.org".to_string(),
            rate_limit: 5.0,
            query_types: vec![QueryType::DOI, QueryType::Title],
        };
        let arxiv_engine = SearchEngine {
            name: "arxiv".to_string(),
            endpoint: "https://export.arxiv.org/api".to_string(),
            rate_limit: 1.0,
            query_types: vec![QueryType::ArXiv, QueryType::Title],
        };

        let mut discovery = CitationDiscovery::new()
            .with_search_engine(doi_engine)
            .with_search_engine(arxiv_engine);
        discovery.set_api_key("crossref", "secret-token");

        assert_eq!(discovery.search_engines().len(), 2);
        assert!(discovery.has_credentials("crossref"));
        assert!(!discovery.has_credentials("arxiv"));

        let doi_engines = discovery.engines_for(&QueryType::DOI);
        assert_eq!(doi_engines.len(), 1);
        assert_eq!(doi_engines[0].name, "crossref");

        // Both engines support Title search; the lower rate-limit engine
        // (arxiv, 1 req/s) should be preferred over crossref (5 req/s).
        let title_engines = discovery.engines_for(&QueryType::Title);
        assert_eq!(title_engines.len(), 2);
        assert_eq!(title_engines[0].name, "arxiv");

        assert!(discovery.engines_for(&QueryType::ISBN).is_empty());
    }

    fn make_citation(key: &str, last_name: &str, year: u32) -> Citation {
        let now = Utc::now();
        Citation {
            key: key.to_string(),
            publication_type: PublicationType::Article,
            title: format!("Paper by {last_name}"),
            authors: vec![Author {
                first_name: "A".to_string(),
                last_name: last_name.to_string(),
                middle_name: None,
                suffix: None,
                orcid: None,
                affiliation: None,
            }],
            year: Some(year),
            venue: Some("Journal".to_string()),
            volume: None,
            issue: None,
            pages: None,
            doi: None,
            url: None,
            abstracttext: None,
            keywords: Vec::new(),
            notes: None,
            custom_fields: HashMap::new(),
            attachments: Vec::new(),
            groups: Vec::new(),
            import_source: None,
            created_at: now,
            modified_at: now,
        }
    }

    // Regression test for F25: every entry in a numbered-style bibliography
    // was rendered as "[1]" regardless of its real position in the list.
    #[test]
    fn test_generate_bibliography_assigns_distinct_numbers() {
        let mut manager = CitationManager::new();
        manager
            .add_citation(make_citation("adams2020", "Adams", 2020))
            .expect("add should succeed");
        manager
            .add_citation(make_citation("zimmerman2021", "Zimmerman", 2021))
            .expect("add should succeed");

        let bibliography = manager
            .generate_bibliography(
                &["adams2020".to_string(), "zimmerman2021".to_string()],
                Some("IEEE"),
            )
            .expect("bibliography generation should succeed");

        let lines: Vec<&str> = bibliography.lines().filter(|l| !l.is_empty()).collect();
        assert_eq!(lines.len(), 2);
        // Author-ascending sort puts Adams (position 1) before Zimmerman (position 2).
        assert!(
            lines[0].starts_with("[1]"),
            "first entry should be numbered [1]: {:?}",
            lines[0]
        );
        assert!(
            lines[1].starts_with("[2]"),
            "second entry should be numbered [2], not a duplicate [1]: {:?}",
            lines[1]
        );
    }

    #[test]
    fn test_to_superscript_renders_multi_digit_positions() {
        assert_eq!(to_superscript(1), "¹");
        assert_eq!(to_superscript(12), "¹²");
        assert_eq!(to_superscript(103), "¹⁰³");
    }
}