kj 0.1.0

Kōgnitara external REST API
use axum::{
    Json,
    extract::{Path, State},
    http::StatusCode,
};
use axum::{Router, routing::get};
use klm::storage::KpackRecipe;
use klm::{EvidenceRelation, Kognitara};
use serde::Serialize;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::net::SocketAddr;
use std::sync::Arc;

#[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,
}

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

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

    let revision = hypothesis.revision();
    let age_seconds = now.saturating_sub(hypothesis.created_at);

    // Règle simple pour l'instant : 12h minimum
    let min_wait_sec = 12 * 3600;
    let remaining_sec = (min_wait_sec as i64).saturating_sub(age_seconds);
    let can_validate = remaining_sec <= 0
        && !hypothesis
            .evidence
            .iter()
            .any(|e| e.revision == revision && matches!(e.relation, EvidenceRelation::Contradicts));

    // Label simple : premiers mots du statement
    let label = hypothesis
        .statement
        .split_whitespace()
        .take(4)
        .collect::<Vec<_>>()
        .join(" ");

    // Réflexions liées (celles qui mentionnent des concepts ou le statement)
    let reflections: Vec<ReflectionInfo> = mind
        .swarm
        .brains
        .values()
        .flat_map(|brain| &brain.learner.socratic_engine.reflections)
        .filter(|r| {
            r.examined_hypothesis
                .contains(&hypothesis.statement[..hypothesis.statement.len().min(40)])
                || 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, // à brancher sur night review plus tard
            last_examination: None,
            min_wait_hours: 12,
            remaining_sec,
        },
        proposal: ProposalInfo {
            label: label.clone(),
            origin: "HarvestedSeed".into(),
            confidence: 0.65,
            description: hypothesis.statement.clone(),
            tags: vec![],
        },
        changes: Changes {
            add_concept: true,
            add_edges: vec![], // à enrichir plus tard
        },
        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))
}
#[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,
}

pub async fn k_proposals(State(state): State<AppState>) -> Json<Vec<Proposal>> {
    let mind = &state.mind;
    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();

            // Contradiction simple : au moins une evidence "Contradicts"
            let has_contradiction = h.evidence.iter().any(|e| {
                e.revision == revision && matches!(e.relation, klm::EvidenceRelation::Contradicts)
            });

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

    Json(proposals)
}

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

#[derive(Clone)]
pub struct AppState {
    pub mind: Arc<Kognitara>,
}

#[derive(Serialize)]
pub struct StatusResponse {
    pub epoch: u64,
    pub concepts: usize,
    pub hypotheses: usize,
    pub sanctuary: String,
    pub ready_proposals: usize, // à calculer plus tard
}

pub async fn k_status(State(state): State<AppState>) -> Json<StatusResponse> {
    let mind = &state.mind;

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

    let hypotheses = mind.hypotheses.hypotheses.len();

    // Pour l'instant on met 0, on calculera les "ready" plus tard
    let ready_proposals = 0;

    Json(StatusResponse {
        epoch: mind.swarm.global_epoch,
        concepts,
        hypotheses,
        sanctuary: mind.sanctuary.sanctuary_name.clone(),
        ready_proposals,
    })
}
#[tokio::main]
async fn main() {
    let data_path = std::path::Path::new("/mnt/kognitara/data"); // ou via env

    let mind = load_kognitara(data_path).expect("Failed to load Kognitara");

    let state = AppState {
        mind: Arc::new(mind),
    };

    let app = Router::new()
        .route("/status", get(k_status))
        .route("/proposals", get(k_proposals))
        .route("/diff/{id}", get(k_diff))
        .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();
}