File size: 44,330 Bytes
39508ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
#!/bin/bash
# ==========================================
# VHectorLab 3D - CONTROL PANEL & CLI SETUP
# ==========================================

# ANSI Color Palette
RESET="\033[0m"
BOLD="\033[1m"
CYAN="\033[1;36m"
GREEN="\033[1;32m"
YELLOW="\033[1;33m"
BLUE="\033[1;34m"
MAGENTA="\033[1;35m"
RED="\033[1;31m"
DIM="\033[2m"

LOG_FILE="vhectorlab_dev.log"
# Created & tested on macOS 26.5.1 (Darwin 25.5.0, arm64). Not prepared for Windows/Linux.
SUPPORTED_OS_LABEL="macOS 26.5.1 (Darwin 25.5.0)"

# Panel phase for SIGINT: menu | logs | confirm
# Ctrl+C must NEVER stop backend/frontend β€” only option 10 does that.
PANEL_PHASE="menu"

exit_panel_keep_services() {
    echo -e "\n${CYAN}${BOLD}Goodbye! Services keep running (use option 10 to stop).${RESET}"
    exit 0
}

handle_sigint() {
    case "$PANEL_PHASE" in
        logs)
            # Interrupt tail -f only; follow_backend_logs continues to the confirm prompt.
            echo -e "\n${YELLOW}${BOLD}⏸ Log follow paused. Services still running.${RESET}"
            PANEL_PHASE="confirm"
            ;;
        confirm)
            exit_panel_keep_services
            ;;
        *)
            exit_panel_keep_services
            ;;
    esac
}

trap 'handle_sigint' INT

# Launch a command in a new session (no controlling TTY).
# Avoids: (1) panel Ctrl+C SIGINT killing services, (2) SIGTTOU stop (STAT T) from set -m/job control.
# Usage: launch_detached <workdir> <logfile|-> <cmd...>   ("-" logfile β†’ /dev/null)
launch_detached() {
    local workdir="$1"
    local logfile="$2"
    shift 2
    if [ "$logfile" = "-" ]; then
        logfile="/dev/null"
    fi
    case "$workdir" in
        /*) ;;
        *) workdir="$(pwd)/$workdir" ;;
    esac
    case "$logfile" in
        /*) ;;
        *) logfile="$(pwd)/$logfile" ;;
    esac

    python3 - "$workdir" "$logfile" "$@" <<'PY'
import os, sys, subprocess

workdir, logfile, *cmd = sys.argv[1:]
os.chdir(workdir)
log = open(logfile, "a", buffering=1)
subprocess.Popen(
    cmd,
    stdin=subprocess.DEVNULL,
    stdout=log,
    stderr=subprocess.STDOUT,
    start_new_session=True,
    close_fds=True,
)
PY
}

refresh_path() {
    # uv installer lands in ~/.local/bin; Homebrew on Apple Silicon uses /opt/homebrew.
    export PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"
    # shellcheck disable=SC1090
    [ -f "$HOME/.local/bin/env" ] && source "$HOME/.local/bin/env"
}

warn_if_unsupported_platform() {
    local os_name
    os_name="$(uname -s 2>/dev/null || echo unknown)"
    if [ "$os_name" != "Darwin" ]; then
        echo -e "${YELLOW}${BOLD}⚠️  Unsupported platform: ${os_name}${RESET}"
        echo -e "${YELLOW}   This project was created and tested on ${SUPPORTED_OS_LABEL}.${RESET}"
        echo -e "${YELLOW}   It was not prepared for Windows or Linux. Small adaptations may make it work.${RESET}"
        echo -e "${YELLOW}   Auto-install of missing tools is macOS-only (Homebrew + official uv installer).${RESET}"
        return 1
    fi
    return 0
}

ensure_homebrew() {
    if command -v brew &> /dev/null; then
        echo -e "  ${GREEN}βœ“ Homebrew detected.${RESET}"
        return 0
    fi
    echo -e "${YELLOW}β–Ά Homebrew not found. Installing Homebrew (may ask for your password)...${RESET}"
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    if [ -x /opt/homebrew/bin/brew ]; then
        eval "$(/opt/homebrew/bin/brew shellenv)"
    elif [ -x /usr/local/bin/brew ]; then
        eval "$(/usr/local/bin/brew shellenv)"
    fi
    refresh_path
    if ! command -v brew &> /dev/null; then
        echo -e "${RED}❌ Failed to install Homebrew. Install it from https://brew.sh and re-run.${RESET}"
        return 1
    fi
    echo -e "  ${GREEN}βœ“ Homebrew installed.${RESET}"
    return 0
}

ensure_uv() {
    refresh_path
    if command -v uv &> /dev/null; then
        echo -e "  ${GREEN}βœ“ Python package manager 'uv' detected ($(uv --version 2>/dev/null | head -1)).${RESET}"
        return 0
    fi
    echo -e "${YELLOW}β–Ά 'uv' not found. Installing via official installer...${RESET}"
    curl -LsSf https://astral.sh/uv/install.sh | sh
    refresh_path
    if ! command -v uv &> /dev/null; then
        echo -e "${RED}❌ Failed to install 'uv'. See https://docs.astral.sh/uv/getting-started/installation/${RESET}"
        return 1
    fi
    echo -e "  ${GREEN}βœ“ 'uv' installed ($(uv --version 2>/dev/null | head -1)).${RESET}"
    return 0
}

ensure_node_npm() {
    refresh_path
    if command -v npm &> /dev/null && command -v node &> /dev/null; then
        echo -e "  ${GREEN}βœ“ Node.js $(node --version) / npm $(npm --version) detected.${RESET}"
        return 0
    fi
    if [ "$(uname -s)" != "Darwin" ]; then
        echo -e "${RED}❌ Node.js/npm missing. On this unsupported OS, install Node.js LTS yourself, then re-run.${RESET}"
        return 1
    fi
    ensure_homebrew || return 1
    echo -e "${YELLOW}β–Ά Node.js/npm not found. Installing Node via Homebrew...${RESET}"
    brew install node
    refresh_path
    if ! command -v npm &> /dev/null || ! command -v node &> /dev/null; then
        echo -e "${RED}❌ Failed to install Node.js/npm. Install the LTS from https://nodejs.org and re-run.${RESET}"
        return 1
    fi
    echo -e "  ${GREEN}βœ“ Node.js $(node --version) / npm $(npm --version) installed.${RESET}"
    return 0
}

ensure_project_deps() {
    if [ ! -f .env ] && [ -f .env.example ]; then
        echo -e "${YELLOW}β–Ά Creating .env from .env.example...${RESET}"
        cp .env.example .env
        echo -e "  ${GREEN}βœ“ .env created (edit values if needed).${RESET}"
    elif [ -f .env ]; then
        echo -e "  ${GREEN}βœ“ .env present.${RESET}"
    fi

    # After renaming/moving the repo folder, entrypoint scripts in .venv keep absolute
    # shebangs to the old path β†’ `uv run pytest` fails with "No such file or directory".
    if [ -f backend/.venv/bin/pytest ]; then
        local pytest_python
        pytest_python="$(head -1 backend/.venv/bin/pytest | sed 's/^#![[:space:]]*//')"
        if [ -n "$pytest_python" ] && [ ! -e "$pytest_python" ]; then
            echo -e "${YELLOW}β–Ά Backend .venv is stale (scripts still point to a missing path).${RESET}"
            echo -e "${YELLOW}  Recreating virtualenv after folder move/rename...${RESET}"
            rm -rf backend/.venv
        fi
    fi

    echo -e "${BLUE}β–Ά Syncing backend Python deps (uv sync --extra dev)...${RESET}"
    (cd backend && uv sync --extra dev) || {
        echo -e "${RED}❌ Backend dependency sync failed.${RESET}"
        return 1
    }
    echo -e "  ${GREEN}βœ“ Backend deps ready.${RESET}"

    if [ ! -d node_modules ]; then
        echo -e "${YELLOW}β–Ά Frontend node_modules missing. Running npm install...${RESET}"
        npm install || {
            echo -e "${RED}❌ npm install failed.${RESET}"
            return 1
        }
        echo -e "  ${GREEN}βœ“ Frontend deps installed.${RESET}"
    else
        echo -e "  ${GREEN}βœ“ Frontend node_modules present.${RESET}"
    fi
    return 0
}

ensure_prerequisites() {
    echo -e "\n${CYAN}${BOLD}====================================================${RESET}"
    echo -e "${CYAN}${BOLD}πŸ” CHECKING / INSTALLING PREREQUISITES...${RESET}"
    echo -e "${CYAN}${BOLD}====================================================${RESET}"
    echo -e "  ${DIM}Supported / tested on: ${SUPPORTED_OS_LABEL}${RESET}"

    warn_if_unsupported_platform
    # On macOS, missing tools are installed automatically. Elsewhere, require them preinstalled.

    ensure_uv || return 1
    ensure_node_npm || return 1
    ensure_project_deps || return 1
    return 0
}

# --- Idempotent service probes (process + health; ports detect "sick") ---
# healthy = matching process AND health OK
# down    = no process, no health, port free
# sick    = anything else (partial / port held / health failing)

BACKEND_URL="http://127.0.0.1:8000"
FRONTEND_URL="http://127.0.0.1:5173"
BACKEND_PORT=8000
FRONTEND_PORT=5173
# Must match `python3 -m server` / venv `.../python3 -m server` (NOT only `python -m server`).
# Also matches uvicorn import string backend.server:app when present in the cmdline.
BACKEND_PROC_PATTERN='backend\.server:app|-m[[:space:]]+server'

port_listening() {
    local port="$1"
    lsof -nP -iTCP:"$port" -sTCP:LISTEN >/dev/null 2>&1
}

backend_process_running() {
    pgrep -f "$BACKEND_PROC_PATTERN" >/dev/null 2>&1
}

kill_backend() {
    # Stop matching processes, then anything still bound to BACKEND_PORT.
    # Uvicorn --reload leaves multiprocessing workers whose cmdline is
    # `python -c ...spawn_main...` (does NOT match -m server) β€” port kill is mandatory.
    pkill -f "$BACKEND_PROC_PATTERN" 2>/dev/null || true
    local i pids
    for i in 1 2 3 4 5 6 7 8; do
        pids="$(lsof -nP -tiTCP:"${BACKEND_PORT}" -sTCP:LISTEN 2>/dev/null || true)"
        if [ -z "$pids" ]; then
            return 0
        fi
        # shellcheck disable=SC2086
        if [ "$i" -le 3 ]; then
            kill $pids 2>/dev/null || true
        else
            kill -9 $pids 2>/dev/null || true
        fi
        sleep 0.4
    done
}

wait_backend_port_free() {
    local i
    for i in $(seq 1 40); do
        if ! port_listening "$BACKEND_PORT"; then
            return 0
        fi
        sleep 0.25
    done
    echo -e "  ${RED}Port ${BACKEND_PORT} still in use after kill.${RESET}"
    return 1
}

frontend_process_running() {
    # Prefer the launch signature from this script; avoid bare "vite" (matches vitest).
    pgrep -f "vite --port ${FRONTEND_PORT}" >/dev/null 2>&1
}

backend_health_ok() {
    local body
    body="$(curl -sf --max-time 2 "${BACKEND_URL}/health" 2>/dev/null)" || return 1
    echo "$body" | grep -q '"status"[[:space:]]*:[[:space:]]*"ok"'
}

frontend_health_ok() {
    curl -sf --max-time 2 -o /dev/null "${FRONTEND_URL}/" 2>/dev/null
}

# Prints: healthy | sick | down
probe_backend() {
    local proc=0 health=0 port=0
    backend_process_running && proc=1
    backend_health_ok && health=1
    port_listening "$BACKEND_PORT" && port=1
    if [ "$proc" -eq 1 ] && [ "$health" -eq 1 ]; then
        echo "healthy"
    elif [ "$proc" -eq 0 ] && [ "$health" -eq 0 ] && [ "$port" -eq 0 ]; then
        echo "down"
    else
        echo "sick"
    fi
}

# Prints: healthy | sick | down
probe_frontend() {
    local proc=0 health=0 port=0
    frontend_process_running && proc=1
    frontend_health_ok && health=1
    port_listening "$FRONTEND_PORT" && port=1
    if [ "$proc" -eq 1 ] && [ "$health" -eq 1 ]; then
        echo "healthy"
    elif [ "$proc" -eq 0 ] && [ "$health" -eq 0 ] && [ "$port" -eq 0 ]; then
        echo "down"
    else
        echo "sick"
    fi
}

describe_service_state() {
    local name="$1"
    local state="$2"
    local port="$3"
    case "$state" in
        healthy) echo -e "  ${GREEN}βœ“ ${name}: healthy (process + health OK on :${port})${RESET}" ;;
        down)    echo -e "  ${DIM}Β· ${name}: down${RESET}" ;;
        sick)    echo -e "  ${YELLOW}⚠ ${name}: sick (process/port/health mismatch on :${port})${RESET}" ;;
        *)       echo -e "  ${RED}? ${name}: unknown (${state})${RESET}" ;;
    esac
}

ensure_vocab() {
    if [ ! -f "public/vocab.txt" ]; then
        echo -e "${YELLOW}⚠️ Vocabulary missing at public/vocab.txt. Generating 10,000 words...${RESET}"
        python3 scripts/generate_vocab.py --count 10000
    fi
    echo -e "  ${GREEN}βœ“ public/vocab.txt OK ($(wc -l < public/vocab.txt | tr -d ' ') words).${RESET}"
}

run_full_test_suite() {
    echo -e "\n${CYAN}${BOLD}====================================================${RESET}"
    echo -e "${CYAN}${BOLD}πŸ§ͺ RUNNING FULL TEST SUITE...${RESET}"
    echo -e "${CYAN}${BOLD}====================================================${RESET}"

    echo -e "${BLUE}${BOLD}β–Ά [1/2] Backend unit tests (pytest)...${RESET}"
    echo -e "${DIM}Loading PyTorch SentenceTransformer model into memory...${RESET}"
    (cd backend && uv run python -m pytest -v -s)
    if [ $? -ne 0 ]; then
        echo -e "${RED}${BOLD}❌ ERROR: Backend tests failed. Fix them before deploying.${RESET}"
        return 1
    fi
    echo -e "  ${GREEN}${BOLD}βœ“ Backend tests GREEN.${RESET}"

    echo -e "\n${BLUE}${BOLD}β–Ά [2/2] Frontend unit tests (Vitest)...${RESET}"
    npx vitest run --reporter=verbose
    if [ $? -ne 0 ]; then
        echo -e "${RED}${BOLD}❌ ERROR: Frontend tests failed. Fix them before deploying.${RESET}"
        return 1
    fi
    echo -e "  ${GREEN}${BOLD}βœ“ Frontend tests GREEN.${RESET}"
    return 0
}

kill_stack() {
    kill_backend
    pkill -f "vite --port ${FRONTEND_PORT}" 2>/dev/null || true
    # Fallback for older/manual vite launches on the same port
    pkill -f "vite" 2>/dev/null || true
    sleep 1
}

wait_backend_healthy() {
    # Progress bar while model loads into RAM (up to ~60s).
    local i filled empty bar pct
    local total=60
    echo -e "  ${DIM}Waiting for /health status=ok (model load)…${RESET}"
    for i in $(seq 1 "$total"); do
        if backend_health_ok; then
            bar="$(printf 'β–ˆ%.0s' $(seq 1 28))"
            echo -ne "\r  [${GREEN}${bar}${RESET}]  ${BOLD}100%${RESET}  ${GREEN}${BOLD}MODEL LOADED OK${RESET}                    \n"
            return 0
        fi
        filled=$(( i * 28 / total ))
        empty=$(( 28 - filled ))
        pct=$(( i * 100 / total ))
        bar="$(printf 'β–ˆ%.0s' $(seq 1 "$filled") 2>/dev/null)$(printf 'β–‘%.0s' $(seq 1 "$empty") 2>/dev/null)"
        echo -ne "\r  [${CYAN}${bar}${RESET}]  ${pct}%  probing ${BACKEND_URL}/health…   "
        sleep 1
    done
    echo -e "\n  ${RED}${BOLD}TIMEOUT${RESET} β€” backend did not become healthy"
    return 1
}

start_backend() {
    echo -e "${BLUE}β–Ά Starting Backend FastAPI (${BACKEND_URL})...${RESET}"
    # Pass repo-root .env explicitly: uv project cwd is backend/ (no backend/.env).
    # UVICORN_RELOAD=0 avoids orphan multiprocessing workers that survive pkill -m server.
    local env_file
    env_file="$(pwd)/.env"
    if [ -f "$env_file" ]; then
        launch_detached "backend" "$LOG_FILE" \
            env UVICORN_RELOAD=0 uv run --env-file "$env_file" python -m server
    else
        launch_detached "backend" "$LOG_FILE" \
            env UVICORN_RELOAD=0 uv run python -m server
    fi
    wait_backend_healthy
}

start_frontend() {
    echo -e "${BLUE}β–Ά Starting Frontend WebGL (Vite Dev Server)...${RESET}"
    launch_detached "." "-" npx vite --port "$FRONTEND_PORT" --host 127.0.0.1
    local i
    for i in {1..20}; do
        if frontend_health_ok; then
            echo -e "  ${GREEN}βœ“ Frontend responding on ${FRONTEND_URL}${RESET}"
            return 0
        fi
        sleep 0.5
    done
    echo -e "${YELLOW}  Frontend started but not responding yet on ${FRONTEND_URL}${RESET}"
    return 1
}

open_app_browser() {
    echo -e "${YELLOW}🌐 Opening browser at ${FRONTEND_URL}...${RESET}"
    if command -v open &> /dev/null; then
        open "$FRONTEND_URL"
    elif command -v xdg-open &> /dev/null; then
        xdg-open "$FRONTEND_URL"
    fi
}

follow_backend_logs() {
    echo -e "\n${MAGENTA}${BOLD}====================================================${RESET}"
    echo -e "${MAGENTA}${BOLD}πŸ“œ LIVE BACKEND LOGS${RESET}"
    echo -e "${MAGENTA}${BOLD}====================================================${RESET}"
    echo -e " ${DIM}Ctrl+C pauses logs (does NOT stop services).${RESET}\n"

    PANEL_PHASE="logs"
    # SIGINT interrupts this pipeline; handle_sigint keeps the panel alive.
    tail -f "$LOG_FILE" 2>/dev/null | sed \
        -e "s/INFO/${GREEN}INFO${RESET}/g" \
        -e "s/WARNING/${YELLOW}WARNING${RESET}/g" \
        -e "s/ERROR/${RED}ERROR${RESET}/g" \
        -e "s/200 OK/${GREEN}200 OK${RESET}/g" \
        -e "s/POST /${CYAN}POST ${RESET}/g" \
        -e "s/GET /${CYAN}GET ${RESET}/g" \
        || true

    PANEL_PHASE="confirm"
    echo -e "\n${YELLOW}${BOLD}Press Enter to return to the menu, or Ctrl+C again to exit the panel.${RESET}"
    echo -e "${DIM}Services stay up either way. Use option 10 to stop them.${RESET}"
    if read -r _; then
        PANEL_PHASE="menu"
        return 0
    fi
    exit_panel_keep_services
}

print_ready_banner() {
    echo -e "\n${GREEN}${BOLD}====================================================${RESET}"
    echo -e "${GREEN}${BOLD}        πŸŽ‰ Ready to go!${RESET}"
    echo -e "${GREEN}${BOLD}====================================================${RESET}"
    echo -e " ${BOLD}The tool is running at:${RESET}"
    echo -e " ${CYAN}${BOLD}πŸ‘‰ ${FRONTEND_URL}${RESET}\n"
}

show_menu() {
    clear
    echo -e "${CYAN}${BOLD}====================================================${RESET}"
    echo -e "${CYAN}${BOLD}       🌐 VHectorLab 3D - CONTROL PANEL${RESET}"
    echo -e "${CYAN}${BOLD}====================================================${RESET}"
    echo -e " ${GREEN}${BOLD}1. πŸš€ Deploy / Start Tool${RESET} ${DIM}(Idempotent: skip start if already healthy)${RESET}"
    echo -e " ${GREEN}2.${RESET} ${BOLD}Start Bare-metal Backend${RESET} ${DIM}(FastAPI on 127.0.0.1:8000 Β· skip if healthy)${RESET}"
    echo -e " ${BLUE}3.${RESET} ${BOLD}Run System Heartbeat${RESET} ${DIM}(Health Check & Arithmetic)${RESET}"
    echo -e " ${BLUE}4.${RESET} ${BOLD}Run Frontend Unit Tests${RESET} ${DIM}(Vitest)${RESET}"
    echo -e " ${BLUE}5.${RESET} ${BOLD}Run Backend Unit Tests${RESET} ${DIM}(pytest)${RESET}"
    echo -e " ${MAGENTA}6.${RESET} ${BOLD}Manage Vocabulary${RESET} ${DIM}(Custom vocab.txt / N words)${RESET}"
    echo -e " ${YELLOW}7.${RESET} ${BOLD}Build Hugging Face Space Docker Image${RESET} ${DIM}(Docker Desktop Β· torch CPU Β· :7860)${RESET}"
    echo -e " ${YELLOW}8.${RESET} ${BOLD}Publish Hugging Face Space${RESET} ${DIM}(hf CLI Β· inject deploy/hf frontmatter Β· cpu-basic)${RESET}"
    echo -e " ${CYAN}9.${RESET} ${BOLD}View Logs${RESET} ${DIM}(Live backend logs)${RESET}"
    echo -e " ${RED}10.${RESET} ${BOLD}Stop / Clean Services${RESET}"
    echo -e " ${MAGENTA}11.${RESET} ${BOLD}Select Embedding Model / Profile${RESET} ${DIM}(catalog Β· rebuild NPZ Β· restart backend)${RESET}"
    echo -e " ${DIM}0. Exit${RESET}"
    echo -e "${CYAN}${BOLD}====================================================${RESET}"
}

deploy_and_start() {
    local be_state fe_state force_restart=0
    be_state="$(probe_backend)"
    fe_state="$(probe_frontend)"

    echo -e "\n${CYAN}${BOLD}====================================================${RESET}"
    echo -e "${CYAN}${BOLD}πŸ“‘ SERVICE STATUS${RESET}"
    echo -e "${CYAN}${BOLD}====================================================${RESET}"
    describe_service_state "Backend " "$be_state" "$BACKEND_PORT"
    describe_service_state "Frontend" "$fe_state" "$FRONTEND_PORT"

    # Both already healthy: skip prereqs, tests, and start β€” just open the app.
    if [ "$be_state" = "healthy" ] && [ "$fe_state" = "healthy" ]; then
        echo -e "\n${GREEN}${BOLD}βœ“ Stack already up β€” skipping prerequisites, tests, and start.${RESET}"
        print_ready_banner
        open_app_browser
        echo -e "${DIM}Services left running as-is. Use options 4/5 for tests, 9 for logs, 10 to stop.${RESET}"
        read -p "Press Enter to return to menu..."
        return
    fi

    # Sick or partial β†’ recycle both (don't leave the user stuck on a frozen port).
    if [ "$be_state" = "sick" ] || [ "$fe_state" = "sick" ]; then
        force_restart=1
        echo -e "\n${YELLOW}${BOLD}⚠ Sick stack detected (e.g. frozen process on a live port). Recycling BOTH services.${RESET}"
    elif { [ "$be_state" = "healthy" ] && [ "$fe_state" = "down" ]; } || \
         { [ "$be_state" = "down" ] && [ "$fe_state" = "healthy" ]; }; then
        force_restart=1
        echo -e "\n${YELLOW}${BOLD}⚠ Partial stack detected β€” restarting BOTH services.${RESET}"
    fi

    echo -e "\n${CYAN}${BOLD}====================================================${RESET}"
    echo -e "${CYAN}${BOLD}πŸ” VERIFYING ENVIRONMENT & REQUIREMENTS...${RESET}"
    echo -e "${CYAN}${BOLD}====================================================${RESET}"

    if ! ensure_prerequisites; then
        read -p "Press Enter..."
        return
    fi

    ensure_vocab

    if ! run_full_test_suite; then
        read -p "Press Enter..."
        return
    fi

    echo -e "\n${CYAN}${BOLD}====================================================${RESET}"
    echo -e "${CYAN}${BOLD}πŸš€ STARTING SERVICES (BACKEND + FRONTEND)...${RESET}"
    echo -e "${CYAN}${BOLD}====================================================${RESET}"

    if [ "$force_restart" -eq 1 ]; then
        echo -e "${YELLOW}β–Ά Stopping existing services before full restart...${RESET}"
    fi
    kill_stack

    if ! start_backend; then
        echo -e "${RED}${BOLD}❌ Backend failed to become healthy. Check ${LOG_FILE}.${RESET}"
        read -p "Press Enter..."
        return
    fi
    start_frontend

    print_ready_banner
    open_app_browser
    follow_backend_logs
}

start_bare_metal_backend() {
    local be_state
    be_state="$(probe_backend)"
    describe_service_state "Backend " "$be_state" "$BACKEND_PORT"

    if [ "$be_state" = "healthy" ]; then
        echo -e "${GREEN}${BOLD}βœ“ Backend already healthy β€” skipping start.${RESET}"
        read -p "Press Enter..."
        return
    fi

    if [ "$be_state" = "sick" ]; then
        echo -e "\n${YELLOW}${BOLD}⚠ Backend sick β€” stopping and restarting.${RESET}"
        kill_backend
        wait_backend_port_free || true
    fi

    echo -e "${GREEN}Starting Bare-metal Backend...${RESET}"
    if ! ensure_prerequisites; then
        read -p "Press Enter..."
        return
    fi
    start_backend
    echo -e "${GREEN}Backend started in background (Logs: $LOG_FILE)${RESET}"
    read -p "Press Enter..."
}

manage_vocab() {
    echo ""
    echo -e "${MAGENTA}${BOLD}--- Manage Vocabulary ---${RESET}"
    echo -e " ${GREEN}1)${RESET} Load Custom vocab.txt file"
    echo -e " ${GREEN}2)${RESET} Generate new vocab.txt with custom word count"
    read -p "Select option [1-2]: " vopt
    case $vopt in
        1)
            read -p "Enter path to your custom vocab.txt: " custom_path
            if [ -f "$custom_path" ]; then
                cp "$custom_path" public/vocab.txt
                echo -e "${GREEN}βœ… Successfully copied $custom_path to public/vocab.txt${RESET}"
            else
                echo -e "${RED}❌ Error: File $custom_path does not exist.${RESET}"
            fi
            ;;
        2)
            read -p "Enter target word count (default 10000): " count
            count=${count:-10000}
            python3 scripts/generate_vocab.py --count "$count"
            ;;
        *)
            echo -e "${RED}Invalid option.${RESET}"
            ;;
    esac
    read -p "Press Enter to return to menu..."
}

select_embedding_model() {
    local choice summary confirm
    local script
    script="$(pwd)/scripts/select_embedding_model.py"

    echo ""
    echo -e "${MAGENTA}${BOLD}╔════════════════════════════════════════════════════════════╗${RESET}"
    echo -e "${MAGENTA}${BOLD}β•‘${RESET}  ${BOLD}Select Embedding Model / Profile${RESET}                         ${MAGENTA}${BOLD}β•‘${RESET}"
    echo -e "${MAGENTA}${BOLD}β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•${RESET}"
    echo -e "${DIM}  Always regenerates vocab NPZ Β· writes .env Β· restarts backend${RESET}"
    echo -e "${DIM}  ENβˆͺES vocab ensured Β· HF Space options 7/8 unchanged${RESET}"
    echo ""

    if [ -f .env ]; then
        echo -e "  ${BOLD}Current selection${RESET}"
        local cur_profile cur_model cur_trunc cur_vocab
        cur_profile="$(grep -E '^MODEL_PROFILE=' .env 2>/dev/null | head -1 | cut -d= -f2-)"
        cur_model="$(grep -E '^MODEL_NAME=' .env 2>/dev/null | head -1 | cut -d= -f2-)"
        cur_trunc="$(grep -E '^TRUNCATE_DIM=' .env 2>/dev/null | head -1 | cut -d= -f2-)"
        cur_vocab="$(grep -E '^VOCAB_PATH=' .env 2>/dev/null | head -1 | cut -d= -f2-)"
        echo -e "    ${DIM}profile${RESET}   ${cur_profile:-β€”}"
        echo -e "    ${DIM}model${RESET}     ${cur_model:-β€”}"
        echo -e "    ${DIM}truncate${RESET}  ${cur_trunc:-β€”}"
        echo -e "    ${DIM}vocab${RESET}     ${cur_vocab:-β€”}"
    else
        echo -e "  ${YELLOW}No .env yet β€” will be created on apply.${RESET}"
    fi
    echo ""

    if ! uv run --directory backend python "$script" list; then
        echo -e "${RED}Failed to load embedding catalog.${RESET}"
        read -p "Press Enter to return to menu..."
        return
    fi
    echo ""
    read -p "  Choice [number / P# / M# / 0 cancel]: " choice
    case "$choice" in
        ""|0|c|C|cancel|Cancel|CANCEL)
            echo -e "${YELLOW}  Cancelled.${RESET}"
            read -p "Press Enter to return to menu..."
            return
            ;;
    esac

    if ! summary="$(uv run --directory backend python "$script" describe --choice "$choice" 2>/dev/null)"; then
        echo -e "${RED}  Invalid choice: ${choice}${RESET}"
        read -p "Press Enter to return to menu..."
        return
    fi

    echo ""
    echo -e "  ${BOLD}You selected${RESET}"
    echo -e "    ${CYAN}${summary}${RESET}"
    echo ""
    echo -e "  ${DIM}This will: merge ENβˆͺES if needed β†’ stage .env β†’ encode NPZ β†’ restart backend${RESET}"
    read -p "  Proceed? [Y/n]: " confirm
    case "$confirm" in
        n|N|no|No|NO)
            echo -e "${YELLOW}  Cancelled.${RESET}"
            read -p "Press Enter to return to menu..."
            return
            ;;
    esac

    echo ""
    echo -e "${CYAN}${BOLD}── Pipeline ──────────────────────────────────────────────${RESET}"
    echo -e "  ${DIM}[β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘]  overall Β· prepare + restart${RESET}"
    echo ""

    # Phase A β€” Python prepare (shows its own 1/4…4/4 bars + encode tqdm)
    echo -e "  ${BOLD}Phase A/B${RESET}  Prepare (.env + NPZ)"
    if ! uv run --directory backend python "$script" apply --choice "$choice" --device "${SAE_DEVICE:-AUTO}"; then
        echo -e "${RED}${BOLD}  βœ— Swap failed β€” previous .env restored.${RESET}"
        echo -e "${DIM}  Gated models: hf auth login + accept license on the Hub.${RESET}"
        read -p "Press Enter to return to menu..."
        return
    fi

    echo ""
    echo -e "  ${BOLD}Phase B/B${RESET}  Restart backend + wait for /health"
    echo -e "  ${DIM}Stopping old backend process…${RESET}"
    kill_backend
    if ! wait_backend_port_free; then
        echo -e "${RED}${BOLD}  βœ— Could not free :${BACKEND_PORT} β€” old process may still be live.${RESET}"
        read -p "Press Enter to return to menu..."
        return
    fi
    if ! start_backend; then
        echo -e "${RED}${BOLD}  βœ— Backend failed to become healthy after swap. Check ${LOG_FILE}.${RESET}"
        read -p "Press Enter to return to menu..."
        return
    fi

    echo ""
    echo -e "  ${GREEN}${BOLD}βœ“ Swap complete β€” /health${RESET}"
    local health_json expected_model
    health_json="$(curl -sS --max-time 5 "${BACKEND_URL}/health" 2>/dev/null || true)"
    echo "$health_json" | python3 -m json.tool 2>/dev/null || echo "$health_json"
    expected_model="$(grep -E '^MODEL_NAME=' .env 2>/dev/null | head -1 | cut -d= -f2-)"
    if [ -n "$expected_model" ] && [ -n "$health_json" ]; then
        if ! echo "$health_json" | grep -Fq "$expected_model"; then
            echo -e "${RED}${BOLD}  βœ— /health model does not match .env MODEL_NAME=${expected_model}${RESET}"
            echo -e "${DIM}  Old process may have survived, or .env was not loaded. Check ${LOG_FILE}.${RESET}"
            read -p "Press Enter to return to menu..."
            return
        fi
    fi
    echo ""
    read -p "Press Enter to return to menu..."
}

ensure_docker() {
    refresh_path
    if command -v docker &> /dev/null && docker info &> /dev/null; then
        echo -e "  ${GREEN}βœ“ Docker is available ($(docker --version 2>/dev/null)).${RESET}"
        return 0
    fi

    if command -v docker &> /dev/null && ! docker info &> /dev/null; then
        echo -e "${YELLOW}β–Ά Docker CLI found but the daemon is not running.${RESET}"
        if [ "$(uname -s)" = "Darwin" ]; then
            echo -e "${YELLOW}  Opening Docker Desktop β€” wait until it says running, then retry option 7.${RESET}"
            open -a Docker 2>/dev/null || true
        fi
        echo -e "${RED}❌ Start Docker Desktop (whale icon in the menu bar), then re-run option 7.${RESET}"
        return 1
    fi

    if [ "$(uname -s)" != "Darwin" ]; then
        echo -e "${RED}❌ Docker is required for this option but is not installed.${RESET}"
        echo -e "${RED}   Local daily use (option 1) does not need Docker. Install Docker yourself on this OS.${RESET}"
        return 1
    fi

    ensure_homebrew || return 1
    echo -e "${YELLOW}β–Ά Docker not found. Installing Docker Desktop via Homebrew (cask)...${RESET}"
    echo -e "${DIM}  Note: Docker Desktop is optional β€” only needed for HF Space image builds (option 7).${RESET}"
    brew install --cask docker || {
        echo -e "${RED}❌ Failed to install Docker Desktop. Install from https://www.docker.com/products/docker-desktop/${RESET}"
        return 1
    }
    echo -e "${YELLOW}  Opening Docker Desktop for first-time setup...${RESET}"
    open -a Docker 2>/dev/null || true
    echo -e "${YELLOW}  Wait until Docker Desktop finishes starting, then re-run option 7.${RESET}"
    return 1
}

ensure_hf_cli() {
    refresh_path
    if command -v hf &> /dev/null; then
        echo -e "  ${GREEN}βœ“ Hugging Face CLI available ($(hf version 2>/dev/null | head -1 || echo hf)).${RESET}"
        return 0
    fi
    echo -e "${YELLOW}β–Ά Installing Hugging Face Hub CLI via uv…${RESET}"
    uv tool install huggingface_hub[cli] 2>/dev/null || uv pip install --system 'huggingface_hub[cli]' 2>/dev/null || {
        echo -e "${RED}❌ Could not install hf CLI. Run: uv tool install 'huggingface_hub[cli]' then hf auth login${RESET}"
        return 1
    }
    refresh_path
    if ! command -v hf &> /dev/null; then
        echo -e "${RED}❌ hf not on PATH after install. Open a new terminal or run: uv tool update-shell${RESET}"
        return 1
    fi
    return 0
}

ensure_hf_auth() {
    local out ec=0
    out="$(hf auth whoami 2>&1)" || ec=$?
    if [ "$ec" -ne 0 ] || echo "$out" | grep -qiE 'invalid user token|not logged in|no token|unauthorized|401|error:'; then
        echo -e "${RED}❌ Hugging Face auth failed.${RESET}"
        echo -e "${DIM}$(echo "$out" | head -4)${RESET}"
        echo -e "${YELLOW}  Fix: hf auth login --force --add-to-git-credential${RESET}"
        echo -e "${DIM}  Create a Write token at https://huggingface.co/settings/tokens${RESET}"
        return 1
    fi
    echo -e "  ${GREEN}βœ“ HF auth OK${RESET} ${DIM}$(echo "$out" | head -3 | tr '\n' ' ')${RESET}"
    return 0
}

build_hf_docker() {
    echo -e "${YELLOW}${BOLD}Compiling Hugging Face Spaces Docker Image (cpu-basic / torch CPU)…${RESET}"
    if ! ensure_docker; then
        read -p "Press Enter to return to menu..."
        return
    fi
    echo -e "${DIM}  pytorch-cpu index (Linux) Β· port 7860 Β· precomputes vocab_embeddings.npz in-image${RESET}"
    docker build -t vhectorlab-3d:latest .
    if [ $? -ne 0 ]; then
        echo -e "${RED}${BOLD}❌ Docker build failed.${RESET}"
        read -p "Press Enter to return to menu..."
        return
    fi
    echo -e "${GREEN}${BOLD}βœ… Image tagged vhectorlab-3d:latest${RESET}"
    read -p "Smoke-test locally on :7860 now? [y/N]: " smoke
    if [[ "$smoke" =~ ^[Yy]$ ]]; then
        echo -e "${CYAN}β–Ά docker run --rm -p 7860:7860 vhectorlab-3d:latest${RESET}"
        echo -e "${DIM}  Open http://127.0.0.1:7860 β€” Ctrl+C stops the container.${RESET}"
        docker run --rm -p 7860:7860 vhectorlab-3d:latest
    fi
    read -p "Press Enter to return to menu..."
}

# Normalize user input to Hugging Face Space id: "namespace/name".
# Accepts bare id, or URLs like https://huggingface.co/spaces/ns/name
normalize_hf_space_id() {
    local raw="$1"
    raw="$(echo "$raw" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
    # Strip common URL prefixes (order matters: spaces/ before bare hub host)
    raw="$(echo "$raw" | sed -E \
        -e 's#^https?://huggingface\.co/spaces/##' \
        -e 's#^https?://hf\.co/spaces/##' \
        -e 's#^https?://huggingface\.co/##' \
        -e 's#^https?://hf\.co/##' \
        -e 's#/$##')"
    echo "$raw"
}

validate_hf_space_id() {
    local id="$1"
    if [[ ! "$id" =~ ^[A-Za-z0-9_-]+/[A-Za-z0-9._-]+$ ]]; then
        return 1
    fi
    return 0
}

load_dotenv() {
    # Export KEY=VAL from .env (ignore comments / blank lines). Used for option 8 defaults.
    if [ ! -f .env ]; then
        return 0
    fi
    local line key val
    while IFS= read -r line || [ -n "$line" ]; do
        case "$line" in
            ''|\#*) continue ;;
        esac
        if [[ "$line" != *=* ]]; then
            continue
        fi
        key="${line%%=*}"
        val="${line#*=}"
        key="$(echo "$key" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
        val="$(echo "$val" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^"//' -e 's/"$//' -e "s/^'//" -e "s/'$//")"
        if [[ "$key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]; then
            export "$key=$val"
        fi
    done < .env
}

# Push HEAD tree to a Space remote, but with README.md = frontmatter + project README.
# Uses a temp GIT_INDEX_FILE + commit-tree so the working tree and GitHub branch stay clean.
# Strips GitHub-only binaries (e.g. demo GIFs) β€” HF rejects non-Xet binaries on Space git push.
push_hf_space_commit() {
    local space_url="$1"
    local force_push="$2"
    local composed_readme="$3"
    local blob tree commit idx ec=0
    local stripped=0 path

    idx="$(mktemp)"
    export GIT_INDEX_FILE="$idx"
    if ! git read-tree HEAD; then
        unset GIT_INDEX_FILE
        rm -f "$idx"
        echo -e "${RED}❌ git read-tree HEAD failed.${RESET}"
        return 1
    fi

    # HF Hub pre-receive rejects large/non-Xet binaries. Demo assets are README-only on GitHub.
    while IFS= read -r path; do
        [ -n "$path" ] || continue
        if git rm --cached -f -- "$path" >/dev/null 2>&1; then
            echo -e "${DIM}  Stripped from Space tip (HF binary policy): ${path}${RESET}"
            stripped=$((stripped + 1))
        fi
    done < <(git ls-files -c -- 'demo/*' '*.gif' '*.mp4' '*.webm' '*.mov' 2>/dev/null)

    blob="$(git hash-object -w "$composed_readme")" || ec=$?
    if [ "$ec" -ne 0 ] || [ -z "$blob" ]; then
        unset GIT_INDEX_FILE
        rm -f "$idx"
        echo -e "${RED}❌ Could not hash composed README.${RESET}"
        return 1
    fi
    git update-index --cacheinfo "100644,${blob},README.md" || ec=$?
    if [ "$ec" -ne 0 ]; then
        unset GIT_INDEX_FILE
        rm -f "$idx"
        echo -e "${RED}❌ git update-index for README.md failed.${RESET}"
        return 1
    fi
    tree="$(git write-tree)" || ec=$?
    unset GIT_INDEX_FILE
    rm -f "$idx"
    if [ "$ec" -ne 0 ] || [ -z "$tree" ]; then
        echo -e "${RED}❌ git write-tree failed.${RESET}"
        return 1
    fi
    if [ "$stripped" -gt 0 ]; then
        echo -e "${DIM}  Removed ${stripped} binary path(s) from ephemeral Space tip (GitHub tree unchanged).${RESET}"
    fi

    # Orphan commit (no -p HEAD): a parented tip still packs GitHub history that
    # contains demo GIFs; HF pre-receive scans the whole pack, not only the tip tree.
    commit="$(git commit-tree "$tree" -m "$(cat <<'EOF'
publish(hf): Space snapshot with injected README frontmatter

Orphan tip for Hugging Face only β€” not merged to GitHub main.
EOF
)")" || ec=$?
    if [ "$ec" -ne 0 ] || [ -z "$commit" ]; then
        echo -e "${RED}❌ git commit-tree failed.${RESET}"
        return 1
    fi

    # Hard guards β€” catch stale in-memory setup.sh (option 8 after edit without restart).
    local parent_n
    parent_n="$(git rev-list --parents -n 1 "$commit" | awk '{print NF-1}')"
    if [ "$parent_n" != "0" ]; then
        echo -e "${RED}❌ Space tip is not orphan (parents=${parent_n}).${RESET}"
        echo -e "${YELLOW}  Exit setup.sh (0) and re-run ./setup.sh β€” option 8 was still using an old in-memory function.${RESET}"
        return 1
    fi
    if git rev-list --objects "$commit" | grep -E '(^|/)(demo/|.*\.(gif|mp4|webm|mov))( |$)' >/dev/null; then
        echo -e "${RED}❌ Space tip still reaches a binary demo asset β€” aborting push.${RESET}"
        git rev-list --objects "$commit" | grep -E '(^|/)(demo/|.*\.(gif|mp4|webm|mov))( |$)' | head -20
        return 1
    fi

    echo -e "${DIM}  Ephemeral orphan Space tip: ${commit:0:12} (parents=0; no demo binaries; README injected)${RESET}"
    # Always force: orphan tip cannot fast-forward Space main.
    echo -e "${DIM}  Using --force (orphan tip); GitHub main is untouched.${RESET}"
    if ! git push --force "$space_url" "${commit}:main"; then
        echo -e "${RED}❌ git push --force to Space failed.${RESET}"
        echo -e "${DIM}  Tip: hf auth login --force --add-to-git-credential ; token needs Write scope.${RESET}"
        return 1
    fi
    return 0
}

publish_hf_space() {
    load_dotenv
    local default_space="${HF_SPACE_ID:-hbauzan/llm-semantic-visualizer}"
    local force_push="${HF_SPACE_FORCE_PUSH:-1}"
    local frontmatter="${HF_SPACE_FRONTMATTER:-deploy/hf/space-frontmatter.yml}"

    echo -e "${YELLOW}${BOLD}--- Hugging Face Spaces Publisher (Docker Β· cpu-basic) ---${RESET}"
    echo -e "${DIM}  Defaults from .env β€” press Enter to accept.${RESET}"
    echo -e "${DIM}  Space: ${default_space}  Β·  force-push: ${force_push}${RESET}"
    echo -e "${DIM}  Frontmatter: ${frontmatter} (injected at push; GitHub README stays clean)${RESET}"
    if ! ensure_hf_cli; then
        read -p "Press Enter..."
        return
    fi
    if ! ensure_hf_auth; then
        read -p "Press Enter..."
        return
    fi

    if [ ! -f "$frontmatter" ]; then
        echo -e "${RED}❌ Missing Space frontmatter: ${frontmatter}${RESET}"
        echo -e "${DIM}  Expected deploy/hf/space-frontmatter.yml (sdk: docker, app_port: 7860).${RESET}"
        read -p "Press Enter..."
        return
    fi
    if [ ! -f scripts/compose_hf_space_readme.sh ]; then
        echo -e "${RED}❌ Missing scripts/compose_hf_space_readme.sh${RESET}"
        read -p "Press Enter..."
        return
    fi

    local space_raw
    read -p "Enter Space id [${default_space}]: " space_raw
    space_raw="${space_raw:-$default_space}"
    local space_id
    space_id="$(normalize_hf_space_id "$space_raw")"
    if [ -z "$space_id" ]; then
        echo -e "${RED}Space ID required.${RESET}"
        read -p "Press Enter..."
        return
    fi
    if ! validate_hf_space_id "$space_id"; then
        echo -e "${RED}❌ Invalid Space id: ${space_raw}${RESET}"
        echo -e "${RED}   Use namespace/name only, e.g. hbauzan/llm-semantic-visualizer${RESET}"
        echo -e "${DIM}   (You pasted a profile/URL; that is not a Space repository.)${RESET}"
        read -p "Press Enter..."
        return
    fi
    if [ "$space_id" != "$space_raw" ]; then
        echo -e "${CYAN}  Normalized to: ${BOLD}${space_id}${RESET}"
    fi

    # Prefer reusing an existing Space. `hf repos create` now returns 402 without PRO
    # even with --exist-ok, so never call create when the Space is already there.
    if hf spaces info "$space_id" &> /dev/null; then
        echo -e "  ${GREEN}βœ“ Space exists β€” skipping create (push-only).${RESET}"
        echo -e "${DIM}  https://huggingface.co/spaces/${space_id}${RESET}"
    else
        echo -e "${CYAN}β–Ά Space not found. Creating (sdk=docker, flavor=cpu-basic)…${RESET}"
        echo -e "${DIM}  Note: new Gradio/Docker Spaces require HF PRO since mid-2026.${RESET}"
        if ! hf repos create "$space_id" --type space --space-sdk docker --flavor cpu-basic --exist-ok; then
            if ! hf repos create "$space_id" --type space --space-sdk docker --exist-ok; then
                echo -e "${RED}❌ Cannot create Space (often HTTP 402 without PRO).${RESET}"
                echo -e "${YELLOW}  Reuse an existing Docker Space id, or subscribe: https://huggingface.co/pro${RESET}"
                read -p "Press Enter..."
                return
            fi
            echo -e "${YELLOW}⚠ Created without --flavor; set hardware to cpu-basic in Space Settings if needed.${RESET}"
        fi
    fi

    echo -e "${CYAN}Building production frontend bundle…${RESET}"
    npm run build || {
        echo -e "${RED}❌ Frontend build failed.${RESET}"
        read -p "Press Enter..."
        return
    }

    local composed
    composed="$(mktemp)"
    echo -e "${CYAN}Composing Space README (frontmatter + project README)…${RESET}"
    if ! bash scripts/compose_hf_space_readme.sh "$frontmatter" README.md "$composed"; then
        rm -f "$composed"
        echo -e "${RED}❌ README compose failed β€” aborting Space push.${RESET}"
        read -p "Press Enter..."
        return
    fi
    echo -e "  ${GREEN}βœ“ Composed README has sdk: docker + app_port: 7860${RESET}"

    local space_url="https://huggingface.co/spaces/${space_id}"
    echo -e "${CYAN}Pushing ephemeral tip β†’ ${space_url} (main)…${RESET}"
    echo -e "${DIM}  HF builds Docker from this tree (Dockerfile + injected README). GitHub README unchanged.${RESET}"

    # Space git history is independent of GitHub. Default force-push replaces the old
    # Space tree (e.g. predecessor app) with this repo β€” does NOT touch origin/main.
    if ! push_hf_space_commit "$space_url" "$force_push" "$composed"; then
        rm -f "$composed"
        read -p "Press Enter..."
        return
    fi
    rm -f "$composed"

    echo -e "${GREEN}${BOLD}βœ… Published.${RESET}"
    echo -e "  Space URL: ${CYAN}${space_url}${RESET}"
    echo -e "${DIM}  Build may take several minutes (torch CPU + model + vocab NPZ).${RESET}"
    read -p "Press Enter to return to menu..."
}

stop_services() {
    echo -e "${RED}${BOLD}Stopping background services...${RESET}"
    kill_stack
    echo -e "${GREEN}βœ… Services stopped.${RESET}"
    read -p "Press Enter to return to menu..."
}

view_logs() {
    if [ -f "$LOG_FILE" ]; then
        echo -e "${MAGENTA}${BOLD}πŸ“œ Mostrando ΓΊltimos logs del backend...${RESET}"
        tail -n 40 "$LOG_FILE" | sed \
            -e "s/INFO/${GREEN}INFO${RESET}/g" \
            -e "s/WARNING/${YELLOW}WARNING${RESET}/g" \
            -e "s/ERROR/${RED}ERROR${RESET}/g" \
            -e "s/200 OK/${GREEN}200 OK${RESET}/g"
    else
        echo -e "${RED}No log file found.${RESET}"
    fi
    read -p "Press Enter..."
}

while true; do
    show_menu
    echo -ne "${BOLD}Choose an option [0-11]: ${RESET}"
    read choice
    case $choice in
        1)
            deploy_and_start
            ;;
        2)
            start_bare_metal_backend
            ;;
        3)
            (cd backend && uv run python perform_tests.py)
            read -p "Press Enter..."
            ;;
        4)
            npx vitest run --reporter=verbose
            read -p "Press Enter..."
            ;;
        5)
            (cd backend && uv run python -m pytest -v -s)
            read -p "Press Enter..."
            ;;
        6)
            manage_vocab
            ;;
        7)
            build_hf_docker
            ;;
        8)
            publish_hf_space
            ;;
        9)
            view_logs
            ;;
        10)
            stop_services
            ;;
        11)
            select_embedding_model
            ;;
        0)
            exit_panel_keep_services
            ;;
        *)
            echo -e "${RED}Invalid choice.${RESET}"
            sleep 1
            ;;
    esac
done