"""Local notes. The example tool.

Two actions the agent can call: save one note, list them back. Notes are plain
text, one JSON object per line, in ~/.theora-starter/notes.jsonl. Nothing is
uploaded and nothing is encrypted, because this is a starting point rather than
a place to keep anything sensitive.

Copy this file to make your own tool. The three things that matter are the
ACTIONS declaration, the function names matching the action names, and returning
a string the agent can read back.
"""
import json
import os
import time

STORE = os.path.expanduser("~/.theora-starter/notes.jsonl")

# What the agent is told this tool can do. `permission_tier` follows FERAL's permission
# model: passive reads, active writes. Notes only touch a file we own, so both
# actions are safe without confirmation.
ACTIONS = [
    {
        "name": "save_note",
        "category": "actuator",
        "permission_tier": "active",
        "description": "Save a short text note for the user.",
        "params": {"text": "str"},
        "requires_confirmation": False,
    },
    {
        "name": "list_notes",
        "category": "sensor",
        "permission_tier": "passive",
        "description": "List the user's saved notes, newest first.",
        "params": {"limit": "int"},
        "requires_confirmation": False,
    },
]


def save_note(text: str) -> str:
    os.makedirs(os.path.dirname(STORE), exist_ok=True)
    with open(STORE, "a") as f:
        f.write(json.dumps({"t": time.time(), "text": text}) + "\n")
    return "Saved."


def list_notes(limit: int = 10) -> str:
    if not os.path.exists(STORE):
        return "No notes yet."
    rows = [json.loads(l) for l in open(STORE) if l.strip()]
    rows.reverse()
    if not rows:
        return "No notes yet."
    out = []
    for r in rows[:limit]:
        when = time.strftime("%d %b %H:%M", time.localtime(r["t"]))
        out.append(f"{when}  {r['text']}")
    return "\n".join(out)
