~kris/dots

srice

ref: 3bdfd3e0c26b75a939850355c30bee6fa9cc9abd srice/.local/bin/tome -rwxr-xr-x 35.4 KiB
3bdfd3e0 — Kris Yotam sync: lock down plan9 theme, wallpapers, nvim configs 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
#!/usr/bin/env bash
set -euo pipefail

###############################################################################
# TOME -- Content manager for krisyotam.com
#
# Maintainer:   Kris Yotam <krisyotam@pm.me>
# License:      MIT
# Created:      2026-05-18
# Description:  Unified content creator, editor, and metadata manager.
#               Three actions (create, edit, data) with two interfaces
#               (nnn/fzf TUI or dmenu).
#
# Usage:
#   tome -nnn -create      Create new content entry (TUI)
#   tome -dmenu -create    Create new content entry (dmenu)
#   tome -nnn -edit        Browse content, open in write (TUI)
#   tome -dmenu -edit      Browse content, open in write (dmenu)
#   tome -nnn -data        Edit content metadata (TUI)
#   tome -dmenu -data      Edit content metadata (dmenu)
###############################################################################

###############################################################################
# config
###############################################################################

DB="$HOME/dev/krisyotam.com/data/content.db"
CONTENT_DIR="$HOME/.corpus/content"
TIL_DIR="$HOME/.corpus/til"

# Menu entries (order matters -- displayed as-is)
# Indented entries are news publications
MENU_ENTRIES=(
    "papers"
    "essays"
    "blog"
    "diary"
    "reviews"
    "verse"
    "news"
    "  the-soapbox"
    "  field-notes"
    "  off-the-record"
    "til"
    "fiction"
    "ocs"
    "prayers"
    "progymnasmata"
)

# Types that are actual content directories
ALL_TYPES=(papers essays blog diary reviews verse news til fiction ocs prayers progymnasmata)

# News publications
NEWS_PUBS=("the-soapbox" "field-notes" "off-the-record")

# Diary has no status/confidence/importance columns
DIARY_FIELDS=(title preview category_slug state)
STANDARD_FIELDS=(title preview category_slug status confidence importance state)

VALID_STATUSES=("Notes" "Draft" "In Progress" "Finished" "Abandoned")
VALID_CONFIDENCES=(
    "certain" "highly likely" "likely" "possible"
    "unlikely" "highly unlikely" "remote" "impossible"
)
VALID_STATES=("active" "hidden")

# nerd font icon map
declare -A TYPE_ICONS=(
    [papers]="󰈙"    [essays]="󰬝"   [blog]="󰬞"
    [diary]="󰃮"     [reviews]="󰓥"  [verse]="󱗝"
    [news]="󰎕"      [fiction]="󰂺"  [ocs]="󰏫"
    [prayers]="󰥍"   [progymnasmata]="󰑴"  [til]="󰛄"
    [the-soapbox]="󰎕" [field-notes]="󰎕" [off-the-record]="󰎕"
)

###############################################################################
# helpers
###############################################################################

have_cmd() { command -v "$1" >/dev/null 2>&1; }
die()      { echo "ERROR: $1" >&2; exit 1; }
sql()      { sqlite3 "$DB" "$1"; }
notify()   { notify-send "tome" "$1" 2>/dev/null || true; }

slugify() {
    echo "$1" |
        tr '[:upper:]' '[:lower:]' |
        sed 's/[^a-z0-9 -]//g' |
        sed 's/  */ /g; s/ /-/g; s/--*/-/g; s/^-//; s/-$//'
}

check_slug_globally() {
    local slug="$1"
    for dir in "$CONTENT_DIR"/*/; do
        [ -d "$dir" ] || continue
        if [ -f "$dir/${slug}.mdx" ]; then
            echo "$(basename "$dir"):${slug}.mdx"
            return
        fi
    done
    # Also check til
    for subdir in "$TIL_DIR"/*/; do
        [ -d "$subdir" ] || continue
        if [ -f "$subdir/${slug}.mdx" ]; then
            echo "til/$(basename "$subdir"):${slug}.mdx"
            return
        fi
    done
}

# Get content directory for a type (or news publication)
content_dir_for() {
    local selection="$1"
    case "$selection" in
        the-soapbox|field-notes|off-the-record)
            echo "$CONTENT_DIR/news"
            ;;
        til)
            echo "$TIL_DIR"
            ;;
        *)
            echo "$CONTENT_DIR/$selection"
            ;;
    esac
}

# Resolve a menu selection to its content type (for DB operations)
db_type_for() {
    local selection="$1"
    case "$selection" in
        the-soapbox|field-notes|off-the-record) echo "news" ;;
        *) echo "$selection" ;;
    esac
}

today() { date +%Y-%m-%d; }

###############################################################################
# argument parsing
###############################################################################

UI_MODE=""
ACTION_MODE=""

for arg in "$@"; do
    case "$arg" in
        -nnn)    UI_MODE="nnn" ;;
        -dmenu)  UI_MODE="dmenu" ;;
        -create) ACTION_MODE="create" ;;
        -edit)   ACTION_MODE="edit" ;;
        -data)   ACTION_MODE="data" ;;
        *)
            echo "Unknown flag: $arg" >&2
            echo "Usage: tome -nnn|-dmenu -create|-edit|-data" >&2
            exit 1
            ;;
    esac
done

if [[ -z "$UI_MODE" || -z "$ACTION_MODE" ]]; then
    echo "Usage: tome -nnn|-dmenu -create|-edit|-data" >&2
    exit 1
fi

###############################################################################
# dependency checks
###############################################################################

check_deps_nnn() {
    have_cmd fzf     || die "fzf not found"
    have_cmd nnn     || die "nnn not found"
}

check_deps_dmenu() {
    have_cmd dmenu   || die "dmenu not found"
}

check_deps_data() {
    have_cmd sqlite3 || die "sqlite3 not found"
    [[ -f "$DB" ]]   || die "content.db not found at $DB"
}

###############################################################################
# menu rendering
###############################################################################

# Build the fzf menu string
fzf_menu() {
    for entry in "${MENU_ENTRIES[@]}"; do
        echo "$entry"
    done
    echo "quit"
}

# Build the dmenu menu string (with icons)
dmenu_menu() {
    for entry in "${MENU_ENTRIES[@]}"; do
        local trimmed="${entry## }"
        local indent="${entry%%[! ]*}"
        local icon="${TYPE_ICONS[$trimmed]:-󰈙}"
        echo "${indent}${icon}  ${trimmed}"
    done
}

# Parse a menu selection back to a clean type/publication name
parse_selection() {
    echo "$1" | sed 's/^[[:space:]]*//' | sed 's/^[^ ]* *//'
}

###############################################################################
# banners
###############################################################################

print_banner_main() {
    local cols
    cols="$(tput cols 2>/dev/null || echo 80)"

    if have_cmd figlet; then
        figlet -w "$cols" -f big "KRISYOTAM.COM" 2>/dev/null \
            || figlet -w "$cols" "KRISYOTAM.COM"
    else
        echo "KRISYOTAM.COM"
    fi

    echo
    echo "  est. 2025"
    echo "  author: Kris Yotam"
    echo "  script: tome"
    echo
    echo "  \"Do I contradict myself? Very well then I contradict myself,"
    echo "   (I am large, I contain multitudes.)\""
    echo "  -- Walt Whitman"
    echo
}

print_banner_data() {
    local cols
    cols="$(tput cols 2>/dev/null || echo 80)"

    if have_cmd figlet; then
        figlet -w "$cols" -f big "DATA" 2>/dev/null \
            || figlet -w "$cols" "DATA"
    else
        echo "=== DATA ==="
    fi

    echo
    echo "  Content metadata editor for krisyotam.com"
    echo
}

###############################################################################
# create: write frontmatter + .mdx file (pure shell)
###############################################################################

# Collect metadata and write the .mdx file
write_new_entry() {
    local selection="$1"
    local type
    type="$(db_type_for "$selection")"
    local target_dir
    target_dir="$(content_dir_for "$selection")"

    mkdir -p "$target_dir"

    # For news publications browsing into subdirectory is not needed
    # since all news lives flat in content/news/

    local title slug preview category status confidence importance
    local verse_type="" prayer_type="" form="" publication=""

    # Title
    if [[ "$UI_MODE" == "dmenu" ]]; then
        title="$(echo "" | dmenu -p "title:")"
    else
        read -rp "  Title: " title
    fi
    [[ -z "$title" ]] && return

    # Slug
    slug="$(slugify "$title")"
    local collision
    collision="$(check_slug_globally "$slug")"
    if [[ -n "$collision" ]]; then
        if [[ "$UI_MODE" == "dmenu" ]]; then
            notify "Slug collision: $slug ($collision)"
            slug="$(echo "$slug" | dmenu -p "collision! alt slug:")"
        else
            echo "  Slug collision: $slug ($collision)"
            read -rp "  Alt slug: " slug
        fi
        [[ -z "$slug" ]] && return
        slug="$(slugify "$slug")"
        collision="$(check_slug_globally "$slug")"
        if [[ -n "$collision" ]]; then
            if [[ "$UI_MODE" == "dmenu" ]]; then
                notify "Still colliding: $slug. Aborting."
            else
                echo "  Still colliding: $slug. Aborting."
            fi
            return
        fi
    fi

    # Preview
    if [[ "$UI_MODE" == "dmenu" ]]; then
        preview="$(echo "" | dmenu -p "preview:")"
    else
        read -rp "  Preview: " preview
    fi

    # Category
    check_deps_data
    if [[ "$UI_MODE" == "dmenu" ]]; then
        category="$(sql "SELECT slug FROM categories ORDER BY slug" | dmenu -i -l 20 -p "category:")"
    else
        category="$(sql "SELECT slug FROM categories ORDER BY slug" | fzf --prompt="category> " --height=20 --reverse)" || category=""
    fi
    [[ -z "$category" ]] && return

    # Status (skip for diary)
    if [[ "$type" == "diary" ]]; then
        status="" confidence="" importance=""
    else
        if [[ "$UI_MODE" == "dmenu" ]]; then
            status="$(printf "%s\n" "${VALID_STATUSES[@]}" | dmenu -i -l 5 -p "status:")"
            confidence="$(printf "%s\n" "${VALID_CONFIDENCES[@]}" | dmenu -i -l 8 -p "confidence:")"
            importance="$(seq 1 10 | dmenu -i -l 10 -p "importance:")"
        else
            status="$(printf "%s\n" "${VALID_STATUSES[@]}" | fzf --prompt="status> " --height=8 --reverse)" || status="Draft"
            confidence="$(printf "%s\n" "${VALID_CONFIDENCES[@]}" | fzf --prompt="confidence> " --height=10 --reverse)" || confidence="possible"
            read -rp "  Importance (1-10): " importance
        fi
        [[ -z "$status" ]] && status="Draft"
        [[ -z "$confidence" ]] && confidence="possible"
        [[ -z "$importance" ]] && importance="5"
    fi

    # Type-specific fields
    case "$type" in
        verse)
            if [[ "$UI_MODE" == "dmenu" ]]; then
                verse_type="$(printf 'haiku\nsonnet\nfree-verse\node\nlimerick\nvillanelle\nother' | dmenu -i -l 7 -p "verse type:")"
            else
                verse_type="$(printf 'haiku\nsonnet\nfree-verse\node\nlimerick\nvillanelle\nother' | fzf --prompt="verse type> " --height=10 --reverse)" || verse_type=""
            fi
            ;;
        prayers)
            if [[ "$UI_MODE" == "dmenu" ]]; then
                prayer_type="$(echo "" | dmenu -p "prayer type:")"
                form="$(echo "" | dmenu -p "form:")"
            else
                read -rp "  Prayer type: " prayer_type
                read -rp "  Form: " form
            fi
            ;;
        news)
            # Publication is determined by the menu selection
            case "$selection" in
                the-soapbox|field-notes|off-the-record)
                    publication="$selection"
                    ;;
                news)
                    # Selected the parent "news" -- ask which publication
                    if [[ "$UI_MODE" == "dmenu" ]]; then
                        publication="$(printf '%s\n' "${NEWS_PUBS[@]}" | dmenu -i -l 3 -p "publication:")"
                    else
                        publication="$(printf '%s\n' "${NEWS_PUBS[@]}" | fzf --prompt="publication> " --height=5 --reverse)" || publication="the-soapbox"
                    fi
                    [[ -z "$publication" ]] && publication="the-soapbox"
                    ;;
            esac
            ;;
    esac

    # Tags
    local tags=""
    if [[ "$UI_MODE" == "dmenu" ]]; then
        # Collect up to 5 tags
        local tag_list=()
        for _ in 1 2 3 4 5; do
            local tag
            tag="$(sql "SELECT slug FROM tags ORDER BY slug" | dmenu -i -l 20 -p "tag (empty=done):")" || break
            [[ -z "$tag" ]] && break
            tag_list+=("$tag")
        done
        tags="$(printf '%s\n' "${tag_list[@]}" 2>/dev/null | paste -sd',' -)"
    else
        echo "  Tags (comma-separated, or empty):"
        read -rp "  > " tags
    fi

    # Build the .mdx file
    local target_file="$target_dir/${slug}.mdx"
    local date
    date="$(today)"

    {
        echo "---"
        echo "title: \"$title\""
        echo "slug: $slug"
        echo "type: $type"
        echo "category: $category"
        echo "start_date: '$date'"
        echo "end_date: ''"
        echo "state: active"
        [[ -n "$preview" ]] && echo "preview: \"$preview\""

        if [[ "$type" != "diary" ]]; then
            echo "status: $status"
            echo "confidence: $confidence"
            echo "importance: $importance"
        fi

        # Type-specific fields
        [[ -n "$verse_type" ]] && echo "verse_type: $verse_type"
        [[ -n "$prayer_type" ]] && echo "prayer_type: $prayer_type"
        [[ -n "$form" ]] && echo "form: $form"
        [[ -n "$publication" ]] && echo "publication: $publication"

        # Tags as inline YAML array
        if [[ -n "$tags" ]]; then
            local tag_arr
            tag_arr="$(echo "$tags" | tr ',' '\n' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | awk '{printf "%s\"%s\"", (NR>1 ? ", " : ""), $0}')"
            echo "tags: [$tag_arr]"
        else
            echo "tags: []"
        fi

        echo "---"
        echo ""
    } > "$target_file"

    if [[ "$UI_MODE" == "dmenu" ]]; then
        notify "Created: $title ($slug)"
        # Open in write
        write "$target_file" &
        disown
    else
        echo
        echo "  Created: $target_file"
        echo
        read -rp "  Open in write? [Y/n] " yn
        case "$yn" in
            n|N) ;;
            *) write "$target_file" ;;
        esac
    fi
}

###############################################################################
# mode: -nnn -create
###############################################################################

run_nnn_create() {
    check_deps_nnn

    clear
    print_banner_main

    local selection
    selection="$(fzf_menu | fzf --prompt="create> " --height=20 --reverse)" || exit 0

    [[ "$selection" == "quit" ]] && exit 0

    # Trim whitespace (for indented news publications)
    selection="${selection## }"

    # If they selected "news" (parent), let them pick publication or create generic
    write_new_entry "$selection"
}

###############################################################################
# mode: -dmenu -create
###############################################################################

run_dmenu_create() {
    check_deps_dmenu

    local raw
    raw="$(dmenu_menu | dmenu -i -l 16 -p "create:")"
    [[ -z "$raw" ]] && exit 0

    local selection
    selection="$(parse_selection "$raw")"
    [[ -z "$selection" ]] && exit 0

    write_new_entry "$selection"
}

###############################################################################
# mode: -nnn -edit  (browse and open existing content in write)
###############################################################################

run_nnn_edit() {
    check_deps_nnn

    local nnn_write_helper="$HOME/.local/bin/nnn-write"
    [[ ! -x "$nnn_write_helper" ]] && die "nnn-write helper not found at $nnn_write_helper"

    clear
    print_banner_main

    while true; do
        local selection
        selection="$(fzf_menu | fzf --prompt="edit> " --height=20 --reverse)" || exit 0

        [[ "$selection" == "quit" ]] && exit 0

        selection="${selection## }"
        local target_dir
        target_dir="$(content_dir_for "$selection")"

        if [[ ! -d "$target_dir" ]]; then
            echo "Directory not found: $target_dir"
            read -rp "Press Enter..." _
            continue
        fi

        # For news publications, filter to only show matching files
        case "$selection" in
            the-soapbox|field-notes|off-the-record)
                # Show only files matching this publication
                local tmpdir
                tmpdir="$(mktemp -d)"
                # Symlink matching files into tmpdir for nnn browsing
                for f in "$target_dir"/*.mdx; do
                    [[ -f "$f" ]] || continue
                    if grep -q "^publication: $selection" "$f" 2>/dev/null; then
                        ln -s "$f" "$tmpdir/$(basename "$f")"
                    fi
                done
                NNN_OPENER="$nnn_write_helper" \
                NNN_FALLBACK_OPENER="${NNN_OPENER:-xdg-open}" \
                    nnn "$tmpdir"
                rm -rf "$tmpdir"
                ;;
            til)
                # TIL has subdirectories
                NNN_OPENER="$nnn_write_helper" \
                NNN_FALLBACK_OPENER="${NNN_OPENER:-xdg-open}" \
                    nnn "$target_dir"
                ;;
            *)
                NNN_OPENER="$nnn_write_helper" \
                NNN_FALLBACK_OPENER="${NNN_OPENER:-xdg-open}" \
                    nnn "$target_dir"
                ;;
        esac

        clear
        print_banner_main
    done
}

###############################################################################
# mode: -dmenu -edit
###############################################################################

run_dmenu_edit() {
    check_deps_dmenu

    local raw
    raw="$(dmenu_menu | dmenu -i -l 16 -p "edit:")"
    [[ -z "$raw" ]] && exit 0

    local selection
    selection="$(parse_selection "$raw")"
    [[ -z "$selection" ]] && exit 0

    local target_dir
    target_dir="$(content_dir_for "$selection")"
    [[ ! -d "$target_dir" ]] && { notify "Directory not found: $target_dir"; exit 1; }

    local file

    case "$selection" in
        the-soapbox|field-notes|off-the-record)
            # Filter news files by publication
            file="$(
                for f in "$target_dir"/*.mdx; do
                    [[ -f "$f" ]] || continue
                    if grep -q "^publication: $selection" "$f" 2>/dev/null; then
                        basename "$f" .mdx
                    fi
                done | sort | dmenu -i -l 20 -p "$selection:"
            )"
            [[ -z "$file" ]] && exit 0
            write "$target_dir/$file.mdx"
            ;;
        til)
            # TIL has subdirs -- first pick subdir, then file
            local subdir
            subdir="$(ls "$target_dir" | dmenu -i -l 10 -p "til topic:")"
            [[ -z "$subdir" ]] && exit 0
            file="$(ls "$target_dir/$subdir"/*.mdx 2>/dev/null | xargs -I{} basename {} .mdx | sort | dmenu -i -l 20 -p "$subdir:")"
            [[ -z "$file" ]] && exit 0
            write "$target_dir/$subdir/$file.mdx"
            ;;
        *)
            file="$(
                ls "$target_dir"/*.mdx 2>/dev/null |
                    xargs -I{} basename {} .mdx |
                    sort |
                    dmenu -i -l 20 -p "$selection:"
            )"
            [[ -z "$file" ]] && exit 0
            write "$target_dir/$file.mdx"
            ;;
    esac
}

###############################################################################
# metadata display (for -data mode)
###############################################################################

show_metadata() {
    local type="$1" slug="$2"

    local title preview category state tags id

    title="$(sql "SELECT title FROM $type WHERE slug='$slug'")"
    preview="$(sql "SELECT preview FROM $type WHERE slug='$slug'")"
    category="$(sql "SELECT category_slug FROM $type WHERE slug='$slug'")"
    state="$(sql "SELECT state FROM $type WHERE slug='$slug'")"

    id="$(sql "SELECT id FROM $type WHERE slug='$slug'")"
    tags="$(sql "SELECT t.slug FROM tags t JOIN content_tags ct ON ct.tag_id = t.id WHERE ct.content_type = '$type' AND ct.content_id = $id ORDER BY t.slug" | paste -sd', ' -)"

    echo
    echo "  ┌─ $slug ─────────────────────────────────"
    printf "  │ %-14s %s\n" "Title:" "$title"
    printf "  │ %-14s %s\n" "Preview:" "${preview:0:60}"
    printf "  │ %-14s %s\n" "Category:" "$category"
    printf "  │ %-14s %s\n" "Tags:" "$tags"

    if [[ "$type" != "diary" ]]; then
        local status confidence importance
        status="$(sql "SELECT status FROM $type WHERE slug='$slug'")"
        confidence="$(sql "SELECT confidence FROM $type WHERE slug='$slug'")"
        importance="$(sql "SELECT importance FROM $type WHERE slug='$slug'")"
        printf "  │ %-14s %s\n" "Status:" "$status"
        printf "  │ %-14s %s\n" "Confidence:" "$confidence"
        printf "  │ %-14s %s\n" "Importance:" "$importance"
    fi

    if [[ "$type" == "news" ]]; then
        local pub
        pub="$(sql "SELECT publication FROM $type WHERE slug='$slug'")"
        printf "  │ %-14s %s\n" "Publication:" "$pub"
    fi

    printf "  │ %-14s %s\n" "State:" "$state"
    echo "  └──────────────────────────────────────────"
    echo
}

###############################################################################
# field editing -- nnn/fzf mode (for -data)
###############################################################################

edit_tags_nnn() {
    local type="$1" slug="$2"

    local id
    id="$(sql "SELECT id FROM $type WHERE slug='$slug'")"

    echo
    echo "  Current tags:"
    sql "SELECT t.slug FROM tags t JOIN content_tags ct ON ct.tag_id = t.id WHERE ct.content_type = '$type' AND ct.content_id = $id ORDER BY t.slug" | while read -r tag; do
        echo "    - $tag"
    done

    echo
    echo "  Actions: [a]dd tag, [r]emove tag, [d]one"
    while true; do
        read -rp "  tag> " action
        case "$action" in
            a|add)
                local new_tag
                new_tag="$(
                    sql "SELECT slug FROM tags ORDER BY slug" |
                    fzf --prompt="add tag> " --height=20 --reverse
                )" || continue

                local existing
                existing="$(sql "SELECT COUNT(*) FROM content_tags WHERE content_type='$type' AND content_id=$id AND tag_id=(SELECT id FROM tags WHERE slug='$new_tag')")"
                if [[ "$existing" -gt 0 ]]; then
                    echo "  Tag '$new_tag' already linked."
                    continue
                fi

                local tag_id
                tag_id="$(sql "SELECT id FROM tags WHERE slug='$new_tag'")"
                sql "INSERT INTO content_tags (content_type, content_id, tag_id) VALUES ('$type', $id, $tag_id)"
                echo "  Added tag: $new_tag"
                ;;
            r|remove)
                local rm_tag
                rm_tag="$(
                    sql "SELECT t.slug FROM tags t JOIN content_tags ct ON ct.tag_id = t.id WHERE ct.content_type = '$type' AND ct.content_id = $id ORDER BY t.slug" |
                    fzf --prompt="remove tag> " --height=10 --reverse
                )" || continue

                sql "DELETE FROM content_tags WHERE content_type='$type' AND content_id=$id AND tag_id=(SELECT id FROM tags WHERE slug='$rm_tag')"
                echo "  Removed tag: $rm_tag"
                ;;
            d|done|q|quit)
                break
                ;;
            *)
                echo "  Unknown action. Use [a]dd, [r]emove, or [d]one."
                ;;
        esac
    done
}

edit_field_nnn() {
    local type="$1" slug="$2" field="$3"
    local new_value=""

    case "$field" in
        title|preview)
            local current
            current="$(sql "SELECT $field FROM $type WHERE slug='$slug'")"
            echo "  Current $field: $current"
            read -rp "  New $field: " new_value
            [[ -z "$new_value" ]] && return
            new_value="${new_value//\'/\'\'}"
            sql "UPDATE $type SET $field='$new_value', updated_at=datetime('now') WHERE slug='$slug'"
            echo "  Updated $field."
            ;;
        category_slug)
            new_value="$(
                sql "SELECT slug FROM categories ORDER BY slug" |
                fzf --prompt="category> " --height=20 --reverse
            )" || return
            sql "UPDATE $type SET category_slug='$new_value', updated_at=datetime('now') WHERE slug='$slug'"
            echo "  Updated category to: $new_value"
            ;;
        tags)
            edit_tags_nnn "$type" "$slug"
            ;;
        status)
            new_value="$(
                printf "%s\n" "${VALID_STATUSES[@]}" |
                fzf --prompt="status> " --height=10 --reverse
            )" || return
            sql "UPDATE $type SET status='$new_value', updated_at=datetime('now') WHERE slug='$slug'"
            echo "  Updated status to: $new_value"
            ;;
        confidence)
            new_value="$(
                printf "%s\n" "${VALID_CONFIDENCES[@]}" |
                fzf --prompt="confidence> " --height=12 --reverse
            )" || return
            sql "UPDATE $type SET confidence='$new_value', updated_at=datetime('now') WHERE slug='$slug'"
            echo "  Updated confidence to: $new_value"
            ;;
        importance)
            read -rp "  Importance (1-10): " new_value
            if [[ "$new_value" =~ ^[0-9]+$ ]] && (( new_value >= 1 && new_value <= 10 )); then
                sql "UPDATE $type SET importance=$new_value, updated_at=datetime('now') WHERE slug='$slug'"
                echo "  Updated importance to: $new_value"
            else
                echo "  Invalid. Must be 1-10."
            fi
            ;;
        publication)
            new_value="$(
                printf "%s\n" "${NEWS_PUBS[@]}" |
                fzf --prompt="publication> " --height=5 --reverse
            )" || return
            sql "UPDATE $type SET publication='$new_value', updated_at=datetime('now') WHERE slug='$slug'"
            echo "  Updated publication to: $new_value"
            ;;
        state)
            new_value="$(
                printf "%s\n" "${VALID_STATES[@]}" |
                fzf --prompt="state> " --height=5 --reverse
            )" || return
            sql "UPDATE $type SET state='$new_value', updated_at=datetime('now') WHERE slug='$slug'"
            echo "  Updated state to: $new_value"
            ;;
        *)
            echo "  Unknown field: $field"
            ;;
    esac
}

###############################################################################
# field editing -- dmenu mode (for -data)
###############################################################################

edit_field_dmenu() {
    local type="$1" slug="$2" field="$3"
    local current new_value

    case "$field" in
        title|preview)
            current="$(sql "SELECT $field FROM $type WHERE slug='$slug'")"
            new_value="$(echo "$current" | dmenu -p "$field:")"
            [[ -z "$new_value" ]] && return
            new_value="${new_value//\'/\'\'}"
            sql "UPDATE $type SET $field='$new_value', updated_at=datetime('now') WHERE slug='$slug'"
            notify "Updated $field"
            ;;
        category_slug)
            new_value="$(sql "SELECT slug FROM categories ORDER BY slug" | dmenu -i -l 15 -p "category:")"
            [[ -z "$new_value" ]] && return
            sql "UPDATE $type SET category_slug='$new_value', updated_at=datetime('now') WHERE slug='$slug'"
            notify "Category: $new_value"
            ;;
        tags)
            local id
            id="$(sql "SELECT id FROM $type WHERE slug='$slug'")"
            local action
            action="$(printf "add\nremove" | dmenu -i -p "tags:")"
            [[ -z "$action" ]] && return

            if [[ "$action" == "add" ]]; then
                local tag
                tag="$(sql "SELECT slug FROM tags ORDER BY slug" | dmenu -i -l 20 -p "add tag:")"
                [[ -z "$tag" ]] && return
                local tag_id
                tag_id="$(sql "SELECT id FROM tags WHERE slug='$tag'")"
                [[ -z "$tag_id" ]] && return
                sql "INSERT OR IGNORE INTO content_tags (content_type, content_id, tag_id) VALUES ('$type', $id, $tag_id)"
                notify "Added tag: $tag"
            else
                local tag
                tag="$(sql "SELECT t.slug FROM tags t JOIN content_tags ct ON ct.tag_id=t.id WHERE ct.content_type='$type' AND ct.content_id=$id ORDER BY t.slug" | dmenu -i -l 10 -p "remove:")"
                [[ -z "$tag" ]] && return
                sql "DELETE FROM content_tags WHERE content_type='$type' AND content_id=$id AND tag_id=(SELECT id FROM tags WHERE slug='$tag')"
                notify "Removed tag: $tag"
            fi
            ;;
        status)
            new_value="$(printf "Notes\nDraft\nIn Progress\nFinished\nAbandoned" | dmenu -i -l 5 -p "status:")"
            [[ -z "$new_value" ]] && return
            sql "UPDATE $type SET status='$new_value', updated_at=datetime('now') WHERE slug='$slug'"
            notify "Status: $new_value"
            ;;
        confidence)
            new_value="$(printf "certain\nhighly likely\nlikely\npossible\nunlikely\nhighly unlikely\nremote\nimpossible" | dmenu -i -l 8 -p "confidence:")"
            [[ -z "$new_value" ]] && return
            sql "UPDATE $type SET confidence='$new_value', updated_at=datetime('now') WHERE slug='$slug'"
            notify "Confidence: $new_value"
            ;;
        importance)
            new_value="$(seq 1 10 | dmenu -i -l 10 -p "importance:")"
            [[ -z "$new_value" ]] && return
            sql "UPDATE $type SET importance=$new_value, updated_at=datetime('now') WHERE slug='$slug'"
            notify "Importance: $new_value"
            ;;
        publication)
            new_value="$(printf '%s\n' "${NEWS_PUBS[@]}" | dmenu -i -l 3 -p "publication:")"
            [[ -z "$new_value" ]] && return
            sql "UPDATE $type SET publication='$new_value', updated_at=datetime('now') WHERE slug='$slug'"
            notify "Publication: $new_value"
            ;;
        state)
            new_value="$(printf "active\nhidden" | dmenu -i -l 2 -p "state:")"
            [[ -z "$new_value" ]] && return
            sql "UPDATE $type SET state='$new_value', updated_at=datetime('now') WHERE slug='$slug'"
            notify "State: $new_value"
            ;;
    esac
}

###############################################################################
# entry selection helpers
###############################################################################

select_entry_fzf() {
    local type="$1" filter_pub="${2:-}"

    local query="SELECT title || '  (' || slug || ')' || char(9) || slug FROM $type WHERE state != '' "
    [[ -n "$filter_pub" ]] && query+="AND publication = '$filter_pub' "
    query+="ORDER BY title"

    sql "$query" |
    fzf --prompt="$type> " --delimiter=$'\t' --with-nth=1 \
        --preview="sqlite3 '$DB' \"SELECT 'Title: ' || title || char(10) || 'Preview: ' || COALESCE(preview,'') || char(10) || 'Category: ' || COALESCE(category_slug,'') || char(10) || 'State: ' || COALESCE(state,'active') FROM $type WHERE slug='{2}'\"" \
        --height=80% --reverse |
    awk -F'\t' '{print $2}'
}

select_entry_nnn_browse() {
    local type="$1"
    local content_path="$CONTENT_DIR/$type"

    [[ ! -d "$content_path" ]] && { echo ""; return; }

    local tmpfile
    tmpfile="$(mktemp)"

    NNN_TMPFILE="$tmpfile" nnn -p "$tmpfile" "$content_path"

    if [[ -s "$tmpfile" ]]; then
        local selected
        selected="$(cat "$tmpfile")"
        rm -f "$tmpfile"
        basename "$selected" .mdx
    else
        rm -f "$tmpfile"
        echo ""
    fi
}

###############################################################################
# mode: -nnn -data
###############################################################################

run_nnn_data() {
    check_deps_nnn
    check_deps_data

    clear
    print_banner_data

    while true; do
        local selection
        selection="$(fzf_menu | fzf --prompt="data> " --height=20 --reverse)" || exit 0

        [[ "$selection" == "quit" ]] && exit 0

        selection="${selection## }"
        local type
        type="$(db_type_for "$selection")"

        # Determine publication filter for news
        local pub_filter=""
        case "$selection" in
            the-soapbox|field-notes|off-the-record) pub_filter="$selection" ;;
        esac

        local mode
        mode="$(
            printf "%s\n" "fzf (search by title)" "nnn (browse files)" "back" |
            fzf --prompt="select via> " --height=5 --reverse
        )" || continue

        [[ "$mode" == "back" ]] && continue

        local slug=""
        if [[ "$mode" == *"fzf"* ]]; then
            slug="$(select_entry_fzf "$type" "$pub_filter")" || continue
        else
            slug="$(select_entry_nnn_browse "$type")" || continue
        fi

        [[ -z "$slug" ]] && continue

        local count
        count="$(sql "SELECT COUNT(*) FROM $type WHERE slug='$slug'")"
        if [[ "$count" -eq 0 ]]; then
            echo "  Slug '$slug' not found in $type table."
            read -rp "  Press Enter..." _
            continue
        fi

        while true; do
            clear
            print_banner_data
            show_metadata "$type" "$slug"

            local fields
            if [[ "$type" == "diary" ]]; then
                fields=("${DIARY_FIELDS[@]}" "tags" "done")
            elif [[ "$type" == "news" ]]; then
                fields=("${STANDARD_FIELDS[@]}" "publication" "tags" "done")
            else
                fields=("${STANDARD_FIELDS[@]}" "tags" "done")
            fi

            local field
            field="$(
                printf "%s\n" "${fields[@]}" |
                fzf --prompt="edit field> " --height=14 --reverse
            )" || break

            [[ "$field" == "done" ]] && break

            edit_field_nnn "$type" "$slug" "$field"
            read -rp "  Press Enter..." _
        done
    done
}

###############################################################################
# mode: -dmenu -data
###############################################################################

run_dmenu_data() {
    check_deps_dmenu
    check_deps_data

    local raw
    raw="$(dmenu_menu | dmenu -i -l 16 -p "data:")"
    [[ -z "$raw" ]] && exit 0

    local selection
    selection="$(parse_selection "$raw")"
    [[ -z "$selection" ]] && exit 0

    local type
    type="$(db_type_for "$selection")"

    # Publication filter for news subs
    local pub_filter=""
    case "$selection" in
        the-soapbox|field-notes|off-the-record) pub_filter="$selection" ;;
    esac

    # Select entry
    local query="SELECT title || '  [' || slug || ']' FROM $type "
    [[ -n "$pub_filter" ]] && query+="WHERE publication = '$pub_filter' "
    query+="ORDER BY title"

    local slug
    slug="$(
        sql "$query" |
            dmenu -i -l 20 -p "$type:" |
            sed 's/.*\[\(.*\)\]/\1/'
    )"
    [[ -z "$slug" ]] && exit 0

    # Edit loop
    while true; do
        local fields="title
preview
category_slug
tags
state"

        if [[ "$type" != "diary" ]]; then
            fields+="
status
confidence
importance"
        fi

        if [[ "$type" == "news" ]]; then
            fields+="
publication"
        fi

        local field
        field="$(echo "$fields" | dmenu -i -l 12 -p "field:")"
        [[ -z "$field" ]] && break
        edit_field_dmenu "$type" "$slug" "$field"
    done
}

###############################################################################
# dispatch
###############################################################################

case "${UI_MODE}-${ACTION_MODE}" in
    nnn-create)   run_nnn_create ;;
    dmenu-create) run_dmenu_create ;;
    nnn-edit)     run_nnn_edit ;;
    dmenu-edit)   run_dmenu_edit ;;
    nnn-data)     run_nnn_data ;;
    dmenu-data)   run_dmenu_data ;;
esac