#!/usr/bin/env python3
"""Show sticky notes popup for a project desk."""

import json, sys, os, time

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

if len(sys.argv) < 2:
    print("Usage: show-notes.py <project>", file=sys.stderr)
    sys.exit(1)

project = sys.argv[1]
notes_file = os.path.expanduser(f"~/.config/mux/notes/{project}.json")

d = load_json(notes_file)
if not d:
    sys.exit(0)

active = [n for n in d.get("notes", []) if not n.get("archived")]
if not active:
    sys.exit(0)

print()
print("  Notes on this desk:")
print()
for i, n in enumerate(active, 1):
    seen = n.get("sessions_seen", 0)
    age = f" ({seen} session{'s' if seen != 1 else ''} ago)" if seen > 0 else " (new)"
    print(f"  {i}. {n['text']}{age}")
print()
print("  q = close, # = remove note")
print()

# Increment sessions_seen once per tmux pane (not each popup display)
pane_id = os.environ.get("TMUX_PANE", "")
marker_dir = os.path.expanduser("~/.config/mux/notes")
marker_file = os.path.join(marker_dir, f".seen-{project}")

already_seen = False
if pane_id and os.path.exists(marker_file):
    with open(marker_file) as f:
        if f.read().strip() == pane_id:
            already_seen = True

if not already_seen:
    changed = False
    for n in d.get("notes", []):
        if not n.get("archived"):
            n["sessions_seen"] = n.get("sessions_seen", 0) + 1
            if n["sessions_seen"] >= 5:
                n["archived"] = True
                print(f"  Archived: '{n['text']}' (seen 5 times)")
            changed = True

    if changed:
        save_json(notes_file, d)

    # Write the marker so this pane won't increment again
    if pane_id:
        os.makedirs(marker_dir, exist_ok=True)
        with open(marker_file, "w") as f:
            f.write(pane_id)

# Interactive: let user remove a note or just close
try:
    choice = input().strip()
except EOFError:
    sys.exit(0)

if not choice or choice in ("q", "Q"):
    sys.exit(0)

if choice.isdigit():
    idx = int(choice) - 1
    if 0 <= idx < len(active):
        target_id = active[idx]["id"]
        d = load_json(notes_file)
        for n in d["notes"]:
            if n["id"] == target_id:
                n["archived"] = True
        save_json(notes_file, d)
        print(f"  Removed: '{active[idx]['text']}'")
        time.sleep(0.8)
    else:
        print(f"  No note #{choice}.")
        time.sleep(0.8)
