use std::cell::RefCell;
use std::path::Path;
use chrono::{DateTime, Utc};
use second_brain_core::session_dates::SessionEvidence;
use crate::claude_code::{Transcript, read_transcript};
use crate::claude_memory::is_note;
#[derive(Default)]
pub struct TranscriptEvidence {
last: RefCell<Option<(String, Option<Transcript>)>>,
}
impl TranscriptEvidence {
fn with_transcript<T>(
&self,
path: &str,
read: impl FnOnce(&Transcript) -> Option<T>,
) -> Option<T> {
let mut last = self.last.borrow_mut();
if last.as_ref().is_none_or(|(cached, _)| cached != path) {
let parsed = std::fs::read_to_string(path)
.ok()
.map(|content| read_transcript(&content));
*last = Some((path.to_string(), parsed));
}
last.as_ref()
.and_then(|(_, transcript)| transcript.as_ref())
.and_then(read)
}
}
impl SessionEvidence for TranscriptEvidence {
fn line_time(&self, transcript: &str, text: &str) -> Option<DateTime<Utc>> {
let first_paragraph = text.split("\n\n").next().unwrap_or("").trim();
if first_paragraph.is_empty() {
return None;
}
self.with_transcript(transcript, |t| {
t.assistant_texts
.iter()
.find(|block| block.text.contains(first_paragraph))
.and_then(|block| block.at)
})
}
fn first_time(&self, transcript: &str) -> Option<DateTime<Utc>> {
self.with_transcript(transcript, |t| t.first_timestamp)
}
fn note_modified_at(&self, path: &str) -> Option<DateTime<Utc>> {
let path = Path::new(path);
if is_note(path) {
modified_at(path)
} else {
None
}
}
}
pub(crate) fn modified_at(path: &Path) -> Option<DateTime<Utc>> {
std::fs::metadata(path)
.and_then(|meta| meta.modified())
.ok()
.map(DateTime::<Utc>::from)
}