#+TITLE: Flight Plan: Note Metadata Sovereignty
#+DATE: 2026-04-07
#+FILETAGS: :plan:metadata:integrity:psf:

* Phase D: Build (Implementation)

** 1. Extract Dates Script
#+begin_src bash :tangle extract-git-dates.sh
#!/bin/bash
NOTES_DIR="notes"
for f in $NOTES_DIR/*.org; do
    CREATED=$(git log --diff-filter=A --format=%aI -- "$f" | tail -1)
    EDITED=$(git log -1 --format=%aI -- "$f")
    # If not in git, use file mtime
    [ -z "$CREATED" ] && CREATED=$(date -Iseconds -r "$f")
    [ -z "$EDITED" ] && EDITED=$(date -Iseconds -r "$f")
    echo "$f|$CREATED|$EDITED"
done
#+end_src

** 2. Inject Properties Script (Elisp)
#+begin_src elisp :tangle inject-metadata.el
(require 'org)

(defun opencortex-inject-metadata (file created edited)
  (with-current-buffer (find-file-noselect file)
    (org-with-wide-buffer
     (goto-char (point-min))
     (let ((props (org-get-property-block)))
       (unless props
         (org-id-get-create) ; Ensure drawer exists
         (setq props (org-get-property-block))))
     
     (org-set-property "CREATED" (opencortex-format-iso created))
     (org-set-property "EDITED" (opencortex-format-iso edited))
     (save-buffer)
     (kill-buffer))))

(defun opencortex-format-iso (iso-date)
  "Convert 2026-04-07T10:00:00+00:00 to [2026-04-07 Tue 10:00]"
  (let ((time (parse-time-string iso-date)))
    (format-time-string "[%Y-%m-%d %a %H:%M]" (apply #'encode-time time))))

;; Batch execution logic
(let ((lines (with-temp-buffer
               (insert-file-contents "system/git-dates.txt")
               (split-string (buffer-string) "\n" t))))
  (dolist (line lines)
    (let ((parts (split-string line "|")))
      (when (= (length parts) 3)
        (opencortex-inject-metadata (nth 0 parts) (nth 1 parts) (nth 2 parts))))))
#+end_src
