#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10"
# dependencies = []
# ///
"""
inbox.py: the phone-to-Mac inbox for glanceable episodes.

Your phone (an iOS Shortcut in the share sheet) appends one line per link to
iCloud Drive/glanceable/inbox.txt:

  2026-10-06T12:01  https://example.com/post  optional note for Claude

Only the phone writes inbox.txt. The Mac keeps its own state in state.json and
writes status.md, a log of every link and what happened to it, newest first,
readable in the Files app. One writer per file, so iCloud never has to merge.

Commands:
  init                        create the folder and files
  pending                     sync the inbox; print queued items as JSON
  mark ID STATUS [--title T] [--detail D]
                              record progress: processing, published,
                              attention (needs you), skipped, failed
  retry ID                    put an item back in the queue
  show                        print status.md
"""

import argparse
import hashlib
import json
import os
import re
import subprocess
import sys
from datetime import datetime
from pathlib import Path

FOLDER = Path(os.environ.get("GLANCEABLE_INBOX") or
              Path.home() / "Library" / "Mobile Documents" / "com~apple~CloudDocs" / "glanceable")
INBOX, STATE, STATUS = FOLDER / "inbox.txt", FOLDER / "state.json", FOLDER / "status.md"

STATUSES = {
  "queued": "⏳ Queued",
  "processing": "🔄 In progress",
  "attention": "⚠️ Needs you",
  "published": "✅ Published",
  "skipped": "⏭️ Skipped",
  "failed": "❌ Failed",
}
URL = re.compile(r"(https?://\S+|(?:www\.)?(?:youtube\.com|youtu\.be|x\.com|arxiv\.org)/\S+)", re.I)
STAMP = re.compile(r"^\s*(\d{4}-\d{2}-\d{2}[T ]?\d{0,2}:?\d{0,2}(?::\d{2})?)(?:Z|[+-]\d{2}:?\d{2})?\s*")


def now():
  return datetime.now().astimezone().strftime("%Y-%m-%d %H:%M")


def fail(msg):
  print(f"error: {msg}", file=sys.stderr)
  sys.exit(1)


def load():
  return json.loads(STATE.read_text()) if STATE.exists() else {"items": {}}


def save(state):
  STATE.write_text(json.dumps(state, indent=2, ensure_ascii=False) + "\n")
  write_status(state)


def parse(line):
  """(added, url, note) from an inbox line, or None for blanks and comments."""
  line = line.strip()
  if not line or line.startswith("#"):
    return None
  added = None
  stamp = STAMP.match(line)
  if stamp:
    added, line = stamp[1].replace("T", " ")[:16], line[stamp.end():]  # same format as now()
  match = URL.search(line)
  if not match:
    return None
  url = match[1].rstrip(".,)>")
  if not url.lower().startswith("http"):
    url = "https://" + url
  note = (line[:match.start()] + " " + line[match.end():]).strip(" -–—|\t")
  return added, url, note


def sync(state):
  """Fetch the latest inbox from iCloud and add any new lines as queued items."""
  subprocess.run(["brctl", "download", str(FOLDER)], capture_output=True)  # nudge iCloud; harmless if already local
  if not INBOX.exists():
    fail(f"no inbox at {INBOX}; run `inbox.py init`")
  seen = {}
  for raw in INBOX.read_text(encoding="utf-8", errors="replace").splitlines():
    parsed = parse(raw)
    if not parsed:
      continue
    seen[raw.strip()] = seen.get(raw.strip(), 0) + 1  # the same link sent twice is two items
    item_id = hashlib.sha1(f"{raw.strip()}#{seen[raw.strip()]}".encode()).hexdigest()[:8]
    if item_id not in state["items"]:
      added, url, note = parsed
      item = {"url": url, "note": note, "added": added or now(), "status": "queued",
              "title": None, "detail": None, "updated": now()}
      # A link sent again is a duplicate, unless the earlier try is stuck: then it's a retry.
      earlier = [v for v in state["items"].values() if v["url"] == url]
      if any(v["status"] in ("queued", "processing", "published", "skipped") for v in earlier):
        item.update(status="skipped", detail="Sent again; it's already " +
                    next(STATUSES[v["status"]].split(" ", 1)[1].lower() for v in earlier if v["status"] != "skipped"))
      state["items"][item_id] = item
  return state


def write_status(state):
  items = sorted(state["items"].items(), key=lambda kv: kv[1]["added"], reverse=True)
  lines = [f"# Glanceable inbox", "", f"Updated {now()}. Newest first.", ""]
  attention = [(k, v) for k, v in items if v["status"] in ("attention", "failed")]
  if attention:
    lines += ["## Needs you", ""]
    for item_id, v in attention:
      lines.append(f"- {STATUSES[v['status']]}: {v['url']}  \n  {v['detail'] or ''} (id {item_id})")
    lines += ["", "Reply in your Glanceable session in the Claude app, or send the link again with a note.", ""]
  lines += ["## All items", ""]
  for item_id, v in items:
    label = v["title"] or v["url"]
    extra = f" — {v['detail']}" if v["detail"] and v["status"] not in ("attention", "failed") else ""
    note = f" (note: {v['note']})" if v["note"] else ""
    lines.append(f"- {STATUSES[v['status']]} · {v['added']} · {label}{extra}{note}")
  STATUS.write_text("\n".join(lines) + "\n")


def main():
  p = argparse.ArgumentParser(description="The phone-to-Mac inbox for glanceable episodes.")
  sub = p.add_subparsers(dest="command", required=True)
  sub.add_parser("init")
  sub.add_parser("pending")
  mark = sub.add_parser("mark")
  mark.add_argument("id")
  mark.add_argument("status", choices=[s for s in STATUSES if s != "queued"])
  mark.add_argument("--title")
  mark.add_argument("--detail")
  retry = sub.add_parser("retry")
  retry.add_argument("id")
  sub.add_parser("show")
  args = p.parse_args()

  if args.command == "init":
    FOLDER.mkdir(parents=True, exist_ok=True)
    if not INBOX.exists():
      INBOX.write_text("# Glanceable inbox: one link per line, added by the \"Glance this\" Shortcut.\n")
    save(load())
    print(f"Ready: {FOLDER}")
    return

  state = load()
  if args.command == "pending":
    state = sync(state)
    save(state)
    queued = [{"id": k, **{f: v[f] for f in ("url", "note", "added")}}
              for k, v in sorted(state["items"].items(), key=lambda kv: kv[1]["added"]) if v["status"] == "queued"]
    print(json.dumps(queued, indent=2, ensure_ascii=False))
  elif args.command in ("mark", "retry"):
    item = state["items"].get(args.id) or fail(f"no item {args.id}; see status.md")
    if args.command == "retry":
      item.update(status="queued", detail=None)
    else:
      item["status"] = args.status
      if args.title:
        item["title"] = args.title
      if args.detail is not None:
        item["detail"] = args.detail
    item["updated"] = now()
    save(state)
    print(f"{args.id}: {STATUSES[item['status']]}")
  elif args.command == "show":
    write_status(state)
    print(STATUS.read_text())


if __name__ == "__main__":
  main()
