File size: 1,495 Bytes
c76423f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
from datetime import datetime
from pathlib import Path
from uuid import uuid4

from core.config import NOTES_PATH


def load_notes(notes_path=NOTES_PATH):
    path = Path(notes_path)
    if not path.exists():
        return []

    content = json.loads(path.read_text(encoding="utf-8"))
    notes = content if isinstance(content, list) else []
    return sorted(notes, key=lambda item: item.get("saved_at", ""), reverse=True)


def save_note(query, answer, citations=None, notes_path=NOTES_PATH):
    notes = load_notes(notes_path)
    note = {
        "note_id": uuid4().hex[:12],
        "query": query,
        "answer": answer,
        "citations": citations or [],
        "saved_at": datetime.now().isoformat(timespec="seconds"),
    }
    notes.insert(0, note)
    Path(notes_path).write_text(
        json.dumps(notes, indent=2, ensure_ascii=True),
        encoding="utf-8",
    )
    return note


def delete_note(note_id, notes_path=NOTES_PATH):
    notes = load_notes(notes_path)
    remaining_notes = [note for note in notes if note.get("note_id") != note_id]
    if len(remaining_notes) == len(notes):
        raise ValueError("Note not found.")

    Path(notes_path).write_text(
        json.dumps(remaining_notes, indent=2, ensure_ascii=True),
        encoding="utf-8",
    )
    return True


def clear_notes(notes_path=NOTES_PATH):
    Path(notes_path).write_text(
        json.dumps([], indent=2, ensure_ascii=True),
        encoding="utf-8",
    )
    return True