optirs-core 0.3.1

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
// 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>,
}

/// 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
    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)
    }

    /// 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 citation in citations {
            let formatted = self.format_citation_with_style(citation, citation_style)?;
            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,
    ) -> Result<String> {
        match style.intext_format {
            InTextFormat::AuthorYear => self.format_author_year(citation, style),
            InTextFormat::Numbered => self.format_numbered(citation, style),
            InTextFormat::Superscript => self.format_superscript(citation, style),
            InTextFormat::AuthorNumber => self.format_author_number(citation, style),
            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) -> Result<String> {
        // In a real implementation, you'd need to assign numbers based on order
        Ok(format!("[{}]", 1)) // Placeholder
    }

    fn format_superscript(&self, citation: &Citation, style: &CitationStyle) -> Result<String> {
        Ok("¹".to_string()) // Placeholder
    }

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

    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();
        let first = chars
            .next()
            .expect("unwrap failed")
            .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,
            },
        }
    }
}

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

    /// Parse BibTeX content into citations
    pub fn parse_bibtex(&self, content: &str) -> Result<Vec<Citation>> {
        // Simplified BibTeX parser
        // In a real implementation, you'd want a proper BibTeX parser
        let mut citations = Vec::new();
        let lines: Vec<&str> = content.lines().collect();
        let mut current_entry: Option<(String, PublicationType, HashMap<String, String>)> = None;

        for line in lines {
            let line = line.trim();

            if line.starts_with('@') {
                // Save previous entry
                if let Some((key, pub_type, fields)) = current_entry.take() {
                    if let Ok(citation) = self.fields_to_citation(key, pub_type, fields) {
                        citations.push(citation);
                    }
                }

                // Parse new entry
                if let Some(pos) = line.find('{') {
                    let entry_type = line[1..pos].to_lowercase();
                    let pub_type = self.bibtex_type_to_publication_type(&entry_type);

                    let key_part = &line[pos + 1..];
                    if let Some(comma_pos) = key_part.find(',') {
                        let key = key_part[..comma_pos].trim().to_string();
                        current_entry = Some((key, pub_type, HashMap::new()));
                    }
                }
            } else if line.contains('=') && current_entry.is_some() {
                // Parse field
                if let Some(eq_pos) = line.find('=') {
                    let field_name = line[..eq_pos].trim().to_lowercase();
                    let field_value = line[eq_pos + 1..]
                        .trim()
                        .trim_start_matches('{')
                        .trim_end_matches("},")
                        .trim_start_matches('"')
                        .trim_end_matches("\",")
                        .to_string();

                    if let Some((_, _, ref mut fields)) = current_entry {
                        fields.insert(field_name, field_value);
                    }
                }
            }
        }

        // Save last entry
        if let Some((key, pub_type, fields)) = current_entry {
            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> {
        let title = 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);
    }
}