microscope-memory 1.2.0

Pure binary cognitive memory engine with REST API bridge for LLM integration. Zero-JSON core, mmap-based, hierarchical, sub-microsecond search.
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
//! Knowledge Base — a memóriában tárolt architektúrákból, szimulációs eredményekből
//! és döntési mintákból épített kereshető tudásbázis.
//!
//! Ez a modul folyamatosan tanul a szimulációkból, döntésekből és eureka pillanatokból,
//! és strukturált tudást biztosít a heurisztikus döntéshozó számára.

use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::{SystemTime, UNIX_EPOCH};

use crate::architecture_simulator::{Architecture, SimulationMetrics};
use crate::heuristic_decision::{DecisionLogEntry, HeuristicPattern};

// ─── Alap típusok ───────────────────────────────────────────────────────────

/// Egy tudásbázis bejegyzés típusa
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum KnowledgeEntryType {
    /// Architektúra minta
    ArchitecturePattern,
    /// Szimulációs eredmény
    SimulationResult,
    /// Döntési minta
    DecisionPattern,
    /// Eureka/Insight
    Insight,
    /// Heurisztikus szabály
    HeuristicRule,
    /// Legjobb gyakorlat
    BestPractice,
    /// Ismert hiba / buktató
    KnownPitfall,
    /// Egyedi
    Custom(String),
}

/// Egy tudásbázis bejegyzés
#[derive(Debug, Clone)]
pub struct KnowledgeEntry {
    pub id: String,
    pub entry_type: KnowledgeEntryType,
    pub title: String,
    pub description: String,
    pub tags: Vec<String>,
    /// Kapcsolódó bejegyzések ID-i
    pub related_entries: Vec<String>,
    /// Megbízhatósági pontszám (0.0 - 1.0)
    pub confidence: f64,
    /// Hányszor volt hasznos
    pub usefulness: u64,
    /// Létrehozás időpontja
    pub created_at: u64,
    /// Utolsó módosítás
    pub updated_at: u64,
    /// Forrás (pl. melyik architektúrából, döntésből származik)
    pub source: String,
    /// Kontextus (milyen körülmények között érvényes)
    pub context: String,
}

/// Keresési eredmény
#[derive(Debug, Clone)]
pub struct SearchResult {
    pub entry: KnowledgeEntry,
    pub relevance_score: f64,
    pub matched_tags: Vec<String>,
}

/// Tudásbázis statisztikák
#[derive(Debug, Clone)]
pub struct KnowledgeBaseStats {
    pub total_entries: u64,
    pub architecture_patterns: u64,
    pub simulation_results: u64,
    pub decision_patterns: u64,
    pub insights: u64,
    pub heuristic_rules: u64,
    pub best_practices: u64,
    pub known_pitfalls: u64,
    pub avg_confidence: f64,
    pub total_usefulness: u64,
}

// ─── Tudásbázis ─────────────────────────────────────────────────────────────

/// A fő tudásbázis rendszer
pub struct KnowledgeBase {
    entries: Arc<RwLock<HashMap<String, KnowledgeEntry>>>,
    tag_index: Arc<RwLock<HashMap<String, Vec<String>>>>, // tag -> entry_ids
    type_index: Arc<RwLock<HashMap<KnowledgeEntryType, Vec<String>>>>, // type -> entry_ids
    /// Tanult asszociációk (entry_id -> related_entry_id -> weight)
    associations: Arc<RwLock<HashMap<String, HashMap<String, f64>>>>,
    #[allow(dead_code)]
    next_id: Arc<RwLock<u64>>,
}

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

impl KnowledgeBase {
    /// Létrehoz egy új tudásbázist
    pub fn new() -> Self {
        Self {
            entries: Arc::new(RwLock::new(HashMap::new())),
            tag_index: Arc::new(RwLock::new(HashMap::new())),
            type_index: Arc::new(RwLock::new(HashMap::new())),
            associations: Arc::new(RwLock::new(HashMap::new())),
            next_id: Arc::new(RwLock::new(1)),
        }
    }

    /// Hozzáad egy új tudásbázis bejegyzést
    pub fn add_entry(&self, entry: KnowledgeEntry) -> String {
        let mut entries = crate::sync_guard::write_lock(&self.entries);
        let mut tag_index = crate::sync_guard::write_lock(&self.tag_index);
        let mut type_index = crate::sync_guard::write_lock(&self.type_index);

        let id = entry.id.clone();
        entries.insert(id.clone(), entry.clone());

        // Indexelés tagek szerint
        for tag in &entry.tags {
            tag_index.entry(tag.clone()).or_default().push(id.clone());
        }

        // Indexelés típus szerint
        type_index
            .entry(entry.entry_type.clone())
            .or_default()
            .push(id.clone());

        id
    }

    /// Lekér egy bejegyzést ID alapján
    pub fn get_entry(&self, id: &str) -> Option<KnowledgeEntry> {
        let entries = crate::sync_guard::read_lock(&self.entries);
        entries.get(id).cloned()
    }

    /// Keresés a tudásbázisban
    pub fn search(&self, query: &str, max_results: usize) -> Vec<SearchResult> {
        let entries = crate::sync_guard::read_lock(&self.entries);
        let query_lower = query.to_lowercase();
        let query_words: Vec<&str> = query_lower.split_whitespace().collect();

        let mut scored: Vec<(f64, &KnowledgeEntry, Vec<String>)> = entries
            .values()
            .map(|entry| {
                let mut score = 0.0;

                // Cím egyezés
                if entry.title.to_lowercase().contains(&query_lower) {
                    score += 3.0;
                }

                // Leírás egyezés
                if entry.description.to_lowercase().contains(&query_lower) {
                    score += 2.0;
                }

                // Tag egyezés
                let matched_tags: Vec<String> = entry
                    .tags
                    .iter()
                    .filter(|tag| query_words.iter().any(|w| tag.to_lowercase().contains(w)))
                    .cloned()
                    .collect();
                score += matched_tags.len() as f64 * 1.5;

                // Kontextus egyezés
                if entry.context.to_lowercase().contains(&query_lower) {
                    score += 1.0;
                }

                // Hasznosság bónusz
                score += (entry.usefulness as f64).ln_1p() * 0.5;

                // Megbízhatóság bónusz
                score += entry.confidence * 0.5;

                (score, entry, matched_tags)
            })
            .filter(|(score, _, _)| *score > 0.0)
            .collect();

        // Rendezés pontszám szerint
        scored.sort_by(|a, b| b.0.total_cmp(&a.0));

        scored
            .into_iter()
            .take(max_results)
            .map(|(score, entry, matched_tags)| SearchResult {
                entry: entry.clone(),
                relevance_score: score,
                matched_tags,
            })
            .collect()
    }

    /// Bejegyzés hasznosságának növelése
    pub fn mark_useful(&self, id: &str) {
        let mut entries = crate::sync_guard::write_lock(&self.entries);
        if let Some(entry) = entries.get_mut(id) {
            entry.usefulness += 1;
            entry.updated_at = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs();
        }
    }

    /// Asszociáció tanulása két bejegyzés között
    pub fn learn_association(&self, from_id: &str, to_id: &str, weight: f64) {
        let mut associations = crate::sync_guard::write_lock(&self.associations);
        associations
            .entry(from_id.to_string())
            .or_default()
            .entry(to_id.to_string())
            .and_modify(|w| *w = (*w + weight) / 2.0) // mozgóátlag
            .or_insert(weight);
    }

    /// Kapcsolódó bejegyzések lekérése
    pub fn get_related(&self, id: &str, max_results: usize) -> Vec<KnowledgeEntry> {
        let associations = crate::sync_guard::read_lock(&self.associations);
        let entries = crate::sync_guard::read_lock(&self.entries);

        if let Some(related) = associations.get(id) {
            let mut scored: Vec<(f64, &KnowledgeEntry)> = related
                .iter()
                .filter_map(|(rel_id, weight)| entries.get(rel_id).map(|entry| (*weight, entry)))
                .collect();

            scored.sort_by(|a, b| b.0.total_cmp(&a.0));

            scored
                .into_iter()
                .take(max_results)
                .map(|(_, entry)| entry.clone())
                .collect()
        } else {
            Vec::new()
        }
    }

    /// Architektúra minta hozzáadása a szimulációs eredményből
    pub fn add_from_simulation(&self, arch: &Architecture, metrics: &SimulationMetrics) -> String {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let mut tags = vec![
            "architecture".to_string(),
            arch.name.clone(),
            format!("components_{}", arch.components.len()),
            format!("connections_{}", arch.connections.len()),
        ];

        if !metrics.bottleneck_components.is_empty() {
            tags.push("bottleneck".to_string());
            for b in &metrics.bottleneck_components {
                tags.push(format!("bottleneck_{}", b));
            }
        }

        if metrics.stability_score > 0.8 {
            tags.push("high_stability".to_string());
        }
        if metrics.resilience_score > 0.8 {
            tags.push("high_resilience".to_string());
        }

        let entry = KnowledgeEntry {
            id: format!("sim_{}", rand::random::<u32>()),
            entry_type: KnowledgeEntryType::SimulationResult,
            title: format!("Simulation: {} (stability={:.2}, resilience={:.2})",
                arch.name, metrics.stability_score, metrics.resilience_score),
            description: format!(
                "Architecture '{}' simulated: avg_latency={:.2}ms, throughput={:.0}req/s, error_rate={:.2}%, bottlenecks={}",
                arch.name, metrics.avg_latency_ms, metrics.throughput_req_per_sec,
                metrics.error_rate * 100.0, metrics.bottleneck_components.len()
            ),
            tags,
            related_entries: Vec::new(),
            confidence: metrics.stability_score.min(metrics.resilience_score),
            usefulness: 0,
            created_at: now,
            updated_at: now,
            source: format!("simulation_{}", arch.id),
            context: format!("load_pattern=standard, duration={}s", metrics.simulation_time_secs),
        };

        self.add_entry(entry)
    }

    /// Döntési minta hozzáadása
    pub fn add_from_decision(
        &self,
        decision: &DecisionLogEntry,
        pattern: &HeuristicPattern,
    ) -> String {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let entry = KnowledgeEntry {
            id: format!("decision_{}", rand::random::<u32>()),
            entry_type: KnowledgeEntryType::DecisionPattern,
            title: format!(
                "Decision pattern: {} (success={:.1}%)",
                pattern.name,
                pattern.success_rate * 100.0
            ),
            description: format!(
                "Decision type: {:?}, selected: {}, outcome_score: {:.2}, reflection: {}",
                decision.decision_type,
                decision.selected_option,
                decision.outcome_score,
                decision.reflection
            ),
            tags: vec![
                "decision".to_string(),
                format!("{:?}", decision.decision_type),
                format!("success_{:.0}", pattern.success_rate * 100.0),
            ],
            related_entries: Vec::new(),
            confidence: pattern.success_rate,
            usefulness: pattern.usage_count,
            created_at: now,
            updated_at: now,
            source: format!("decision_{}", decision.decision_id),
            context: pattern.context.clone(),
        };

        self.add_entry(entry)
    }

    /// Eureka/Insight hozzáadása
    pub fn add_insight(
        &self,
        title: &str,
        description: &str,
        tags: Vec<String>,
        source: &str,
    ) -> String {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let entry = KnowledgeEntry {
            id: format!("insight_{}", rand::random::<u32>()),
            entry_type: KnowledgeEntryType::Insight,
            title: title.to_string(),
            description: description.to_string(),
            tags: {
                let mut t = vec!["insight".to_string(), "eureka".to_string()];
                t.extend(tags);
                t
            },
            related_entries: Vec::new(),
            confidence: 0.5, // insights start with medium confidence
            usefulness: 0,
            created_at: now,
            updated_at: now,
            source: source.to_string(),
            context: "discovery".to_string(),
        };

        self.add_entry(entry)
    }

    /// Legjobb gyakorlat hozzáadása
    pub fn add_best_practice(
        &self,
        title: &str,
        description: &str,
        context: &str,
        tags: Vec<String>,
    ) -> String {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let entry = KnowledgeEntry {
            id: format!("practice_{}", rand::random::<u32>()),
            entry_type: KnowledgeEntryType::BestPractice,
            title: title.to_string(),
            description: description.to_string(),
            tags: {
                let mut t = vec!["best_practice".to_string(), "recommendation".to_string()];
                t.extend(tags);
                t
            },
            related_entries: Vec::new(),
            confidence: 0.7,
            usefulness: 0,
            created_at: now,
            updated_at: now,
            source: "knowledge_base".to_string(),
            context: context.to_string(),
        };

        self.add_entry(entry)
    }

    /// Ismert hiba/buktátó hozzáadása
    pub fn add_pitfall(
        &self,
        title: &str,
        description: &str,
        context: &str,
        tags: Vec<String>,
    ) -> String {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let entry = KnowledgeEntry {
            id: format!("pitfall_{}", rand::random::<u32>()),
            entry_type: KnowledgeEntryType::KnownPitfall,
            title: title.to_string(),
            description: description.to_string(),
            tags: {
                let mut t = vec![
                    "pitfall".to_string(),
                    "warning".to_string(),
                    "anti_pattern".to_string(),
                ];
                t.extend(tags);
                t
            },
            related_entries: Vec::new(),
            confidence: 0.8,
            usefulness: 0,
            created_at: now,
            updated_at: now,
            source: "knowledge_base".to_string(),
            context: context.to_string(),
        };

        self.add_entry(entry)
    }

    /// Heurisztikus szabály hozzáadása
    pub fn add_heuristic_rule(
        &self,
        title: &str,
        description: &str,
        context: &str,
        confidence: f64,
        tags: Vec<String>,
    ) -> String {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let entry = KnowledgeEntry {
            id: format!("rule_{}", rand::random::<u32>()),
            entry_type: KnowledgeEntryType::HeuristicRule,
            title: title.to_string(),
            description: description.to_string(),
            tags: {
                let mut t = vec!["heuristic".to_string(), "rule".to_string()];
                t.extend(tags);
                t
            },
            related_entries: Vec::new(),
            confidence,
            usefulness: 0,
            created_at: now,
            updated_at: now,
            source: "knowledge_base".to_string(),
            context: context.to_string(),
        };

        self.add_entry(entry)
    }

    /// Típus szerinti lekérdezés
    pub fn get_by_type(&self, entry_type: &KnowledgeEntryType) -> Vec<KnowledgeEntry> {
        let type_index = crate::sync_guard::read_lock(&self.type_index);
        let entries = crate::sync_guard::read_lock(&self.entries);

        type_index
            .get(entry_type)
            .map(|ids| {
                ids.iter()
                    .filter_map(|id| entries.get(id))
                    .cloned()
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Tag szerinti lekérdezés
    pub fn get_by_tag(&self, tag: &str) -> Vec<KnowledgeEntry> {
        let tag_index = crate::sync_guard::read_lock(&self.tag_index);
        let entries = crate::sync_guard::read_lock(&self.entries);

        tag_index
            .get(tag)
            .map(|ids| {
                ids.iter()
                    .filter_map(|id| entries.get(id))
                    .cloned()
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Statisztikák lekérése
    pub fn get_stats(&self) -> KnowledgeBaseStats {
        let entries = crate::sync_guard::read_lock(&self.entries);
        let type_index = crate::sync_guard::read_lock(&self.type_index);

        let total = entries.len() as u64;
        let arch_count = type_index
            .get(&KnowledgeEntryType::ArchitecturePattern)
            .map(|v| v.len() as u64)
            .unwrap_or(0);
        let sim_count = type_index
            .get(&KnowledgeEntryType::SimulationResult)
            .map(|v| v.len() as u64)
            .unwrap_or(0);
        let dec_count = type_index
            .get(&KnowledgeEntryType::DecisionPattern)
            .map(|v| v.len() as u64)
            .unwrap_or(0);
        let ins_count = type_index
            .get(&KnowledgeEntryType::Insight)
            .map(|v| v.len() as u64)
            .unwrap_or(0);
        let rule_count = type_index
            .get(&KnowledgeEntryType::HeuristicRule)
            .map(|v| v.len() as u64)
            .unwrap_or(0);
        let prac_count = type_index
            .get(&KnowledgeEntryType::BestPractice)
            .map(|v| v.len() as u64)
            .unwrap_or(0);
        let pit_count = type_index
            .get(&KnowledgeEntryType::KnownPitfall)
            .map(|v| v.len() as u64)
            .unwrap_or(0);

        let avg_conf = if total > 0 {
            entries.values().map(|e| e.confidence).sum::<f64>() / total as f64
        } else {
            0.0
        };

        let total_use = entries.values().map(|e| e.usefulness).sum();

        KnowledgeBaseStats {
            total_entries: total,
            architecture_patterns: arch_count,
            simulation_results: sim_count,
            decision_patterns: dec_count,
            insights: ins_count,
            heuristic_rules: rule_count,
            best_practices: prac_count,
            known_pitfalls: pit_count,
            avg_confidence: avg_conf,
            total_usefulness: total_use,
        }
    }

    /// Tudásbázis exportálása (minden bejegyzés)
    pub fn export_all(&self) -> Vec<KnowledgeEntry> {
        let entries = crate::sync_guard::read_lock(&self.entries);
        entries.values().cloned().collect()
    }

    /// Tudásbázis törlése
    pub fn clear(&self) {
        crate::sync_guard::write_lock(&self.entries).clear();
        crate::sync_guard::write_lock(&self.tag_index).clear();
        crate::sync_guard::write_lock(&self.type_index).clear();
        crate::sync_guard::write_lock(&self.associations).clear();
    }
}

// ─── Automatikus tudásépítés ────────────────────────────────────────────────

/// Automatikusan építi a tudásbázist a szimulációs eredményekből
pub fn auto_build_from_simulations(
    kb: &KnowledgeBase,
    architectures: &[Architecture],
    simulation_results: &HashMap<String, Vec<SimulationMetrics>>,
) {
    for arch in architectures {
        if let Some(metrics_list) = simulation_results.get(&arch.id) {
            for metrics in metrics_list {
                let _entry_id = kb.add_from_simulation(arch, metrics);

                // Bottleneck detektálás -> pitfall
                if !metrics.bottleneck_components.is_empty() {
                    kb.add_pitfall(
                        &format!("Bottleneck in {}: {}", arch.name, metrics.bottleneck_components.join(", ")),
                        &format!("Components {} became bottlenecks at load. Consider scaling or optimizing.",
                            metrics.bottleneck_components.join(", ")),
                        &format!("architecture={}, load_pattern=standard", arch.name),
                        vec![
                            "bottleneck".to_string(),
                            arch.name.clone(),
                            "performance".to_string(),
                        ],
                    );
                }

                // Magas stabilitás -> best practice
                if metrics.stability_score > 0.9 {
                    kb.add_best_practice(
                        &format!("High stability architecture: {}", arch.name),
                        &format!(
                            "Architecture '{}' achieved {:.1}% stability under test conditions.",
                            arch.name,
                            metrics.stability_score * 100.0
                        ),
                        &format!("architecture={}, stability>0.9", arch.name),
                        vec![
                            "stability".to_string(),
                            arch.name.clone(),
                            "reference_architecture".to_string(),
                        ],
                    );
                }
            }
        }
    }
}

/// Automatikusan építi a tudásbázist a döntési mintákból
pub fn auto_build_from_decisions(
    kb: &KnowledgeBase,
    decision_log: &[DecisionLogEntry],
    patterns: &[HeuristicPattern],
) {
    for pattern in patterns {
        // Csak a releváns döntéseket keressük
        let relevant_decisions: Vec<&DecisionLogEntry> = decision_log
            .iter()
            .filter(|d| format!("{:?}", d.decision_type) == pattern.pattern_type)
            .collect();

        if let Some(latest) = relevant_decisions.last() {
            kb.add_from_decision(latest, pattern);
        }

        // Magas sikerrátájú minták -> best practice
        if pattern.success_rate > 0.8 && pattern.usage_count > 3 {
            kb.add_best_practice(
                &format!("Proven decision pattern: {}", pattern.name),
                &format!(
                    "Pattern '{}' has {:.1}% success rate after {} uses.",
                    pattern.name,
                    pattern.success_rate * 100.0,
                    pattern.usage_count
                ),
                &format!("decision_type={}", pattern.pattern_type),
                vec![
                    "decision".to_string(),
                    pattern.pattern_type.clone(),
                    "proven".to_string(),
                ],
            );
        }

        // Alacsony sikerrátájú minták -> pitfall
        if pattern.success_rate < 0.3 && pattern.usage_count > 2 {
            kb.add_pitfall(
                &format!("Unreliable decision pattern: {}", pattern.name),
                &format!(
                    "Pattern '{}' has only {:.1}% success rate. Consider alternative approaches.",
                    pattern.name,
                    pattern.success_rate * 100.0
                ),
                &format!("decision_type={}", pattern.pattern_type),
                vec![
                    "decision".to_string(),
                    pattern.pattern_type.clone(),
                    "unreliable".to_string(),
                ],
            );
        }
    }
}

/// Automatikus asszociáció tanulás a tudásbázisban
pub fn auto_learn_associations(kb: &KnowledgeBase) {
    let entries = kb.export_all();

    for i in 0..entries.len() {
        for j in (i + 1)..entries.len() {
            let a = &entries[i];
            let b = &entries[j];

            // Közös tagek alapján asszociáció
            let common_tags: Vec<&String> = a.tags.iter().filter(|t| b.tags.contains(t)).collect();

            if !common_tags.is_empty() {
                let weight =
                    common_tags.len() as f64 / a.tags.len().clamp(1, b.tags.len().max(1)) as f64;
                if weight > 0.3 {
                    kb.learn_association(&a.id, &b.id, weight);
                    kb.learn_association(&b.id, &a.id, weight);
                }
            }

            // Típus alapján asszociáció (pl. simulation -> pitfall)
            if a.entry_type == KnowledgeEntryType::SimulationResult
                && b.entry_type == KnowledgeEntryType::KnownPitfall
                && a.description.contains(&b.title[..b.title.len().min(20)])
            {
                kb.learn_association(&a.id, &b.id, 0.8);
            }
        }
    }
}

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

    #[test]
    fn test_add_and_search() {
        let kb = KnowledgeBase::new();

        kb.add_best_practice(
            "Use microservices for scalability",
            "Microservices allow independent scaling of components",
            "high_load_systems",
            vec!["microservices".to_string(), "scalability".to_string()],
        );

        kb.add_pitfall(
            "Avoid tight coupling in distributed systems",
            "Tight coupling reduces fault tolerance",
            "distributed_systems",
            vec!["coupling".to_string(), "distributed".to_string()],
        );

        let results = kb.search("microservices", 10);
        assert!(!results.is_empty());
        assert!(results[0].relevance_score > 0.0);
    }

    #[test]
    fn test_get_stats() {
        let kb = KnowledgeBase::new();
        let stats = kb.get_stats();
        assert_eq!(stats.total_entries, 0);

        kb.add_best_practice("Test", "Test description", "test", vec![]);
        let stats = kb.get_stats();
        assert_eq!(stats.total_entries, 1);
        assert_eq!(stats.best_practices, 1);
    }

    #[test]
    fn test_auto_associations() {
        let kb = KnowledgeBase::new();

        let id_a = kb.add_best_practice(
            "Test Practice",
            "A test best practice",
            "test",
            vec!["test".to_string(), "practice".to_string()],
        );

        let id_b = kb.add_pitfall(
            "Test Pitfall",
            "A test pitfall",
            "test",
            vec!["test".to_string(), "pitfall".to_string()],
        );

        auto_learn_associations(&kb);
        kb.learn_association(&id_a, &id_b, 0.5);

        let related = kb.get_related(&id_a, 5);
        assert!(!related.is_empty());
    }
}