#!/usr/bin/env python3
"""CLI for managing sticky notes — add, list, rm."""

import sys, os

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from muxlib import load_json, save_json, now_iso, D, R

notes_dir = os.path.expanduser("~/.config/mux/notes")
os.makedirs(notes_dir, exist_ok=True)

action = sys.argv[1]  # add, list, rm
project = sys.argv[2]
notes_file = os.path.join(notes_dir, f"{project}.json")


def load():
    d = load_json(notes_file)
    if not d:
        return {"notes": []}
    return d


def active(d):
    return [n for n in d.get("notes", []) if not n.get("archived")]


if action == "add":
    text = " ".join(sys.argv[3:])
    d = load()
    if len(active(d)) >= 3:
        print(f"You already have 3 notes on {project}. Remove one first, or this might belong in a plan instead.")
        sys.exit(1)
    d["notes"].append({
        "id": f"note-{len(d['notes']) + 1}",
        "text": text,
        "created_at": now_iso(),
        "sessions_seen": 0,
        "archived": False
    })
    save_json(notes_file, d)
    print(f'Note added to {project}: "{text}"')

elif action == "list":
    d = load()
    notes = active(d)
    if not notes:
        print("No notes on this desk.")
    else:
        for i, n in enumerate(notes, 1):
            seen = n.get("sessions_seen", 0)
            age = f" ({seen} session{'s' if seen != 1 else ''} ago)" if seen > 0 else " (new)"
            dim = D if seen >= 2 else ""
            reset = R
            print(f"{dim}  {i}. {n['text']}{age}{reset}")

elif action == "rm":
    if len(sys.argv) < 4 or not sys.argv[3].isdigit():
        print("Usage: manage-notes.py rm <project> <number>", file=sys.stderr)
        sys.exit(1)
    num = int(sys.argv[3])
    d = load()
    act = active(d)
    idx = num - 1
    if idx < 0 or idx >= len(act):
        print(f"No note #{num}.")
        sys.exit(1)
    target_id = act[idx]["id"]
    for n in d["notes"]:
        if n["id"] == target_id:
            n["archived"] = True
    save_json(notes_file, d)
    print("Note removed.")
