#!/usr/bin/env python3
# pulse.py: rewrites ops/NOW.md with what you are doing. Nothing leaves this computer.
import os, subprocess, datetime, re
HOME = os.path.expanduser("~"); OPS = os.path.join(HOME, "ops")
DENY = {"Signal", "Passwords", "1Password", "Keychain Access", "Bitwarden", "Messages", "Photos"}
TITLE_OK = {"Claude", "ChatGPT", "Obsidian", "Google Chrome", "Safari", "Finder", "Pages", "Numbers", "TextEdit", "Notes", "Mail", "WhatsApp", "Zoom", "Code"}
EXCLUDE = ("/Private", "Signal", "/.git", "node_modules", "/Library/", "NOW.md")
def osa(s):
    try: return subprocess.run(["osascript", "-e", s], capture_output=True, text=True, timeout=8).stdout.strip()
    except Exception: return ""
app = osa('tell application "System Events" to get name of first application process whose frontmost is true')
title = ""
if app in DENY: app = "[private app]"
elif app in TITLE_OK:
    title = osa('tell application "System Events" to tell (first application process whose frontmost is true) to get name of front window')[:90]
    if re.search(r"incognito|private", title, re.I): title = "[private window]"
files = []
for d in ("Documents", "Desktop", "Downloads", "ops"):
    r = subprocess.run(["mdfind", "-onlyin", os.path.join(HOME, d), "kMDItemFSContentChangeDate >= $time.now(-900)"], capture_output=True, text=True)
    files += [p for p in r.stdout.splitlines() if os.path.isfile(p) and not any(x in p for x in EXCLUDE)]
files = sorted(set(files), key=os.path.getmtime, reverse=True)[:8]
lines = ["# NOW (auto, %s, pulse.py, read this first)" % datetime.datetime.now().strftime("%a %d %b %H:%M"), "Active: %s%s" % (app or "unknown", ' "%s"' % title if title else "")]
lines.append("Files touched (last 15 min):"); lines += ["  " + p.replace(HOME + "/", "~/") for p in files] or ["  none"]
for f in ("hands.md", "handoff.md"):
    p = os.path.join(OPS, f)
    if os.path.exists(p):
        lines.append("From %s:" % f); lines += ["  " + l.rstrip() for l in open(p, encoding="utf-8") if l.strip() and not l.startswith("#")][:5]
open(os.path.join(OPS, "NOW.md"), "w", encoding="utf-8").write("\n".join(lines[:22]) + "\n")
