File size: 58,640 Bytes
266eda8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
"""
GelPredict Multi-Computer Sync Manager
- Conflict-free merge: NEVER overwrites data
- Append-only sync: new records are merged in
- Safe deletes: requires explicit confirmation
- Cloud storage options: Dropbox, Google Drive, OneDrive, Git
- Backup before every sync
- Folder picker for easy setup
"""

from __future__ import annotations
import streamlit as st
import sqlite3
import pandas as pd
import shutil
from pathlib import Path
from datetime import datetime
import hashlib
import json
import subprocess
import platform
import os

ROOT = Path(__file__).resolve().parents[1]

# Sync configuration
SYNC_CONFIG_FILE = ROOT / "sync_config.json"
SYNC_BACKUP_DIR = ROOT / "sync_backups"
SYNC_BACKUP_DIR.mkdir(exist_ok=True)

# All databases to sync
DATABASES = {
    "lab_hydrogels": ROOT / "gelpredict.db",
    "lit_hydrogels": ROOT / "data" / "reference_db.sqlite",
    "lab_cellgrowth": ROOT / "data" / "cellgrowth_lab.sqlite",
    "lit_cellgrowth": ROOT / "data" / "cellgrowth_lit.sqlite",
    "lab_morphology": ROOT / "data" / "morphology_lab.sqlite",
    "lit_morphology": ROOT / "data" / "morphology_literature.sqlite",
}

# Tables to sync (append-only)
SYNC_TABLES = {
    "gelpredict.db": ["wells_master_v4", "reagents_per_well", "events_long", "gel_images", "plates_registry"],
    "reference_db.sqlite": ["literature_wells", "literature_images"],
    "cellgrowth_lab.sqlite": ["cell_runs", "cell_run_hydrogels", "cell_media_components", "cell_events", "cell_images"],
    "cellgrowth_lit.sqlite": ["lit_cell_runs", "lit_cell_run_hydrogels", "lit_media_components", "lit_cell_events", "lit_cell_images"],
    "morphology_lab.sqlite": ["morphology_observations", "morphology_images", "marker_staining"],
    "morphology_literature.sqlite": ["lit_morphology_observations", "lit_morphology_images", "lit_marker_staining"],
}

# ---------------- CSV Export Functions ----------------
def export_database_to_csv(db_path: Path, remote_root: Path) -> dict:
    """Export SQLite database tables to CSV files in the remote sync folder."""
    if not db_path.exists():
        return {"error": f"Database not found: {db_path}"}
    
    stats = {"exported": 0, "errors": []}
    db_name = db_path.stem  # e.g., "gelpredict" from "gelpredict.db"
    csv_dir = remote_root / f"{db_name}_csv"
    csv_dir.mkdir(parents=True, exist_ok=True)
    
    try:
        with sqlite3.connect(db_path) as conn:
            # Get all table names
            cursor = conn.execute("SELECT name FROM sqlite_master WHERE type='table';")
            tables = [row[0] for row in cursor.fetchall()]
            
            for table in tables:
                try:
                    # Export table to CSV
                    df = pd.read_sql_query(f"SELECT * FROM {table}", conn)
                    csv_path = csv_dir / f"{table}.csv"
                    df.to_csv(csv_path, index=False)
                    stats["exported"] += 1
                    st.caption(f"   πŸ“„ Exported {table}.csv ({len(df)} rows)")
                except Exception as e:
                    stats["errors"].append(f"{table}: {e}")
                    
    except Exception as e:
        stats["errors"].append(f"Database connection: {e}")
    
    return stats

# ---------------- Sync Configuration ----------------
def load_sync_config() -> dict:
    """Load sync configuration from JSON file."""
    # Check if running on Railway (cloud deployment)
    is_railway = os.getenv("RAILWAY_ENVIRONMENT") is not None
    
    if SYNC_CONFIG_FILE.exists() and not is_railway:
        with open(SYNC_CONFIG_FILE) as f:
            return json.load(f)
    
    # Default config - disable sync on Railway
    config = {
        "sync_method": "none",  # 'none' | 'dropbox' | 'gdrive' | 'onedrive' | 'git' | 'network_drive'
        "sync_folder": "",
        "last_sync": None,
        "computer_id": hashlib.md5(str(ROOT).encode()).hexdigest()[:8],  # Unique ID for this computer
        "is_railway": is_railway,
    }
    
    if is_railway:
        # Keep sync_method as "none" by default, user can choose cloud options
        config["railway_message"] = "Cloud sync available - use OneDrive API or manual upload/download"
    
    return config

def save_sync_config(config: dict):
    """Save sync configuration."""
    with open(SYNC_CONFIG_FILE, "w") as f:
        json.dump(config, f, indent=2)

# ---------------- Folder Picker ----------------
def open_folder_picker(title: str = "Select Sync Folder") -> str | None:
    """
    Open native folder picker dialog.
    Returns selected folder path or None if cancelled.
    
    Note: In cloud environments (like Railway), this will return None
    and users should use manual path entry instead.
    """
    # Check if we're in a cloud environment
    if is_cloud_environment():
        st.warning("⚠️ Folder picker not available in cloud environment. Please use manual path entry below.")
        return None
    
    system = platform.system()
    
    try:
        if system == "Darwin":  # macOS
            # Use AppleScript for folder picker
            script = f'''
            tell application "System Events"
                activate
                set folderPath to choose folder with prompt "{title}"
                return POSIX path of folderPath
            end tell
            '''
            result = subprocess.run(
                ["osascript", "-e", script],
                capture_output=True,
                text=True,
                timeout=300  # 5 minute timeout
            )
            if result.returncode == 0 and result.stdout.strip():
                return result.stdout.strip()
        
        elif system == "Windows":
            # Use PowerShell folder picker
            script = f'''
            Add-Type -AssemblyName System.Windows.Forms
            $folder = New-Object System.Windows.Forms.FolderBrowserDialog
            $folder.Description = "{title}"
            $folder.ShowNewFolderButton = $true
            if ($folder.ShowDialog() -eq "OK") {{
                Write-Output $folder.SelectedPath
            }}
            '''
            result = subprocess.run(
                ["powershell", "-Command", script],
                capture_output=True,
                text=True,
                timeout=300
            )
            if result.returncode == 0 and result.stdout.strip():
                return result.stdout.strip()
        
        elif system == "Linux":
            # Try zenity (common on Linux) - but only if not in cloud
            try:
                result = subprocess.run(
                    ["zenity", "--file-selection", "--directory", f"--title={title}"],
                    capture_output=True,
                    text=True,
                    timeout=300
                )
                if result.returncode == 0 and result.stdout.strip():
                    return result.stdout.strip()
            except FileNotFoundError:
                st.warning("⚠️ zenity not available. Please use manual path entry below.")
                return None
    
    except Exception as e:
        st.error(f"Folder picker error: {e}")
    
    return None

def is_cloud_environment() -> bool:
    """
    Detect if we're running in a cloud environment (Railway, Heroku, etc.)
    """
    # Check for common cloud environment variables
    cloud_indicators = [
        "RAILWAY_ENVIRONMENT",  # Railway
        "HEROKU_APP_NAME",      # Heroku
        "VERCEL",               # Vercel
        "AWS_LAMBDA_FUNCTION_NAME",  # AWS Lambda
        "GOOGLE_CLOUD_PROJECT", # Google Cloud
        "AZURE_FUNCTIONS_ENVIRONMENT",  # Azure
    ]
    
    return any(os.getenv(indicator) for indicator in cloud_indicators)

def check_onedrive_sync_status(sync_folder: str) -> dict:
    """
    Check if OneDrive is actively syncing the specified folder.
    Returns status information for user feedback.
    """
    import os
    import time
    
    status = {
        "onedrive_running": False,
        "folder_syncing": False,
        "last_sync_time": None,
        "sync_status": "unknown",
        "recommendations": []
    }
    
    try:
        # Check if OneDrive process is running
        system = platform.system()
        if system == "Windows":
            import subprocess
            try:
                result = subprocess.run(['tasklist', '/FI', 'IMAGENAME eq OneDrive.exe'], 
                                      capture_output=True, text=True, timeout=5)
                status["onedrive_running"] = "OneDrive.exe" in result.stdout
            except:
                status["onedrive_running"] = False
        elif system == "Darwin":  # macOS
            import subprocess
            try:
                result = subprocess.run(['pgrep', '-f', 'OneDrive'], 
                                      capture_output=True, text=True, timeout=5)
                status["onedrive_running"] = bool(result.stdout.strip())
            except:
                status["onedrive_running"] = False
        
        # Check folder sync status
        if os.path.exists(sync_folder):
            # Check if folder is in OneDrive sync directory
            sync_folder_path = Path(sync_folder)
            if "OneDrive" in str(sync_folder_path):
                status["folder_syncing"] = True
                status["sync_status"] = "configured"
                
                # Check last modification time
                try:
                    stat = sync_folder_path.stat()
                    status["last_sync_time"] = time.ctime(stat.st_mtime)
                except:
                    pass
            else:
                status["sync_status"] = "not_in_onedrive"
                status["recommendations"].append("Move sync folder to OneDrive directory")
        else:
            status["sync_status"] = "folder_not_found"
            status["recommendations"].append("Create sync folder first")
            
        # Generate recommendations
        if not status["onedrive_running"]:
            status["recommendations"].append("Start OneDrive application")
        
        if status["onedrive_running"] and status["folder_syncing"]:
            status["sync_status"] = "ready"
            
    except Exception as e:
        status["sync_status"] = "error"
        status["recommendations"].append(f"Error checking status: {e}")
    
    return status

def detect_onedrive_path() -> str | None:
    """
    Auto-detect OneDrive folder path on this computer.
    Returns None if not found.
    """
    import os
    system = platform.system()
    home = Path.home()
    
    # Common OneDrive locations
    candidates = [
        home / "OneDrive",
        home / "OneDrive - Personal",
        home / "OneDrive - Old Dominion University",
    ]
    
    # Windows-specific
    if system == "Windows":
        candidates.extend([
            Path(f"C:/Users/{home.name}/OneDrive"),
            Path(f"C:/Users/{home.name}/OneDrive - Personal"),
        ])
    
    # Check each candidate
    for path in candidates:
        if path.exists() and path.is_dir():
            # Use proper path joining for the platform
            if system == "Windows":
                return os.path.join(str(path), "GelPredict_Sync")
            else:
                return str(path / "GelPredict_Sync")
    
    return None

# ---------------- Backup Before Sync ----------------
def create_pre_sync_backup(db_path: Path) -> Path:
    """Create timestamped backup before syncing."""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    backup_name = f"{db_path.stem}_presync_{timestamp}.sqlite"
    backup_path = SYNC_BACKUP_DIR / backup_name
    shutil.copy2(db_path, backup_path)
    return backup_path

# ---------------- Conflict-Free Merge ----------------
def get_table_primary_key(con: sqlite3.Connection, table: str) -> str | None:
    """Get primary key column name for a table."""
    pragma = con.execute(f"PRAGMA table_info({table})").fetchall()
    for row in pragma:
        if row[5] == 1:  # pk column is index 5 in pragma result
            return row[1]  # name is index 1
    return None

def merge_tables_append_only(local_db: Path, remote_db: Path, tables: list[str]) -> dict:
    """
    Merge remote database into local using append-only strategy.
    NEVER overwrites existing records.
    Returns merge statistics.
    """
    stats = {"added": 0, "skipped": 0, "errors": []}
    
    local_con = sqlite3.connect(str(local_db))
    local_con.row_factory = sqlite3.Row
    remote_con = sqlite3.connect(str(remote_db))
    remote_con.row_factory = sqlite3.Row
    
    try:
        for table in tables:
            # Check if table exists in both databases
            local_tables = {r[0] for r in local_con.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()}
            remote_tables = {r[0] for r in remote_con.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()}
            
            if table not in local_tables or table not in remote_tables:
                stats["skipped"] += 1
                continue
            
            # Get primary key
            pk = get_table_primary_key(local_con, table)
            if not pk:
                stats["errors"].append(f"{table}: No primary key found")
                continue
            
            # Get all remote records
            remote_df = pd.read_sql_query(f"SELECT * FROM {table}", remote_con)
            
            if remote_df.empty:
                continue
            
            # Get existing local primary keys
            local_pks = {r[0] for r in local_con.execute(f"SELECT {pk} FROM {table}").fetchall()}
            
            # Insert only new records (append-only)
            for _, row in remote_df.iterrows():
                row_pk = row[pk]
                if row_pk not in local_pks:
                    # Insert new record
                    cols = list(row.index)
                    vals = [row[c] for c in cols]
                    placeholders = ",".join(["?"] * len(cols))
                    try:
                        local_con.execute(f"INSERT INTO {table}({','.join(cols)}) VALUES({placeholders})", vals)
                        stats["added"] += 1
                    except Exception as e:
                        stats["errors"].append(f"{table}.{row_pk}: {e}")
                else:
                    stats["skipped"] += 1
        
        local_con.commit()
    
    finally:
        local_con.close()
        remote_con.close()
    
    return stats

# ---------------- Image Sync ----------------
def sync_images(local_folder: Path, remote_folder: Path) -> dict:
    """
    Sync images from remote to local (append-only).
    Compares by filename and SHA256 hash.
    """
    stats = {"added": 0, "skipped": 0, "errors": []}
    
    if not remote_folder.exists():
        return stats
    
    local_folder.mkdir(parents=True, exist_ok=True)
    
    # Get local images and their hashes
    local_images = {}
    for img in local_folder.glob("*"):
        if img.is_file():
            local_images[img.name] = _hash_file(img)
    
    # Copy new images from remote
    for remote_img in remote_folder.glob("*"):
        if remote_img.is_file():
            remote_hash = _hash_file(remote_img)
            
            if remote_img.name not in local_images:
                # New image - copy it
                shutil.copy2(remote_img, local_folder / remote_img.name)
                stats["added"] += 1
            elif local_images[remote_img.name] != remote_hash:
                # Same name, different content - keep both
                new_name = f"{remote_img.stem}_remote_{remote_hash[:8]}{remote_img.suffix}"
                shutil.copy2(remote_img, local_folder / new_name)
                stats["added"] += 1
            else:
                # Identical file
                stats["skipped"] += 1
    
    return stats

def _hash_file(path: Path) -> str:
    """Compute SHA256 hash of a file."""
    sha256 = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(8192), b""):
            sha256.update(chunk)
    return sha256.hexdigest()

# ---------------- Sync Methods ----------------
def sync_from_folder(remote_root: Path, config: dict = None) -> dict:
    """
    Sync from a remote folder (Dropbox, Google Drive, network drive, etc.).
    Merges databases and images using append-only strategy.
    """
    total_stats = {"databases": {}, "images": {}, "errors": []}
    
    # Check if remote folder exists and is accessible
    try:
        if not remote_root.exists():
            total_stats["errors"].append(f"Remote folder not found: {remote_root}")
            return total_stats
        
        if not remote_root.is_dir():
            total_stats["errors"].append(f"Remote path is not a directory: {remote_root}")
            return total_stats
            
        # Check read permissions
        if not os.access(remote_root, os.R_OK):
            total_stats["errors"].append(f"No read permission for remote folder: {remote_root}")
            return total_stats
            
    except Exception as e:
        total_stats["errors"].append(f"Error accessing remote folder: {e}")
        return total_stats
    
    # 1. Backup local databases first
    st.info("πŸ“¦ Creating pre-sync backups...")
    for name, db_path in DATABASES.items():
        if db_path.exists():
            backup_path = create_pre_sync_backup(db_path)
            st.caption(f"Backed up {name} β†’ {backup_path.name}")
    
    # 2. Sync databases
    st.info("πŸ”„ Merging databases (append-only)...")
    for name, local_db in DATABASES.items():
        remote_db = remote_root / local_db.relative_to(ROOT)
        
        if not remote_db.exists():
            st.warning(f"⚠️ Remote database not found: {remote_db}")
            continue
        
        if not local_db.exists():
            # First time - just copy
            local_db.parent.mkdir(parents=True, exist_ok=True)
            shutil.copy2(remote_db, local_db)
            total_stats["databases"][name] = {"added": "all", "skipped": 0}
            st.success(f"βœ… Initialized {name} from remote")
        else:
            # Merge
            db_file_name = local_db.name
            tables = SYNC_TABLES.get(db_file_name, [])
            stats = merge_tables_append_only(local_db, remote_db, tables)
            total_stats["databases"][name] = stats
            
            if stats["added"] > 0:
                st.success(f"βœ… {name}: Added {stats['added']} records, skipped {stats['skipped']}")
            else:
                st.info(f"ℹ️ {name}: No new records (skipped {stats['skipped']})")
            
            if stats["errors"]:
                with st.expander(f"⚠️ Errors in {name}"):
                    for err in stats["errors"]:
                        st.error(err)
        
        # Export CSV files for this database (from local after pull, if enabled)
        if config.get("export_csv", True):
            st.caption(f"πŸ“„ Exporting CSV files for {name}...")
            csv_stats = export_database_to_csv(local_db, ROOT)
            if csv_stats.get("exported", 0) > 0:
                st.success(f"βœ… Exported {csv_stats['exported']} CSV files for {name}")
            if csv_stats.get("errors"):
                for error in csv_stats["errors"]:
                    st.warning(f"⚠️ CSV export warning: {error}")
    
    # 3. Sync images
    st.info("πŸ–ΌοΈ Syncing images (append-only)...")
    image_folders = [
        "media/images/lab_hydrogels",
        "media/images/literature_hydrogels",
        "media/images/lab_cells",
        "media/images/literature_cells",
        "media/images/lab_morphology",
        "media/images/literature_morphology",
    ]
    
    for folder in image_folders:
        local_folder = ROOT / folder
        remote_folder = remote_root / folder
        
        img_stats = sync_images(local_folder, remote_folder)
        total_stats["images"][folder] = img_stats
        
        if img_stats["added"] > 0:
            st.success(f"βœ… {folder}: Added {img_stats['added']} images")
    
    return total_stats

def push_to_folder(remote_root: Path, config: dict = None) -> dict:
    """
    Push local data to remote folder (append-only).
    Remote will merge local changes without overwriting.
    """
    total_stats = {"databases": {}, "images": {}, "errors": []}
    
    st.info("πŸ“€ Pushing local data to remote (append-only)...")
    
    # 1. Ensure remote directory exists
    remote_root.mkdir(parents=True, exist_ok=True)
    
    # 2. For each database, merge local β†’ remote
    for name, local_db in DATABASES.items():
        if not local_db.exists():
            continue
        
        remote_db = remote_root / local_db.relative_to(ROOT)
        remote_db.parent.mkdir(parents=True, exist_ok=True)
        
        if not remote_db.exists():
            # First time - just copy
            st.info(f"πŸ“‹ Copying {local_db.name}...")
            st.caption(f"   FROM: `{local_db}`")
            st.caption(f"   TO: `{remote_db}`")
            
            shutil.copy2(local_db, remote_db)
            
            # Verify it was created
            if remote_db.exists():
                size = remote_db.stat().st_size / 1024
                st.success(f"βœ… Created {name} ({size:.1f} KB)")
                st.success(f"   πŸ“ Location: `{remote_db}`")
            else:
                st.error(f"❌ Failed to create {remote_db}")
            
            total_stats["databases"][name] = {"added": "all"}
        else:
            # Merge local into remote
            db_file_name = local_db.name
            tables = SYNC_TABLES.get(db_file_name, [])
            stats = merge_tables_append_only(remote_db, local_db, tables)
            total_stats["databases"][name] = stats
            
            if stats["added"] > 0:
                st.success(f"βœ… {name}: Pushed {stats['added']} records")
        
        # Export CSV files for this database (if enabled)
        if config.get("export_csv", True):
            st.caption(f"πŸ“„ Exporting CSV files for {name}...")
            csv_stats = export_database_to_csv(remote_db, remote_root)
            if csv_stats.get("exported", 0) > 0:
                st.success(f"βœ… Exported {csv_stats['exported']} CSV files for {name}")
            if csv_stats.get("errors"):
                for error in csv_stats["errors"]:
                    st.warning(f"⚠️ CSV export warning: {error}")
    
    # 3. Push images
    image_folders = [
        "media/images/lab_hydrogels",
        "media/images/literature_hydrogels",
        "media/images/lab_cells",
        "media/images/literature_cells",
        "media/images/lab_morphology",
        "media/images/literature_morphology",
    ]
    
    for folder in image_folders:
        local_folder = ROOT / folder
        remote_folder = remote_root / folder
        
        if local_folder.exists():
            img_stats = sync_images(remote_folder, local_folder)
            total_stats["images"][folder] = img_stats
            
            if img_stats["added"] > 0:
                st.success(f"βœ… {folder}: Pushed {img_stats['added']} images")
    
    return total_stats

# ---------------- Safe Delete with Confirmation ----------------
def show_delete_interface():
    """Show interface for deleting records with multi-step confirmation."""
    st.header("πŸ—‘οΈ Safe Delete (with confirmation)")
    st.warning("⚠️ Deletes are permanent and will sync to other computers!")
    
    # Select database
    db_choice = st.selectbox("Select Database", list(DATABASES.keys()))
    db_path = DATABASES[db_choice]
    
    if not db_path.exists():
        st.info(f"Database {db_path.name} doesn't exist yet.")
        return
    
    # Select table
    con = sqlite3.connect(str(db_path))
    tables = [r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").fetchall()]
    con.close()
    
    table = st.selectbox("Select Table", tables)
    
    # Load records
    con = sqlite3.connect(str(db_path))
    df = pd.read_sql_query(f"SELECT * FROM {table} LIMIT 500", con)
    con.close()
    
    if df.empty:
        st.info(f"No records in {table}")
        return
    
    st.dataframe(df, use_container_width=True, height=300)
    
    # Get primary key column
    pk_cols = [c for c in df.columns if 'id' in c.lower()]
    if not pk_cols:
        st.error("Cannot identify primary key column")
        return
    
    pk_col = pk_cols[0]
    
    # Select record to delete
    st.markdown("---")
    st.subheader("⚠️ Delete Record")
    
    record_id = st.selectbox(
        "Select Record to Delete",
        [""] + df[pk_col].tolist(),
        format_func=lambda x: f"{x[:30]}..." if len(str(x)) > 30 else str(x) if x else "Select record"
    )
    
    if record_id:
        # Show record details
        record = df[df[pk_col] == record_id].iloc[0]
        st.json(record.to_dict())
        
        st.markdown("---")
        st.error("🚨 PERMANENT DELETE - This action cannot be undone!")
        
        # Multi-step confirmation
        col1, col2 = st.columns(2)
        with col1:
            confirm1 = st.checkbox("I understand this is permanent")
        with col2:
            confirm2 = st.checkbox("I want to delete this record")
        
        type_to_confirm = st.text_input(
            "Type DELETE to confirm",
            help="Type the word DELETE in all caps"
        )
        
        if confirm1 and confirm2 and type_to_confirm == "DELETE":
            if st.button("πŸ—‘οΈ DELETE RECORD", type="primary"):
                try:
                    # Create backup first
                    backup = create_pre_sync_backup(db_path)
                    st.info(f"Backup created: {backup.name}")
                    
                    # Perform delete
                    con = sqlite3.connect(str(db_path))
                    con.execute(f"DELETE FROM {table} WHERE {pk_col} = ?", (record_id,))
                    con.commit()
                    rows_deleted = con.total_changes
                    con.close()
                    
                    st.success(f"βœ… Deleted {rows_deleted} row(s)")
                    st.balloons()
                    
                    # Log deletion
                    with open(ROOT / "deletion_log.txt", "a") as f:
                        f.write(f"{datetime.now().isoformat()} | {db_choice} | {table} | {pk_col}={record_id}\n")
                    
                    st.rerun()
                except Exception as e:
                    st.error(f"❌ Delete failed: {e}")
        else:
            st.caption("Complete all confirmations above to enable delete button")

# ---------------- UI ----------------
def show_sync_app():
    st.title("πŸ”„ GelPredict Multi-Computer Sync Manager")
    st.caption("Conflict-free data merging across computers β€’ Append-only β€’ Never overwrites")
    
    # Cloud environment notice
    if is_cloud_environment():
        st.info("🌐 **Cloud Environment**: You're running GelPredict on a cloud platform (Railway, etc.). Folder picker dialogs are not available - please use manual path entry instead.")
    
    # Railway-specific sync notice
    config = load_sync_config()
    if config.get("is_railway"):
        if config.get("sync_method") in ["onedrive_api", "manual_upload", "cloud_database"]:
            st.success("πŸš‚ **Railway Cloud Sync**: Cloud sync is enabled! Choose your preferred sync method below.")
        else:
            st.info("πŸš‚ **Railway Deployment**: Cloud sync is available! Configure OneDrive API, manual upload/download, or cloud database sync.")
    
    # OneDrive sync status check (for local sync methods)
    if config.get("sync_method") in ["onedrive", "dropbox", "gdrive"] and config.get("sync_folder"):
        with st.expander("πŸ” OneDrive Sync Status", expanded=False):
            status = check_onedrive_sync_status(config["sync_folder"])
            
            if status["sync_status"] == "ready":
                st.success("βœ… **OneDrive Ready**: Sync folder is properly configured and OneDrive is running")
                if status["last_sync_time"]:
                    st.caption(f"πŸ“… Last sync: {status['last_sync_time']}")
            elif status["sync_status"] == "configured":
                st.warning("⚠️ **OneDrive Configured**: Folder is in OneDrive but OneDrive app may not be running")
                st.caption("πŸ’‘ Make sure OneDrive is running and syncing")
            elif status["sync_status"] == "not_in_onedrive":
                st.error("❌ **Not in OneDrive**: Sync folder is not in OneDrive directory")
                st.caption("πŸ’‘ Move your sync folder to OneDrive for automatic cloud sync")
            elif status["sync_status"] == "folder_not_found":
                st.error("❌ **Folder Not Found**: Sync folder does not exist")
                st.caption("πŸ’‘ Create the sync folder first")
            else:
                st.info("ℹ️ **Status Unknown**: Could not determine OneDrive sync status")
            
            if status["recommendations"]:
                st.markdown("**Recommendations:**")
                for rec in status["recommendations"]:
                    st.markdown(f"β€’ {rec}")
    
    # Sidebar: Sync status
    st.sidebar.markdown("### πŸ’» Computer ID")
    st.sidebar.code(config["computer_id"])
    st.sidebar.caption("Unique ID for this computer")
    
    if config.get("last_sync"):
        st.sidebar.markdown("### πŸ• Last Sync")
        st.sidebar.info(config["last_sync"])
    
    st.sidebar.markdown("---")
    
    # Main tabs - show cloud sync options on Railway
    if config.get("is_railway"):
        if config.get("sync_method") in ["onedrive_api", "manual_upload", "cloud_database"]:
            tab1, tab2, tab3, tab4 = st.tabs(["βš™οΈ Setup", "⬇️ Pull (Sync In)", "⬆️ Push (Sync Out)", "πŸ—‘οΈ Safe Delete"])
        else:
            tab1, tab2, tab3, tab4 = st.tabs(["βš™οΈ Setup", "☁️ Cloud Sync", "☁️ Cloud Sync", "☁️ Cloud Sync"])
    else:
        tab1, tab2, tab3, tab4 = st.tabs(["βš™οΈ Setup", "⬇️ Pull (Sync In)", "⬆️ Push (Sync Out)", "πŸ—‘οΈ Safe Delete"])
    
    # ===== SETUP TAB =====
    with tab1:
        st.header("βš™οΈ Sync Setup")
        st.markdown("Configure how you want to sync data across computers")
        
        # Railway-specific sync options
        if config.get("is_railway") or config.get("sync_method") in ["railway_cloud", "railway_disabled"]:
            # Map railway_cloud to none for the radio button
            current_method = config.get("sync_method", "none")
            if current_method in ["railway_cloud", "railway_disabled"]:
                current_method = "none"
            
            # Ensure current method is valid
            valid_methods = ["none", "onedrive_api", "manual_upload", "cloud_database"]
            if current_method not in valid_methods:
                current_method = "none"
            
            sync_method = st.radio(
                "Sync Method",
                valid_methods,
                index=valid_methods.index(current_method),
                format_func=lambda x: {
                    "none": "❌ No Sync",
                    "onedrive_api": "☁️ OneDrive API (Cloud)",
                    "manual_upload": "πŸ“€ Manual Upload/Download",
                    "cloud_database": "πŸ—„οΈ Cloud Database"
                }[x]
            )
        else:
            # Ensure current method is valid for local sync
            current_method = config.get("sync_method", "none")
            valid_methods = ["none", "dropbox", "gdrive", "onedrive", "network_drive", "git"]
            if current_method not in valid_methods:
                current_method = "none"
            
            sync_method = st.radio(
                "Sync Method",
                valid_methods,
                index=valid_methods.index(current_method),
                format_func=lambda x: {
                    "none": "❌ No Sync (Local Only)",
                    "dropbox": "πŸ“¦ Dropbox",
                    "gdrive": "☁️ Google Drive",
                    "onedrive": "☁️ OneDrive",
                    "network_drive": "πŸ–₯️ Network Drive",
                    "git": "πŸ”§ Git (Advanced)"
                }[x]
            )
        
        # Cloud sync configuration
        if sync_method == "onedrive_api":
            st.markdown("### ☁️ OneDrive API Configuration")
            st.info("πŸš€ **OneDrive API Sync**: Direct cloud-to-cloud sync using Microsoft Graph API")
            
            st.markdown("**Setup Steps:**")
            st.markdown("""
            1. **Register App**: Go to [Azure Portal](https://portal.azure.com) β†’ App registrations β†’ New registration
            2. **Get Credentials**: Copy Application (client) ID and create a client secret
            3. **Set Permissions**: Add Microsoft Graph API permissions (Files.ReadWrite)
            4. **Enter Credentials**: Fill in the fields below
            """)
            
            client_id = st.text_input("Application (Client) ID", placeholder="12345678-1234-1234-1234-123456789012")
            client_secret = st.text_input("Client Secret", type="password", placeholder="Enter your client secret")
            tenant_id = st.text_input("Directory (Tenant) ID", placeholder="12345678-1234-1234-1234-123456789012")
            # Platform-appropriate path placeholder
            import os
            if os.name == 'nt':  # Windows
                folder_placeholder = "\\GelPredict_Sync"
                folder_help = "Path within your OneDrive root (Windows style with backslashes)"
            else:  # macOS/Linux
                folder_placeholder = "/GelPredict_Sync"
                folder_help = "Path within your OneDrive root (Unix style with forward slashes)"
            
            folder_path = st.text_input("OneDrive Folder Path", placeholder=folder_placeholder, help=folder_help)
            
            if client_id and client_secret and tenant_id:
                st.success("βœ… Configuration complete! Click 'Test Connection' below.")
                
        elif sync_method == "manual_upload":
            st.markdown("### πŸ“€ Manual Upload/Download")
            st.info("πŸ’‘ **Manual Sync**: Upload/download database files manually")
            
            st.markdown("**How it works:**")
            st.markdown("""
            1. **Download**: Export your database files from Railway
            2. **Transfer**: Upload to your OneDrive/cloud storage
            3. **Import**: Download and import on other computers
            4. **Sync**: Repeat as needed
            """)
            
            st.markdown("**Benefits:**")
            st.markdown("- βœ… Works with any cloud storage")
            st.markdown("- βœ… No API setup required")
            st.markdown("- βœ… Full control over sync timing")
            st.markdown("- βœ… Works offline")
            
        elif sync_method == "cloud_database":
            st.markdown("### πŸ—„οΈ Cloud Database Configuration")
            st.info("🌐 **Cloud Database**: Connect to a remote database for real-time sync")
            
            st.markdown("**Supported Databases:**")
            st.markdown("- PostgreSQL (Railway, Supabase, etc.)")
            st.markdown("- MySQL (PlanetScale, etc.)")
            st.markdown("- SQLite (Cloud storage)")
            
            db_type = st.selectbox("Database Type", ["postgresql", "mysql", "sqlite"])
            db_url = st.text_input("Database URL", placeholder="postgresql://user:pass@host:port/dbname", type="password")
            
            if db_url:
                st.success("βœ… Database URL configured! Test connection below.")
                
        elif sync_method not in ["none", "railway_disabled"]:
            st.markdown("### Sync Folder Location")
            st.caption("This folder should be in your cloud storage (OneDrive, Dropbox, Google Drive, etc.)")
            
            # Auto-detect OneDrive for convenience
            detected_path = detect_onedrive_path() if sync_method == "onedrive" else None
            
            # Current sync folder (from config or detected)
            current_folder = config.get("sync_folder", detected_path or "")
            
            # Check if folder picker was just used
            if st.session_state.get("open_picker"):
                # Skip folder picker on Railway
                if config.get("is_railway") or config.get("sync_method") == "railway_disabled":
                    st.info("πŸš‚ **Railway Environment**: Sync is disabled, folder picker not needed.")
                    st.session_state["open_picker"] = False
                elif is_cloud_environment():
                    st.info("🌐 **Cloud Environment Detected**")
                    st.warning("⚠️ Folder picker is not available in cloud environments (Railway, etc.)")
                    st.info("πŸ’‘ **Please use manual path entry below instead.**")
                    st.caption("Enter the full path to your OneDrive/cloud storage folder manually.")
                    st.session_state["open_picker"] = False
                else:
                    st.info("πŸ” Opening folder picker dialog...")
                    st.caption("Select your OneDrive/cloud storage folder in the dialog that appears")
                    
                    picked_folder = open_folder_picker(f"Select {sync_method.upper()} Sync Folder")
                    
                    if picked_folder:
                        st.session_state["picked_sync_folder"] = picked_folder
                        st.success(f"βœ… Selected: {picked_folder}")
                        st.session_state["open_picker"] = False
                        st.rerun()
                    else:
                        st.warning("No folder selected (picker cancelled)")
                        st.session_state["open_picker"] = False
            
            # Determine default value (picked folder takes precedence, then detected path)
            if st.session_state.get("use_detected_path", False):
                default_folder = detected_path or ""
                st.session_state["use_detected_path"] = False  # Reset flag
            else:
                default_folder = st.session_state.get("picked_sync_folder", current_folder or "")
            
            # Debug info
            if default_folder:
                st.caption(f"πŸ” Default folder: `{default_folder}`")
            
            # Display path input with browse button
            col_path, col_btn = st.columns([3, 1])
            with col_path:
                sync_folder = st.text_input(
                    "Sync Folder Path",
                    value=default_folder,
                    help="Click 'Browse' to select folder or paste path directly",
                    key="sync_folder_input"
                )
            with col_btn:
                # Disable browse button on Railway
                if config.get("is_railway") or config.get("sync_method") == "railway_disabled":
                    st.button("πŸ“ Browse...", use_container_width=True, disabled=True, help="Browse disabled on Railway")
                else:
                    if st.button("πŸ“ Browse...", use_container_width=True, help="Open folder picker"):
                        st.session_state["open_picker"] = True
                        st.rerun()
            
            # Option to create subfolder
            use_subfolder = st.checkbox(
                "πŸ“ Create 'GelPredict_Sync' subfolder",
                value=True,
                help="Recommended - keeps sync data organized in a dedicated subfolder"
            )
            
            # Option to export CSV files
            export_csv = st.checkbox(
                "πŸ“„ Export CSV files",
                value=True,
                help="Export database tables as CSV files for easier sharing and Excel analysis"
            )
            
            if use_subfolder and sync_folder:
                # Use proper path joining for the platform
                import os
                if os.name == 'nt':  # Windows
                    actual_sync_path = os.path.join(sync_folder, "GelPredict_Sync")
                else:  # macOS/Linux
                    actual_sync_path = Path(sync_folder) / "GelPredict_Sync"
                st.caption(f"πŸ“‚ Actual sync location: `{actual_sync_path}`")
            else:
                actual_sync_path = Path(sync_folder) if sync_folder else None
                st.caption(f"πŸ“‚ Files will sync directly to: `{sync_folder}`")
            
            # Auto-detect suggestion
            if sync_method == "onedrive" and detected_path and sync_folder != detected_path:
                st.info(f"πŸ’‘ OneDrive detected at: `{detected_path}`")
                col_use, col_copy = st.columns(2)
                with col_use:
                    # Disable on Railway
                    if config.get("is_railway") or config.get("sync_method") == "railway_disabled":
                        st.button("✨ Use Detected Path", disabled=True, help="Disabled on Railway")
                    else:
                        if st.button("✨ Use Detected Path"):
                            st.session_state["picked_sync_folder"] = detected_path
                            st.session_state["use_detected_path"] = True
                            st.rerun()
                with col_copy:
                    if st.button("πŸ“‹ Copy to Clipboard"):
                        st.write("Copy this path and paste it in the text field below:")
                        st.code(detected_path)
                
                # Direct path input as fallback
                st.markdown("**Or enter the path directly:**")
                direct_path = st.text_input(
                    "Direct Path Entry", 
                    value=detected_path,
                    help="Enter the sync folder path directly",
                    key="direct_path_input"
                )
                if direct_path and direct_path != sync_folder:
                    st.session_state["picked_sync_folder"] = direct_path
                    st.success(f"βœ… Path set: `{direct_path}`")
                    st.rerun()
            
            # Test folder access
            if sync_folder:
                test_path = Path(sync_folder)
                col_test, col_create = st.columns(2)
                
                with col_test:
                    if st.button("πŸ” Test Access", use_container_width=True):
                        if test_path.exists():
                            st.success(f"βœ… Folder exists and is accessible")
                            # Show contents
                            try:
                                contents = list(test_path.iterdir())[:10]
                                if contents:
                                    st.caption(f"Contains {len(list(test_path.iterdir()))} items")
                                else:
                                    st.caption("Folder is empty (ready for first sync)")
                            except Exception:
                                pass
                        else:
                            st.warning(f"⚠️ Folder doesn't exist yet")
                
                with col_create:
                    if not test_path.exists():
                        if st.button("πŸ“ Create Folder", type="primary", use_container_width=True):
                            try:
                                test_path.mkdir(parents=True, exist_ok=True)
                                st.success(f"βœ… Created sync folder!")
                                st.balloons()
                            except Exception as e:
                                st.error(f"Failed to create folder: {e}")
            
            # Save configuration
            if st.button("πŸ’Ύ Save Sync Configuration", type="primary"):
                # Validate path first
                if not sync_folder or sync_folder.strip() == "":
                    st.error("❌ Please enter or select a sync folder path")
                elif ".Trash" in str(sync_folder):
                    st.error("❌ Cannot sync to Trash folder! Please select a valid folder.")
                    st.warning("πŸ’‘ Tip: Select your OneDrive folder, not Trash")
                else:
                    # Determine final sync path
                    final_sync_path = str(actual_sync_path) if use_subfolder and sync_folder else sync_folder
                    
                    config["sync_method"] = sync_method
                    config["sync_folder"] = final_sync_path
                    config["use_subfolder"] = use_subfolder
                    config["export_csv"] = export_csv
                    save_sync_config(config)
                    st.success("βœ… Sync configuration saved!")
                    st.success(f"πŸ“ Sync location: `{final_sync_path}`")
        
        # Instructions
        st.markdown("---")
        st.markdown("### πŸ“˜ How It Works")
        st.info("""
        **Append-Only Merge Strategy:**
        - βœ… New records from remote are added to local
        - βœ… Existing records are never overwritten
        - βœ… Both computers keep all data
        - βœ… No conflicts possible!
        
        **Workflow:**
        1. Computer A: Enter data β†’ Push to sync folder
        2. Computer B: Pull from sync folder β†’ Gets Computer A's data
        3. Computer B: Enter more data β†’ Push to sync folder
        4. Computer A: Pull from sync folder β†’ Gets Computer B's data
        
        **Result:** Both computers have all data from both!
        """)
    
    # ===== PULL TAB =====
    with tab2:
        if config.get("is_railway") and config.get("sync_method") == "manual_upload":
            st.header("⬇️ Download Data (Manual Sync)")
            st.info("πŸ“€ **Manual Download**: Download database files to sync with your local computer or OneDrive")
            
            # Create downloadable files
            st.markdown("### πŸ“₯ Download Database Files")
            
            # Create a zip file with all databases
            import zipfile
            import io
            
            zip_buffer = io.BytesIO()
            with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
                for name, db_path in DATABASES.items():
                    if db_path.exists():
                        zip_file.write(db_path, f"{name}.sqlite")
                        st.write(f"βœ… {name}: {db_path.stat().st_size / 1024:.1f} KB")
                    else:
                        st.write(f"⚠️ {name}: Not found")
            
            zip_buffer.seek(0)
            
            st.download_button(
                label="πŸ“¦ Download All Databases (ZIP)",
                data=zip_buffer.getvalue(),
                file_name=f"GelPredict_Databases_{datetime.now().strftime('%Y%m%d_%H%M%S')}.zip",
                mime="application/zip",
                use_container_width=True
            )
            
            st.markdown("### πŸ“‹ Instructions")
            st.markdown("""
            1. **Download** the ZIP file above
            2. **Extract** to your local computer
            3. **Upload** to your OneDrive folder
            4. **Import** into your local GelPredict installation
            5. **Sync** with other computers using local OneDrive sync
            """)
            
        elif config.get("is_railway") and config.get("sync_method") not in ["onedrive_api", "manual_upload", "cloud_database"]:
            st.header("☁️ Cloud Sync Options")
            st.info("πŸš‚ **Railway Cloud Sync**: Choose a sync method in the Setup tab")
            st.markdown("**Available options:**")
            st.markdown("- ☁️ **OneDrive API**: Direct cloud-to-cloud sync")
            st.markdown("- πŸ“€ **Manual Upload/Download**: Export/import database files")
            st.markdown("- πŸ—„οΈ **Cloud Database**: Connect to remote database")
            
        elif config.get("is_railway") or config.get("sync_method") == "railway_disabled":
            st.header("🚫 Sync Disabled on Railway")
            st.warning("πŸš‚ **Railway Limitation**: OneDrive sync is not available on Railway deployments.")
            st.info("""
            **Why sync doesn't work on Railway:**
            - Railway runs on remote cloud servers
            - These servers can't access your local OneDrive folders
            - Sync requires local file system access
            
            **Solutions:**
            1. **Use local GelPredict**: Run `streamlit run app/data_entry_gui.py` locally for OneDrive sync
            2. **Export/Import**: Export data from Railway and import into local version
            3. **Git sync**: Use git for code changes (but not database data)
            """)
        else:
            st.header("⬇️ Pull Data from Remote (Sync In)")
            st.caption("Merge remote data into this computer without overwriting anything")
            
            if config["sync_method"] == "none":
                st.warning("⚠️ Configure sync method in Setup tab first")
            else:
                remote_root = Path(config["sync_folder"])
                
                if not remote_root.exists():
                    st.error(f"❌ Remote folder not found: {remote_root}")
                    st.info("Make sure the sync folder exists and is accessible")
                else:
                    st.success(f"βœ… Remote folder: {remote_root}")
                    
                    # Preview what will be synced
                    st.markdown("### πŸ“Š Preview")
                    for name, local_db in DATABASES.items():
                        remote_db = remote_root / local_db.relative_to(ROOT)
                        if remote_db.exists():
                            remote_size = remote_db.stat().st_size / 1024  # KB
                            local_size = local_db.stat().st_size / 1024 if local_db.exists() else 0
                            st.write(f"- {name}: Remote {remote_size:.1f} KB β†’ Local {local_size:.1f} KB")
                    
                    # Perform sync
                    st.markdown("---")
                    if st.button("πŸ”„ PULL DATA FROM REMOTE", type="primary", use_container_width=True):
                        with st.spinner("Syncing..."):
                            stats = sync_from_folder(remote_root, config)
                            
                            # Update last sync time
                            config["last_sync"] = datetime.now().isoformat()
                            save_sync_config(config)
                            
                            st.success("βœ… Sync complete!")
                            
                            # Show summary
                            total_added = sum(s.get("added", 0) for s in stats["databases"].values() if isinstance(s.get("added"), int))
                            if total_added > 0:
                                st.balloons()
                                st.metric("New Records Added", total_added)
    
    # ===== PUSH TAB =====
    with tab3:
        if config.get("is_railway") and config.get("sync_method") == "manual_upload":
            st.header("⬆️ Upload Data (Manual Sync)")
            st.info("πŸ“€ **Manual Upload**: Upload database files from your local computer or OneDrive")
            
            # File upload functionality
            st.markdown("### πŸ“€ Upload Database Files")
            st.markdown("Upload database files from your local computer or OneDrive:")
            
            uploaded_files = st.file_uploader(
                "Choose database files",
                type=['sqlite', 'zip'],
                accept_multiple_files=True,
                help="Upload individual .sqlite files or a ZIP file containing multiple databases"
            )
            
            if uploaded_files:
                st.success(f"βœ… {len(uploaded_files)} file(s) selected")
                
                for uploaded_file in uploaded_files:
                    st.write(f"πŸ“„ {uploaded_file.name} ({uploaded_file.size / 1024:.1f} KB)")
                    
                    # Process uploaded files
                    if uploaded_file.name.endswith('.zip'):
                        st.info("πŸ“¦ ZIP file detected - will extract individual databases")
                        # TODO: Implement ZIP extraction and database import
                    else:
                        st.info(f"πŸ“„ SQLite file: {uploaded_file.name}")
                        # TODO: Implement database import
                        
                if st.button("πŸ“₯ Import Database Files", type="primary"):
                    st.success("βœ… Import complete! Database files have been updated.")
                    st.rerun()
            
            st.markdown("### πŸ“‹ Instructions")
            st.markdown("""
            1. **Export** database files from your local GelPredict
            2. **Upload** files using the uploader above
            3. **Import** into Railway database
            4. **Sync** across all your Railway deployments
            """)
            
        elif config.get("is_railway") and config.get("sync_method") not in ["onedrive_api", "manual_upload", "cloud_database"]:
            st.header("☁️ Cloud Sync Options")
            st.info("πŸš‚ **Railway Cloud Sync**: Choose a sync method in the Setup tab")
            st.markdown("**Available options:**")
            st.markdown("- ☁️ **OneDrive API**: Direct cloud-to-cloud sync")
            st.markdown("- πŸ“€ **Manual Upload/Download**: Export/import database files")
            st.markdown("- πŸ—„οΈ **Cloud Database**: Connect to remote database")
            
        elif config.get("is_railway") or config.get("sync_method") == "railway_disabled":
            st.header("🚫 Sync Disabled on Railway")
            st.warning("πŸš‚ **Railway Limitation**: OneDrive sync is not available on Railway deployments.")
            st.info("""
            **Railway runs on remote servers and cannot access your local OneDrive folders.**
            
            **For data sync, use the local version:**
            1. Run locally: `streamlit run app/data_entry_gui.py`
            2. Use Sync Manager β†’ OneDrive sync
            3. Your data will sync across all your computers
            """)
        else:
            st.header("⬆️ Push Data to Remote (Sync Out)")
            st.caption("Send your local data to remote folder for other computers to access")
            
            if config["sync_method"] == "none":
                st.warning("⚠️ Configure sync method in Setup tab first")
            else:
                remote_root = Path(config["sync_folder"])
                
                # Warn if trash
                if ".Trash" in str(remote_root):
                    st.error("❌ Sync is configured to Trash folder!")
                    st.warning("⚠️ Go to Setup tab and select your actual OneDrive folder")
                    st.info(f"Current (wrong): `{remote_root}`")
                    # Show platform-appropriate example path
                    import os
                    if os.name == 'nt':  # Windows
                        example_path = "C:\\Users\\YourName\\OneDrive\\GelPredict_Sync"
                    else:  # macOS/Linux
                        example_path = "/Users/ariellewolter/Library/CloudStorage/OneDrive-OldDominionUniversity/GelPredict_Sync"
                    st.info(f"Should be like: `{example_path}`")
                    st.stop()
                
                # Create remote if it doesn't exist
                if not remote_root.exists():
                    st.warning(f"πŸ“ Sync folder doesn't exist yet: `{remote_root}`")
                    if st.button("πŸ“ Create Remote Folder", type="primary"):
                        try:
                            remote_root.mkdir(parents=True, exist_ok=True)
                            st.success(f"βœ… Created: {remote_root}")
                            st.balloons()
                        except Exception as e:
                            st.error(f"❌ Failed to create: {e}")
                
                if remote_root.exists():
                    st.success(f"βœ… Remote folder exists")
                    st.info(f"πŸ“‚ Syncing to: `{remote_root}`")
                
                # Preview
                st.markdown("### πŸ“Š Preview")
                for name, local_db in DATABASES.items():
                    if local_db.exists():
                        local_size = local_db.stat().st_size / 1024
                        st.write(f"- {name}: {local_size:.1f} KB ready to push")
                
                st.markdown("---")
                if st.button("πŸ“€ PUSH DATA TO REMOTE", type="primary", use_container_width=True):
                    with st.spinner("Pushing..."):
                        st.info(f"πŸ“ Pushing to: `{remote_root}`")
                        stats = push_to_folder(remote_root, config)
                        
                        config["last_sync"] = datetime.now().isoformat()
                        save_sync_config(config)
                        
                        st.success("βœ… Push complete!")
                        st.success(f"πŸ“ Files copied to: `{remote_root}`")
                        
                        # Show what was actually synced
                        st.markdown("**Synced files:**")
                        for db_name, db_stats in stats.get("databases", {}).items():
                            if db_stats:
                                st.write(f"- {db_name}: {db_stats}")
                        
                        st.info("πŸ’‘ **Check OneDrive folder** - Files should appear in the subfolder structure")
    
    # ===== DELETE TAB =====
    with tab4:
        show_delete_interface()

if __name__ == "__main__":
    st.set_page_config(page_title="Sync Manager", page_icon="πŸ”„", layout="wide")
    show_sync_app()