kj 0.1.2

Kōgnitara external REST API
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
use axum::http::Method;
use axum::http::header;
use axum::http::header::{AUTHORIZATION, CONTENT_TYPE};
use axum::response::IntoResponse;
use axum::routing::post;
use axum::{
    Json,
    extract::{Path, State},
    http::StatusCode,
};
use axum::{Router, routing::get};
use klm::storage::KpackRecipe;
use klm::{EvidenceRelation, Kognitara};
use kog::{KogBook, KogBridge, KogLesson, MarginConfig, PrintProfile};
use serde::Serialize;
use std::fs::{self, File};
use std::io::{BufRead, BufReader};
use std::net::SocketAddr;
use std::path::Path as StdPath;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::SystemTime;
use tokio::sync::RwLock;
use tower_http::cors::{Any, CorsLayer};

#[derive(Serialize)]
pub struct TreeNode {
    pub id: String,
    pub brain: u8,
    pub label: String,
    pub description: String,
    pub origin: String,
    pub confidence: f32,
    pub plasticity: f32,
    pub affective_valence: f32,
    pub tags: Vec<String>,
}

#[derive(Serialize)]
pub struct TreeLink {
    pub source: String,
    pub target: String,
    pub relation: String,
    pub weight: f32,
}

#[derive(Serialize)]
pub struct DiffResponse {
    pub id: u64,
    pub can_validate: bool,
    pub time: TimeInfo,
    pub proposal: ProposalInfo,
    pub changes: Changes,
    pub impact: Impact,
    pub reflections: Vec<ReflectionInfo>,
}

#[derive(Serialize)]
pub struct TimeInfo {
    pub created_at: i64,
    pub age_seconds: i64,
    pub examinations: u64, // à brancher plus tard sur night_review
    pub last_examination: Option<i64>,
    pub min_wait_hours: u64,
    pub remaining_sec: i64,
}

#[derive(Serialize)]
pub struct ProposalInfo {
    pub label: String,
    pub origin: String,
    pub confidence: f32,
    pub description: String,
    pub tags: Vec<String>,
}

#[derive(Serialize)]
pub struct Changes {
    pub add_concept: bool,
    pub add_edges: Vec<EdgeChange>,
}

#[derive(Serialize)]
pub struct EdgeChange {
    pub from: String,
    pub relation: String,
    pub to: String,
}

#[derive(Serialize)]
pub struct Impact {
    pub neighbor_concepts: usize,
    pub potential_contradictions: usize,
}

#[derive(Serialize)]
pub struct ReflectionInfo {
    pub stage: String,
    pub question: String,
    pub created_at: i64,
}

#[derive(Serialize)]
pub struct Proposal {
    pub id: u64,
    pub statement: String,
    pub revision: usize,
    pub created_at: i64,
    pub evidence_count: usize,
    pub has_contradiction: bool,
    pub current_timestamp: i64,
}

#[derive(Serialize)]
pub struct NightReviewResponse {
    pub total_reviews: usize,
    pub items: Vec<serde_json::Value>,
}

#[derive(Serialize)]
pub struct EquivalenceItem {
    pub brain: u8,
    pub id: u64,
    pub left_id: String,
    pub left_label: String,
    pub right_id: String,
    pub right_label: String,
    pub source: String,
    pub reason: String,
    pub active: bool,
    pub created_at: i64,
}
#[derive(Deserialize)]
struct ResearchTrace {
    #[serde(default)]
    pub title: String,
    #[serde(default)]
    pub source_url: String,
    #[serde(default)]
    pub snippet: String,
}

#[derive(Deserialize)]
struct ResearchObservation {
    #[serde(default)]
    pub topic: String,
    pub trace: ResearchTrace,
}

#[derive(Serialize)]
pub struct ResearchItem {
    pub id: String,
    pub topic: String,
    pub title: String,
    pub domain: String,
    pub source_url: String,
    pub snippet: String,
    pub imported: bool,
    pub timestamp: i64,
}

#[derive(Deserialize, Default)]
struct ResearchQueueInfo {
    #[serde(default)]
    pub pending: Vec<serde_json::Value>,
    #[serde(default)]
    pub visited: Vec<String>,
    #[serde(default)]
    pub next_topic: usize,
}

#[derive(Serialize)]
pub struct ResearchResponse {
    pub pending_count: usize,
    pub visited_count: usize,
    pub next_topic_index: usize,
    pub items: Vec<ResearchItem>,
}

#[derive(Serialize)]
pub struct TreeConceptDto {
    pub id: String,
    pub label: String,
    pub description: String,
    pub confidence: f32,
    pub brain: u8,
}

#[derive(Serialize)]
pub struct TreeEdgeDto {
    pub from: String,
    pub to: String,
    pub relation: String,
    pub weight: f32,
}

#[derive(Serialize)]
pub struct TreeResponse {
    pub concepts: Vec<TreeConceptDto>,
    pub edges: Vec<TreeEdgeDto>,
}

pub async fn k_tree(State(state): State<AppState>) -> Result<Json<TreeResponse>, StatusCode> {
    let mind = state.mind().await?;
    let mut concepts = Vec::new();
    let mut edges = Vec::new();

    for (coord, brain) in &mind.swarm.brains {
        for (cid, concept) in &brain.tree.concepts {
            concepts.push(TreeConceptDto {
                id: cid.0.clone(),
                label: concept.label.clone(),
                description: concept.description.clone(),
                confidence: concept.confidence,
                brain: coord.0,
            });
        }
        for edge in &brain.tree.edges {
            edges.push(TreeEdgeDto {
                from: edge.source.0.clone(),
                to: edge.target.0.clone(),
                relation: format!("{:?}", edge.relation_type),
                weight: edge.weight,
            });
        }
    }

    Ok(Json(TreeResponse { concepts, edges }))
}

#[derive(Serialize)]
pub struct BridgeDto {
    pub target: String,
    pub note: String,
}

#[derive(Serialize)]
pub struct LessonDto {
    pub file_name: String,
    pub slug: String,
    pub title: String,
    pub family: String,
    pub level: String,
    pub roots: Vec<String>,
    pub essence: String,
    pub example: String,
    pub bridges: Vec<BridgeDto>,
    pub question: String,
}

#[derive(Serialize)]
pub struct BookDto {
    pub file_name: String,
    pub slug: String,
    pub title: String,
    pub subtitle: String,
    pub family: String,
    pub commission: String,
    pub chapters: Vec<String>,
}

#[derive(Serialize, Deserialize, Clone)]
pub struct PrintProfileDto {
    pub file_name: String,
    pub name: String,
    pub paper: String,
    pub font_family: String,
    pub font_size_pt: f32,
    pub line_leading_em: f32,
    pub lang: String,
    pub justify: bool,
    pub accent_hex: String,
    pub inside_mm: f32,
    pub outside_mm: f32,
    pub top_mm: f32,
    pub bottom_mm: f32,
}

impl PrintProfileDto {
    fn from_model(file_name: String, p: &PrintProfile) -> Self {
        Self {
            file_name,
            name: p.name.clone(),
            paper: p.paper.clone(),
            font_family: p.font_family.clone(),
            font_size_pt: p.font_size_pt,
            line_leading_em: p.line_leading_em,
            lang: p.lang.clone(),
            justify: p.justify,
            accent_hex: p.accent_hex.clone(),
            inside_mm: p.margins.inside_mm,
            outside_mm: p.margins.outside_mm,
            top_mm: p.margins.top_mm,
            bottom_mm: p.margins.bottom_mm,
        }
    }

    fn to_model(&self) -> PrintProfile {
        PrintProfile {
            name: self.name.clone(),
            paper: self.paper.clone(),
            font_family: self.font_family.clone(),
            font_size_pt: self.font_size_pt,
            line_leading_em: self.line_leading_em,
            lang: self.lang.clone(),
            justify: self.justify,
            accent_hex: self.accent_hex.clone(),
            margins: MarginConfig {
                inside_mm: self.inside_mm,
                outside_mm: self.outside_mm,
                top_mm: self.top_mm,
                bottom_mm: self.bottom_mm,
            },
        }
    }
}

#[derive(Serialize)]
pub struct StudioPayload {
    pub lessons: Vec<LessonDto>,
    pub books: Vec<BookDto>,
    pub styles: Vec<PrintProfileDto>,
}

fn lessons_dir_from_state(state: &AppState) -> std::path::PathBuf {
    state
        .data_path
        .parent()
        .unwrap_or_else(|| StdPath::new("/mnt/kognitara"))
        .join("lessons")
}

pub async fn k_studio(State(state): State<AppState>) -> Json<StudioPayload> {
    let dir = lessons_dir_from_state(&state);
    let mut lessons = Vec::new();
    let mut books = Vec::new();
    let mut styles = Vec::new();

    if let Ok(entries) = fs::read_dir(&dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            let Some(file_name) = path
                .file_name()
                .and_then(|s| s.to_str())
                .map(str::to_string)
            else {
                continue;
            };
            let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("");
            let Ok(raw) = fs::read_to_string(&path) else {
                continue;
            };

            match ext {
                "kog" => {
                    if let Ok(l) = KogLesson::from_kog(&raw) {
                        lessons.push(LessonDto {
                            file_name,
                            slug: l.slug,
                            title: l.title,
                            family: l.family,
                            level: l.level,
                            roots: l.roots,
                            essence: l.essence,
                            example: l.example,
                            bridges: l
                                .bridges
                                .into_iter()
                                .map(|b: KogBridge| BridgeDto {
                                    target: b.target,
                                    note: b.note,
                                })
                                .collect(),
                            question: l.question,
                        });
                    }
                }
                "kogbook" => {
                    if let Ok(b) = KogBook::from_kogbook(&raw) {
                        books.push(BookDto {
                            file_name,
                            slug: b.slug,
                            title: b.title,
                            subtitle: b.subtitle,
                            family: b.family,
                            commission: b.commission,
                            chapters: b.chapters,
                        });
                    }
                }
                "kogstyle" => {
                    let p = PrintProfile::from_kogstyle(&raw);
                    styles.push(PrintProfileDto::from_model(file_name, &p));
                }
                _ => {}
            }
        }
    }

    if styles.is_empty() {
        styles.push(PrintProfileDto::from_model(
            "default.kogstyle".to_string(),
            &PrintProfile::default(),
        ));
    }

    lessons.sort_by(|a, b| a.title.cmp(&b.title));
    books.sort_by(|a, b| a.title.cmp(&b.title));

    Json(StudioPayload {
        lessons,
        books,
        styles,
    })
}

pub async fn k_save_style(
    State(state): State<AppState>,
    Json(dto): Json<PrintProfileDto>,
) -> Result<Json<PrintProfileDto>, StatusCode> {
    let dir = lessons_dir_from_state(&state);
    fs::create_dir_all(&dir).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    let safe_slug: String = dto
        .name
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() {
                c.to_ascii_lowercase()
            } else {
                '-'
            }
        })
        .collect::<String>()
        .trim_matches('-')
        .to_string();
    let file_name = if safe_slug.is_empty() {
        "custom.kogstyle".to_string()
    } else {
        format!("{safe_slug}.kogstyle")
    };

    let model = dto.to_model();
    fs::write(dir.join(&file_name), model.to_kogstyle())
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    Ok(Json(PrintProfileDto::from_model(file_name, &model)))
}

#[derive(Deserialize)]
pub struct CompilePdfRequest {
    pub target_file: String, // ex: "contrepoint.kog" ou "lharmonie-contrepoint-bach.kogbook"
    pub profile: PrintProfileDto,
}

pub async fn k_compile_pdf(
    State(state): State<AppState>,
    Json(req): Json<CompilePdfRequest>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    let dir = lessons_dir_from_state(&state);
    let safe_name = StdPath::new(&req.target_file)
        .file_name()
        .and_then(|s| s.to_str())
        .ok_or((StatusCode::BAD_REQUEST, "Invalid file name".into()))?;
    let target_path = dir.join(safe_name);

    let raw = fs::read_to_string(&target_path)
        .map_err(|e| (StatusCode::NOT_FOUND, format!("File not found: {e}")))?;

    let profile = req.profile.to_model();
    let typ_source = if safe_name.ends_with(".kogbook") {
        let book =
            KogBook::from_kogbook(&raw).map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
        let mut chapters = Vec::new();
        for ch in &book.chapters {
            if let Ok(ch_raw) = fs::read_to_string(dir.join(ch))
                && let Ok(lesson) = KogLesson::from_kog(&ch_raw)
            {
                chapters.push(lesson);
            }
        }
        book.to_typst_book(&chapters, &profile)
    } else {
        let lesson =
            KogLesson::from_kog(&raw).map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
        lesson.to_typst_document(&profile)
    };

    let stamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis())
        .unwrap_or(0);
    let tmp_typ = std::env::temp_dir().join(format!("kog_{stamp}.typ"));
    let tmp_pdf = std::env::temp_dir().join(format!("kog_{stamp}.pdf"));

    fs::write(&tmp_typ, &typ_source)
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    let status = std::process::Command::new("typst")
        .arg("compile")
        .arg(&tmp_typ)
        .arg(&tmp_pdf)
        .status()
        .map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("Typst error: {e}"),
            )
        })?;

    let _ = fs::remove_file(&tmp_typ);

    if !status.success() {
        return Err((
            StatusCode::INTERNAL_SERVER_ERROR,
            "Typst compilation failed".into(),
        ));
    }

    let pdf_bytes =
        fs::read(&tmp_pdf).map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
    let _ = fs::remove_file(&tmp_pdf);

    let out_name = safe_name
        .trim_end_matches(".kogbook")
        .trim_end_matches(".kog");

    Ok((
        [
            (header::CONTENT_TYPE, "application/pdf".to_string()),
            (
                header::CONTENT_DISPOSITION,
                format!("attachment; filename=\"{out_name}.pdf\""),
            ),
        ],
        pdf_bytes,
    ))
}

pub async fn k_research(
    State(state): State<AppState>,
) -> Result<Json<ResearchResponse>, StatusCode> {
    let mind = state.mind().await?;
    let dir = state
        .data_path
        .parent()
        .unwrap_or_else(|| StdPath::new("/mnt/kognitara"))
        .join("research");

    // 1. Lecture des compteurs de la file d'attente (queue.state)
    let queue_info: ResearchQueueInfo = fs::read(dir.join("queue.state"))
        .ok()
        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
        .unwrap_or_default();

    // 2. Lecture des observations récoltées (*.json)
    let mut items = Vec::new();
    if let Ok(entries) = fs::read_dir(&dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().and_then(|s| s.to_str()) != Some("json") {
                continue;
            }
            let Some(id) = path
                .file_name()
                .and_then(|s| s.to_str())
                .map(str::to_string)
            else {
                continue;
            };
            let timestamp = entry
                .metadata()
                .ok()
                .and_then(|m| m.modified().ok())
                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                .map(|d| d.as_secs() as i64)
                .unwrap_or(0);

            if let Ok(raw) = fs::read(&path)
                && let Ok(obs) = serde_json::from_slice::<ResearchObservation>(&raw)
            {
                let domain = obs
                    .trace
                    .source_url
                    .strip_prefix("https://")
                    .and_then(|s| s.split('/').next())
                    .unwrap_or("fr.wikipedia.org")
                    .to_string();

                items.push(ResearchItem {
                    imported: mind.imported_research.contains(&id),
                    id,
                    topic: obs.topic,
                    title: obs.trace.title,
                    domain,
                    source_url: obs.trace.source_url,
                    snippet: obs.trace.snippet,
                    timestamp,
                });
            }
        }
    }

    items.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));

    Ok(Json(ResearchResponse {
        pending_count: queue_info.pending.len(),
        visited_count: queue_info.visited.len(),
        next_topic_index: queue_info.next_topic,
        items,
    }))
}

pub async fn k_equivalences(
    State(state): State<AppState>,
) -> Result<Json<Vec<EquivalenceItem>>, StatusCode> {
    let mind = state.mind().await?;
    let mut items = Vec::new();

    for (coord, brain) in &mind.swarm.brains {
        for eq in &brain.tree.possible_equivalences {
            items.push(EquivalenceItem {
                brain: coord.0,
                id: eq.id,
                left_id: eq.left.0.clone(),
                left_label: eq.left_label.clone(),
                right_id: eq.right.0.clone(),
                right_label: eq.right_label.clone(),
                source: eq.source.clone(),
                reason: eq.reason.clone(),
                active: eq.is_active(),
                created_at: eq.created_at,
            });
        }
    }

    items.sort_by_key(|a| std::cmp::Reverse(a.created_at));
    Ok(Json(items))
}
use serde::Deserialize;
use serde_json::json;
use std::collections::BTreeMap;

#[derive(Serialize, Deserialize, Clone)]
pub struct WikipediaReview {
    pub source: String,
    pub excerpt: String,
    pub examined_at: i64,
}

#[derive(Serialize, Deserialize, Clone)]
pub struct HypothesisReview {
    pub id: u64,
    pub revision: usize,
    pub statement: String,
    pub examinations: u64,
    pub examined_at: i64,
    pub reports: usize,
    pub supports: usize,
    pub contradicts: usize,
    pub contradictions: Vec<String>,
    pub questions: Vec<String>,
    pub wikipedia: Option<WikipediaReview>,
}

#[derive(Serialize, Deserialize, Clone)]
pub struct ConceptReview {
    pub brain: u8,
    pub label: String,
    pub contradictions: Vec<String>,
    pub question: String,
}

#[derive(Serialize, Deserialize, Clone)]
pub struct NightSubject {
    pub label: String,
    pub kind: String,
    pub contradictions: Vec<String>,
}

#[derive(Default, Serialize, Deserialize, Clone)]
pub struct NightSummary {
    pub cycles: u64,
    pub concept_examinations: u64,
    pub hypothesis_examinations: u64,
    pub last_run: i64,
    pub subjects: BTreeMap<String, NightSubject>,
}

#[derive(Default, Deserialize)]
struct ReviewState {
    #[serde(default)]
    pub concept_examinations: u64,
    #[serde(default)]
    pub hypothesis_examinations: u64,
    #[serde(default)]
    pub last_run: Option<i64>,
    #[serde(default)]
    pub concepts: Vec<ConceptReview>,
    #[serde(default)]
    pub hypotheses: BTreeMap<String, HypothesisReview>,
    #[serde(default)]
    pub summaries: BTreeMap<String, NightSummary>,
}

#[derive(Serialize)]
#[serde(tag = "kind", content = "value")]
enum NightItem<'a> {
    Hypothesis(&'a HypothesisReview),
    Concept(&'a ConceptReview),
}

pub async fn k_night(State(state): State<AppState>) -> Result<Json<serde_json::Value>, StatusCode> {
    let night = read_night_review_state(&state.data_path)?;
    let mut items = Vec::new();

    if let Some(ref review_state) = night {
        let mut reviews: Vec<_> = review_state.hypotheses.values().collect();
        reviews.sort_by(|a, b| b.examined_at.cmp(&a.examined_at));
        for review in reviews {
            items.push(NightItem::Hypothesis(review));
        }
        for concept in &review_state.concepts {
            items.push(NightItem::Concept(concept));
        }
    }

    Ok(Json(json!({
        "concept_examinations": night.as_ref().map_or(0, |n| n.concept_examinations),
        "hypothesis_examinations": night.as_ref().map_or(0, |n| n.hypothesis_examinations),
        "last_run": night.as_ref().and_then(|n| n.last_run),
        "items": items
    })))
}

fn read_night_review_state(data_path: &StdPath) -> Result<Option<ReviewState>, StatusCode> {
    let dir = data_path
        .parent()
        .unwrap_or_else(|| StdPath::new("/mnt/kognitara"));

    let candidates = [
        dir.join("research").join("night-review.state"),
        dir.join("night-review.state"),
    ];

    for path in candidates {
        match fs::read(&path) {
            Ok(data) => {
                return serde_json::from_slice::<ReviewState>(&data)
                    .map(Some)
                    .map_err(|_| StatusCode::SERVICE_UNAVAILABLE);
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
            Err(_) => return Err(StatusCode::SERVICE_UNAVAILABLE),
        }
    }

    Ok(None)
}

pub async fn k_morning(
    State(state): State<AppState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    let night = read_night_review_state(&state.data_path)?;
    let latest = night.as_ref().and_then(|s| s.summaries.last_key_value());

    if let Some((date, summary)) = latest {
        let subjects: Vec<_> = summary.subjects.values().collect();
        let flagged_count = summary
            .subjects
            .values()
            .filter(|s| !s.contradictions.is_empty())
            .count();

        Ok(Json(json!({
            "summary": {
                "date": date,
                "cycles": summary.cycles,
                "concept_examinations": summary.concept_examinations,
                "hypothesis_examinations": summary.hypothesis_examinations,
                "last_run": summary.last_run,
                "subjects_count": summary.subjects.len(),
                "flagged_count": flagged_count,
            },
            "subjects": subjects
        })))
    } else {
        Ok(Json(json!({
            "summary": null,
            "subjects": []
        })))
    }
}

pub async fn k_status(State(state): State<AppState>) -> Result<Json<StatusResponse>, StatusCode> {
    let mind = state.mind().await?;
    let now = klm::current_timestamp();

    let concepts: usize = mind
        .swarm
        .brains
        .values()
        .map(|brain| brain.tree.concepts.len())
        .sum();

    let hypotheses = mind.hypotheses.hypotheses.len();
    let ready_proposals = mind
        .hypotheses
        .hypotheses
        .iter()
        .filter(|h| is_hypothesis_ready(h, now))
        .count();

    let usb_mounted = StdPath::new("/mnt/cubefs-usb").exists()
        && state.data_path.parent().is_some_and(|p| p.exists());
    let backup_ok = check_cubefs_backup_ok(StdPath::new("/mnt/cubefs-usb"));

    // Vérification USB & sauvegarde
    let next_research_ts = get_systemd_next_elapse("klm-research.timer");
    let next_backup_ts = get_systemd_next_elapse("klm-backup.timer");

    // Vérification espace disque via statvfs (Linux)
    let disk_full = check_disk_full(&state.data_path);

    Ok(Json(StatusResponse {
        epoch: mind.swarm.global_epoch,
        concepts,
        hypotheses,
        sanctuary: mind.sanctuary.sanctuary_name.clone(),
        ready_proposals,
        breaths: mind.swarm.cosmic_clock.total_breaths,
        tides: mind.swarm.cosmic_clock.total_tides,
        season: mind.swarm.cosmic_clock.season.label().to_string(),
        conjunctions: mind.swarm.cosmic_clock.conjunctions_experienced,
        usb_mounted,
        backup_ok,
        disk_full,
        next_research_ts,
        next_backup_ts,
    }))
}

fn check_cubefs_backup_ok(backup_dir: &StdPath) -> bool {
    let Ok(entries) = fs::read_dir(backup_dir) else {
        return false;
    };
    entries
        .filter_map(Result::ok)
        .filter_map(|e| e.metadata().ok()?.modified().ok())
        .filter_map(|m| m.elapsed().ok())
        .any(|age| age.as_secs() < 6 * 3600)
}

fn check_disk_full(path: &StdPath) -> bool {
    use std::ffi::CString;
    use std::os::unix::ffi::OsStrExt;
    let target = if path.exists() {
        path
    } else {
        path.parent().unwrap_or(StdPath::new("/"))
    };
    let Ok(c_path) = CString::new(target.as_os_str().as_bytes()) else {
        return false;
    };
    unsafe {
        let mut stat: libc::statvfs = std::mem::zeroed();
        if libc::statvfs(c_path.as_ptr(), &mut stat) == 0 {
            let free_bytes = stat.f_bavail as u64 * stat.f_frsize as u64;
            return free_bytes < 100 * 1024 * 1024; // Moins de 100 Mo libres
        }
    }
    false
}

pub async fn k_proposals(State(state): State<AppState>) -> Result<Json<Vec<Proposal>>, StatusCode> {
    let mind = state.mind().await?;
    let current_timestamp = klm::current_timestamp();

    let proposals: Vec<Proposal> = mind
        .hypotheses
        .hypotheses
        .iter()
        .map(|h| {
            let revision = h.revision();
            let evidence_count = h.evidence.iter().filter(|e| e.revision == revision).count();
            let has_contradiction = h.evidence.iter().any(|e| {
                e.revision == revision && matches!(e.relation, EvidenceRelation::Contradicts)
            });

            Proposal {
                id: h.id,
                statement: h.statement.clone(),
                revision,
                created_at: h.created_at,
                evidence_count,
                has_contradiction,
                current_timestamp,
            }
        })
        .collect();

    Ok(Json(proposals))
}

pub async fn k_diff(
    State(state): State<AppState>,
    Path(id): Path<u64>,
) -> Result<Json<DiffResponse>, StatusCode> {
    let mind = state.mind().await?;
    let now = klm::current_timestamp();

    let hypothesis = mind
        .hypotheses
        .hypotheses
        .iter()
        .find(|h| h.id == id)
        .ok_or(StatusCode::NOT_FOUND)?;

    let age_seconds = now.saturating_sub(hypothesis.created_at);
    let min_wait_sec = 12 * 3600;
    let remaining_sec = (min_wait_sec as i64).saturating_sub(age_seconds);
    let can_validate = is_hypothesis_ready(hypothesis, now);

    let label = hypothesis
        .statement
        .split_whitespace()
        .take(4)
        .collect::<Vec<_>>()
        .join(" ");

    let reflections: Vec<ReflectionInfo> = mind
        .swarm
        .brains
        .values()
        .flat_map(|brain| &brain.learner.socratic_engine.reflections)
        .filter(|r| {
            let prefix: String = hypothesis.statement.chars().take(40).collect();
            r.examined_hypothesis.contains(&prefix)
                || hypothesis
                    .related_concepts
                    .iter()
                    .any(|cid| r.concepts.contains(cid))
        })
        .map(|r| ReflectionInfo {
            stage: format!("{:?}", r.stage),
            question: r.maieutic_question.clone(),
            created_at: r.created_at,
        })
        .collect();

    let response = DiffResponse {
        id,
        can_validate,
        time: TimeInfo {
            created_at: hypothesis.created_at,
            age_seconds,
            examinations: 0,
            last_examination: None,
            min_wait_hours: 12,
            remaining_sec,
        },
        proposal: ProposalInfo {
            label,
            origin: "HarvestedSeed".into(),
            confidence: 0.65,
            description: hypothesis.statement.clone(),
            tags: vec![],
        },
        changes: Changes {
            add_concept: true,
            add_edges: vec![],
        },
        impact: Impact {
            neighbor_concepts: hypothesis.related_concepts.len(),
            potential_contradictions: if hypothesis
                .evidence
                .iter()
                .any(|e| matches!(e.relation, EvidenceRelation::Contradicts))
            {
                1
            } else {
                0
            },
        },
        reflections,
    };

    Ok(Json(response))
}

pub fn load_kognitara(path: &std::path::Path) -> Result<Kognitara, String> {
    let file = File::open(path).map_err(|e| format!("Cannot open registry: {e}"))?;
    let reader = BufReader::new(file);

    let mut last_valid_recipe: Option<KpackRecipe> = None;
    let mut lines_count = 0usize;

    for line in reader.lines().map_while(Result::ok) {
        if let Ok(recipe) = serde_json::from_str::<KpackRecipe>(&line) {
            last_valid_recipe = Some(recipe);
            lines_count += 1;
        }
    }

    let recipe = last_valid_recipe.ok_or("No valid Kpack recipe found in the registry")?;

    let json_bytes = recipe
        .decode()
        .map_err(|e| format!("Kpack decompression failed: {e}"))?;

    let mind: Kognitara = serde_json::from_slice(&json_bytes)
        .map_err(|e| format!("Failed to reconstruct Kognitara: {e}"))?;

    println!(
        "Loaded from iteration {} — Sanctuary: {} — Epoch: {}",
        lines_count, mind.sanctuary.sanctuary_name, mind.swarm.global_epoch
    );

    Ok(mind)
}
pub struct SnapshotCache {
    mind: Arc<Kognitara>,
    modified: Option<SystemTime>,
}

#[derive(Clone)]
pub struct AppState {
    pub data_path: Arc<PathBuf>,
    pub cache: Arc<RwLock<SnapshotCache>>,
}

impl AppState {
    async fn mind(&self) -> Result<Arc<Kognitara>, StatusCode> {
        let current_mtime = fs::metadata(&*self.data_path)
            .and_then(|m| m.modified())
            .ok();

        {
            let guard = self.cache.read().await;
            if guard.modified == current_mtime {
                return Ok(guard.mind.clone());
            }
        }

        let mut guard = self.cache.write().await;
        if guard.modified != current_mtime
            && let Ok(new_mind) = load_kognitara(&self.data_path)
        {
            guard.mind = Arc::new(new_mind);
            guard.modified = current_mtime;
        }
        Ok(guard.mind.clone())
    }
}

fn is_hypothesis_ready(h: &klm::Hypothesis, now: i64) -> bool {
    let revision = h.revision();
    let age_seconds = now.saturating_sub(h.created_at);
    let has_contradiction = h
        .evidence
        .iter()
        .any(|e| e.revision == revision && matches!(e.relation, EvidenceRelation::Contradicts));
    age_seconds >= 12 * 3600 && !has_contradiction
}
fn get_systemd_next_elapse(unit: &str) -> Option<i64> {
    let output = std::process::Command::new("systemctl")
        .args(["--user", "list-timers", unit, "--no-pager", "--no-legend"])
        .output()
        .ok()?;

    let line = String::from_utf8_lossy(&output.stdout).trim().to_string();
    // Format list-timers : "Sun 2026-11-29 20:08:12 CET  4h 44min left ..."
    let parts: Vec<&str> = line.split_whitespace().collect();
    if parts.len() < 4 {
        return None;
    }
    let date_str = format!(
        "{} {} {}",
        parts.get(0).expect(""),
        parts.get(1).expect(""),
        parts.get(2).expect("")
    );

    let ts_out = std::process::Command::new("date")
        .args(["-d", &date_str, "+%s"])
        .output()
        .ok()?;

    String::from_utf8_lossy(&ts_out.stdout)
        .trim()
        .parse::<i64>()
        .ok()
}

#[derive(Serialize)]
pub struct StatusResponse {
    pub epoch: u64,
    pub concepts: usize,
    pub hypotheses: usize,
    pub sanctuary: String,
    pub ready_proposals: usize, // à calculer plus tard
    // Temps cosmique de Kōgnitara (src/clock.rs)
    pub breaths: u64,
    pub tides: u64,
    pub season: String,
    pub conjunctions: u64,
    // Santé matérielle & sauvegarde (pour la couleur du cercle)
    pub usb_mounted: bool,
    pub backup_ok: bool,
    pub disk_full: bool,
    // Timers systemd (timestamps UNIX en secondes)
    pub next_research_ts: Option<i64>,
    pub next_backup_ts: Option<i64>,
}
#[derive(Serialize)]
pub struct BrainInfo {
    pub id: u8,
    pub phase: String,
    pub concepts_count: usize,
    pub edges_count: usize,
    pub cognitive_tension: f32,
}

pub async fn k_brains(State(state): State<AppState>) -> Result<Json<Vec<BrainInfo>>, StatusCode> {
    let mind = state.mind().await?;
    let brains = mind
        .swarm
        .brains
        .iter()
        .map(|(coord, brain)| BrainInfo {
            id: coord.0,
            phase: format!("{:?}", brain.phase),
            concepts_count: brain.tree.concepts.len(),
            edges_count: brain.tree.edges.len(),
            cognitive_tension: brain.state.cognitive_tension,
        })
        .collect();
    Ok(Json(brains))
}

#[derive(Serialize)]
pub struct ReflectionEntry {
    pub brain: u8,
    pub stage: String,
    pub examined_hypothesis: String,
    pub maieutic_question: String,
    pub interior_monologue: String,
    pub created_at: i64,
}

pub async fn k_reflections(
    State(state): State<AppState>,
) -> Result<Json<Vec<ReflectionEntry>>, StatusCode> {
    let mind = state.mind().await?;
    let mut entries: Vec<ReflectionEntry> = mind
        .swarm
        .brains
        .iter()
        .flat_map(|(coord, brain)| {
            brain
                .learner
                .socratic_engine
                .reflections
                .iter()
                .map(move |r| ReflectionEntry {
                    brain: coord.0,
                    stage: format!("{:?}", r.stage),
                    examined_hypothesis: r.examined_hypothesis.clone(),
                    maieutic_question: r.maieutic_question.clone(),
                    interior_monologue: r.interior_monologue.clone(),
                    created_at: r.created_at,
                })
        })
        .collect();
    entries.sort_by_key(|a| std::cmp::Reverse(a.created_at));
    Ok(Json(entries))
}

#[derive(Serialize)]
pub struct FamilyMemberInfo {
    pub id: String,
    pub name: String,
    pub role: String,
    pub trust_level: f32,
    pub affective_affinity: f32,
    pub interaction_count: u64,
    pub last_interacted_at: i64,
    pub anecdotes: Vec<String>,
}

#[derive(Serialize)]
pub struct FamilyResponse {
    pub sanctuary_name: String,
    pub members: Vec<FamilyMemberInfo>,
}

pub async fn k_family(State(state): State<AppState>) -> Result<Json<FamilyResponse>, StatusCode> {
    let mind = state.mind().await?;
    let members = mind
        .sanctuary
        .members
        .values()
        .map(|m| {
            let anecdotes = mind
                .sanctuary
                .bonds
                .get(&m.id)
                .map(|b| b.shared_anecdotes.clone())
                .unwrap_or_default();

            FamilyMemberInfo {
                id: m.id.0.clone(),
                name: m.name.clone(),
                role: format!("{:?}", m.role),
                trust_level: m.trust_level,
                affective_affinity: m.affective_affinity,
                interaction_count: m.interaction_count,
                last_interacted_at: m.last_interacted_at,
                anecdotes,
            }
        })
        .collect();

    Ok(Json(FamilyResponse {
        sanctuary_name: mind.sanctuary.sanctuary_name.clone(),
        members,
    }))
}

#[tokio::main]
async fn main() {
    let cors = CorsLayer::new()
        .allow_origin(Any)
        .allow_methods([Method::GET, Method::POST])
        .allow_headers([CONTENT_TYPE, AUTHORIZATION]);

    let data_path = std::env::var("KOGNITARA_DATA")
        .map(PathBuf::from)
        .unwrap_or_else(|_| PathBuf::from("/mnt/kognitara/data"));

    let modified = fs::metadata(&data_path).and_then(|m| m.modified()).ok();
    let mind = load_kognitara(&data_path).expect("Failed to load Kognitara");

    let state = AppState {
        data_path: Arc::new(data_path),
        cache: Arc::new(RwLock::new(SnapshotCache {
            mind: Arc::new(mind),
            modified,
        })),
    };

    let app = Router::new()
        .route("/studio", get(k_studio))
        .route("/studio/styles", post(k_save_style))
        .route("/studio/pdf", post(k_compile_pdf))
        .route("/research", get(k_research))
        .route("/equivalences", get(k_equivalences))
        .route("/night", get(k_night))
        .route("/morning", get(k_morning))
        .route("/status", get(k_status))
        .route("/brains", get(k_brains))
        .route("/proposals", get(k_proposals))
        .route("/diff/{id}", get(k_diff))
        .route("/tree", get(k_tree))
        .route("/reflections", get(k_reflections))
        .route("/family", get(k_family))
        .layer(cors)
        .with_state(state);

    let addr = SocketAddr::from(([0, 0, 0, 0], 7789));
    println!("listening on http://{}", addr);

    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
    axum::serve(listener, app).await.unwrap();
}