lake-pulse 0.1.1

A Rust library for analyzing data lake table health across multiple formats and storage providers.
Documentation
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
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
// Copyright 2025 Adobe. All rights reserved.
// This file is licensed to you under the Apache License,
// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// or the MIT license (http://opensource.org/licenses/MIT),
// at your option.
//
// Unless required by applicable law or agreed to in writing,
// this software is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
// specific language governing permissions and limitations under
// each license.

use crate::reader::delta::metrics::DeltaMetrics;
#[cfg(feature = "hudi")]
use crate::reader::hudi::metrics::HudiMetrics;
use crate::reader::iceberg::metrics::IcebergMetrics;
#[cfg(feature = "lance")]
use crate::reader::lance::metrics::LanceMetrics;
use crate::util::ascii_gantt::to_ascii_gantt;
use crate::util::ascii_gantt::GanttConfig;
use serde::{Deserialize, Serialize};
use serde_json::{json, Error as JsonError};
use std::collections::{HashMap, LinkedList};
use std::error::Error;
use std::fmt::{Display, Formatter, Result as FmtResult};

/// Information about a single file in the data lake table.
///
/// Contains metadata about a file including its path, size, modification time,
/// and whether it's referenced by the table metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileInfo {
    /// The full path to the file
    pub path: String,
    /// Size of the file in bytes
    pub size_bytes: u64,
    /// Last modification timestamp (ISO 8601 format)
    pub last_modified: Option<String>,
    /// Whether this file is referenced in the table metadata
    pub is_referenced: bool,
}

/// Information about a table partition.
///
/// Contains aggregated metrics for a single partition including file counts,
/// sizes, and the list of files within the partition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PartitionInfo {
    /// Partition key-value pairs (e.g., {"year": "2024", "month": "01"})
    pub partition_values: HashMap<String, String>,
    /// Number of files in this partition
    pub file_count: usize,
    /// Total size of all files in this partition (bytes)
    pub total_size_bytes: u64,
    /// Average file size in this partition (bytes)
    pub avg_file_size_bytes: f64,
    /// List of files in this partition
    pub files: Vec<FileInfo>,
}

/// Clustering information for Iceberg tables.
///
/// Iceberg supports clustering data by specific columns to improve
/// query performance through data locality.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClusteringInfo {
    /// Columns used for clustering
    pub clustering_columns: Vec<String>,
    /// Number of clusters in the table
    pub cluster_count: usize,
    /// Average number of files per cluster
    pub avg_files_per_cluster: f64,
    /// Average cluster size (bytes)
    pub avg_cluster_size_bytes: f64,
}

/// Metrics for Delta Lake deletion vectors.
///
/// Deletion vectors are a Delta Lake feature that allows marking rows as deleted
/// without rewriting data files. High deletion vector usage may indicate a need
/// for compaction.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeletionVectorMetrics {
    /// Number of deletion vectors in the table
    pub deletion_vector_count: usize,
    /// Total size of all deletion vectors (bytes)
    pub total_deletion_vector_size_bytes: u64,
    /// Average deletion vector size (bytes)
    pub avg_deletion_vector_size_bytes: f64,
    /// Age of the oldest deletion vector (days)
    pub deletion_vector_age_days: f64,
    /// Total number of deleted rows tracked by deletion vectors
    pub deleted_rows_count: u64,
    /// Impact score: 0.0 (no impact) to 1.0 (high impact, compaction recommended)
    pub deletion_vector_impact_score: f64,
}

/// Metrics tracking schema evolution over time.
///
/// Monitors how the table schema has changed, helping identify schema stability
/// and potential compatibility issues.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchemaEvolutionMetrics {
    /// Total number of schema changes
    pub total_schema_changes: usize,
    /// Number of breaking schema changes
    pub breaking_changes: usize,
    /// Number of non-breaking schema changes
    pub non_breaking_changes: usize,
    /// Schema stability score: 0.0 (unstable) to 1.0 (very stable)
    pub schema_stability_score: f64,
    /// Days since the last schema change
    pub days_since_last_change: f64,
    /// Schema change frequency (changes per day)
    pub schema_change_frequency: f64,
    /// Current schema version number
    pub current_schema_version: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TimeTravelMetrics {
    pub total_snapshots: usize,
    pub oldest_snapshot_age_days: f64,
    pub newest_snapshot_age_days: f64,
    pub total_historical_size_bytes: u64,
    pub avg_snapshot_size_bytes: f64,
    pub storage_cost_impact_score: f64, // 0.0 = low cost, 1.0 = high cost
    pub retention_efficiency_score: f64, // 0.0 = inefficient, 1.0 = very efficient
    pub recommended_retention_days: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableConstraintsMetrics {
    pub total_constraints: usize,
    pub check_constraints: usize,
    pub not_null_constraints: usize,
    pub unique_constraints: usize,
    pub foreign_key_constraints: usize,
    pub constraint_violation_risk: f64, // 0.0 = low risk, 1.0 = high risk
    pub data_quality_score: f64,        // 0.0 = poor quality, 1.0 = excellent quality
    pub constraint_coverage_score: f64, // 0.0 = no coverage, 1.0 = full coverage
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileCompactionMetrics {
    pub compaction_opportunity_score: f64, // 0.0 = no opportunity, 1.0 = high opportunity
    pub small_files_count: usize,
    pub small_files_size_bytes: u64,
    pub potential_compaction_files: usize,
    pub estimated_compaction_savings_bytes: u64,
    pub recommended_target_file_size_bytes: u64,
    pub compaction_priority: String, // "low", "medium", "high", "critical"
    pub z_order_opportunity: bool,
    pub z_order_columns: Vec<String>,
}

/// Comprehensive health metrics for a data lake table.
///
/// This struct contains all the metrics collected during table analysis,
/// including file statistics, partition information, data quality metrics,
/// and format-specific metrics.
///
/// # Examples
///
/// ```no_run
/// use lake_pulse::analyze::metrics::HealthMetrics;
///
/// let mut metrics = HealthMetrics::new();
/// metrics.calculate_data_skew();
/// let score = metrics.calculate_health_score();
/// println!("Health score: {:.2}", score);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthMetrics {
    /// Total number of data files in the table
    pub total_files: usize,
    /// Total size of all data files (bytes)
    pub total_size_bytes: u64,
    /// List of files not referenced in table metadata
    pub unreferenced_files: Vec<FileInfo>,
    /// Total size of unreferenced files (bytes)
    pub unreferenced_size_bytes: u64,
    /// Number of partitions in the table
    pub partition_count: usize,
    /// Detailed information about each partition
    pub partitions: Vec<PartitionInfo>,
    /// Clustering information (Iceberg-specific)
    pub clustering: Option<ClusteringInfo>,
    /// Average file size across all files (bytes)
    pub avg_file_size_bytes: f64,
    /// Distribution of files by size category
    pub file_size_distribution: FileSizeDistribution,
    /// List of actionable recommendations
    pub recommendations: Vec<String>,
    /// Overall health score (0.0 to 1.0, higher is better)
    pub health_score: f64,
    /// Data skew metrics
    pub data_skew: DataSkewMetrics,
    /// Metadata health metrics
    pub metadata_health: MetadataHealth,
    /// Snapshot health metrics
    pub snapshot_health: SnapshotHealth,
    /// Deletion vector metrics (Delta-specific)
    pub deletion_vector_metrics: Option<DeletionVectorMetrics>,
    /// Schema evolution metrics
    pub schema_evolution: Option<SchemaEvolutionMetrics>,
    /// Time travel metrics
    pub time_travel_metrics: Option<TimeTravelMetrics>,
    /// Table constraints metrics
    pub table_constraints: Option<TableConstraintsMetrics>,
    /// File compaction opportunity metrics
    pub file_compaction: Option<FileCompactionMetrics>,
    /// Delta Lake specific metrics
    pub delta_table_specific_metrics: Option<DeltaMetrics>,
    /// Apache Hudi specific metrics (requires `hudi` feature)
    #[cfg(feature = "hudi")]
    pub hudi_table_specific_metrics: Option<HudiMetrics>,
    /// Apache Iceberg specific metrics
    pub iceberg_table_specific_metrics: Option<IcebergMetrics>,
    /// Lance specific metrics (requires `lance` feature)
    #[cfg(feature = "lance")]
    pub lance_table_specific_metrics: Option<LanceMetrics>,
}

/// Distribution of files by size category.
///
/// Categorizes files into size buckets to help identify potential
/// performance issues from too many small files or very large files.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileSizeDistribution {
    /// Number of small files (< 16MB)
    pub small_files: usize,
    /// Number of medium files (16MB - 128MB)
    pub medium_files: usize,
    /// Number of large files (128MB - 1GB)
    pub large_files: usize,
    /// Number of very large files (> 1GB)
    pub very_large_files: usize,
}

/// Metrics for detecting data skew in partitions and file sizes.
///
/// Data skew can lead to performance issues where some tasks process
/// significantly more data than others.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataSkewMetrics {
    /// Partition skew score: 0.0 (perfectly balanced) to 1.0 (highly skewed)
    pub partition_skew_score: f64,
    /// File size skew score: 0.0 (uniform sizes) to 1.0 (highly varied)
    pub file_size_skew_score: f64,
    /// Size of the largest partition (bytes)
    pub largest_partition_size: u64,
    /// Size of the smallest partition (bytes)
    pub smallest_partition_size: u64,
    /// Average partition size (bytes)
    pub avg_partition_size: u64,
    /// Standard deviation of partition sizes
    pub partition_size_std_dev: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetadataHealth {
    pub metadata_file_count: usize,
    pub metadata_total_size_bytes: u64,
    pub avg_metadata_file_size: f64,
    pub metadata_growth_rate: f64,  // bytes per day (estimated)
    pub manifest_file_count: usize, // For Iceberg
    pub first_file_name: Option<String>,
    pub last_file_name: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SnapshotHealth {
    pub snapshot_count: usize,
    pub oldest_snapshot_age_days: f64,
    pub newest_snapshot_age_days: f64,
    pub avg_snapshot_age_days: f64,
    pub snapshot_retention_risk: f64, // 0.0 (good) to 1.0 (high risk)
}

/// Complete health report for a data lake table.
///
/// This is the main output of the analysis process, containing all metrics,
/// recommendations, and timing information.
///
/// # Examples
///
/// ```no_run
/// use lake_pulse::{Analyzer, StorageConfig};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
/// let config = StorageConfig::local()
///     .with_option("path", "./examples/data");
///
/// let analyzer = Analyzer::builder(config)
///     .build()
///     .await?;
///
/// let report = analyzer.analyze("delta_dataset").await?;
///
/// // Print the report
/// println!("{}", report);
///
/// // Export to JSON
/// let json = report.to_json(false)?;
/// println!("{}", json);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthReport {
    /// Path to the analyzed table
    pub table_path: String,
    /// Table format type ("delta", "iceberg", "hudi", or "lance")
    pub table_type: String,
    /// Timestamp when the analysis was performed (ISO 8601 format)
    pub analysis_timestamp: String,
    /// Comprehensive health metrics
    pub metrics: HealthMetrics,
    /// Overall health score (0.0 to 1.0, higher is better)
    pub health_score: f64,
    /// Performance timing metrics
    pub timed_metrics: TimedLikeMetrics,
}

/// Performance timing metrics for analysis operations.
///
/// Tracks the duration of various operations during table analysis,
/// useful for performance profiling and optimization.
///
/// # Examples
///
/// ```no_run
/// use lake_pulse::analyze::metrics::TimedLikeMetrics;
///
/// # fn example(metrics: &TimedLikeMetrics) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
/// // Export to Chrome tracing format
/// let tracing_json = metrics.to_chrome_tracing()?;
///
/// // Generate ASCII Gantt chart
/// let gantt = metrics.duration_collection_as_gantt(None)?;
/// println!("{}", gantt);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TimedLikeMetrics {
    /// Collection of (operation_name, start_time_micros, duration_micros) tuples
    pub duration_collection: LinkedList<(String, u128, u128)>,
}

impl TimedLikeMetrics {
    pub fn to_chrome_tracing(&self) -> Result<String, Box<dyn Error + Send + Sync>> {
        let mut events = Vec::new();
        for (name, start, duration) in &self.duration_collection {
            events.push(json!({
                "name": name,
                "cat": "PERF",
                "pid": "1",
                "ph": "B",
                "ts": start * 1000,
            }));
            events.push(json!({
                "name": name,
                "cat": "PERF",
                "pid": "1",
                "ph": "E",
                "ts": start * 1000 + duration * 1000,
            }));
        }
        Ok(serde_json::to_string(&events)?)
    }

    /// Generate an ASCII Gantt chart representation of the timing data
    ///
    /// This creates a visual timeline showing when each operation started and how long it took.
    ///
    /// # Arguments
    ///
    /// * `config` - Optional configuration for the chart appearance. If None, uses default settings.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let gantt = metrics.to_ascii_gantt(None);
    /// println!("{}", gantt);
    /// ```
    ///
    /// Output example:
    /// ```text
    /// Timeline (ms):
    ///                           1000        1550        2100        2650
    ///                           |-----------|-----------|-----------|
    /// storage_config_new_dur    [] 50ms
    /// analyzer_new_dur           [====] 300ms
    /// analyze_total_dur                [========================] 2400ms
    /// ```
    pub fn duration_collection_as_gantt(
        &self,
        config: Option<GanttConfig>,
    ) -> Result<String, Box<dyn Error + Send + Sync>> {
        to_ascii_gantt(&self.duration_collection, config)
    }
}

impl Display for HealthReport {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let report = self;

        // Header (no vertical borders for path to allow longer paths)
        writeln!(f, "\n{}", "━".repeat(80))?;
        writeln!(
            f,
            " {:<60} Score: {:>5.1}% ",
            "Table Health Report",
            report.health_score * 100.0
        )?;
        writeln!(f, "{}", "━".repeat(80))?;
        writeln!(f, " {}", report.table_path)?;
        writeln!(f, " {} ({})", report.analysis_timestamp, report.table_type)?;
        writeln!(f, "{}", "━".repeat(80))?;

        // Key Metrics and File Size Distribution (side by side)
        writeln!(f)?;
        writeln!(f, " {:<41} File Size Distribution", "Key Metrics")?;
        writeln!(f, "{}", "━".repeat(80))?;

        let dist = &report.metrics.file_size_distribution;
        let total_files =
            (dist.small_files + dist.medium_files + dist.large_files + dist.very_large_files)
                as f64;

        let size_gb = report.metrics.total_size_bytes as f64 / (1024.0 * 1024.0 * 1024.0);
        let size_str = if size_gb >= 1.0 {
            format!("{:.2} GB", size_gb)
        } else {
            let size_mb = report.metrics.total_size_bytes as f64 / (1024.0 * 1024.0);
            format!("{:.2} MB", size_mb)
        };

        let avg_mb = report.metrics.avg_file_size_bytes / (1024.0 * 1024.0);

        writeln!(
            f,
            " {:<19} {:>8}              {:<19} {:>8}  {:>5.1}%",
            "Total Data Files",
            format!("{}", report.metrics.total_files),
            "Small (<16MB)",
            dist.small_files,
            if total_files > 0.0 {
                dist.small_files as f64 / total_files * 100.0
            } else {
                0.0
            }
        )?;
        writeln!(
            f,
            " {:<19} {:>8}              {:<19} {:>8}  {:>5.1}%",
            "Total Data Size",
            size_str,
            "Medium (16-128MB)",
            dist.medium_files,
            if total_files > 0.0 {
                dist.medium_files as f64 / total_files * 100.0
            } else {
                0.0
            }
        )?;
        writeln!(
            f,
            " {:<19} {:>8}              {:<19} {:>8}  {:>5.1}%",
            "Avg File Size",
            format!("{:.2} MB", avg_mb),
            "Large (128MB-1GB)",
            dist.large_files,
            if total_files > 0.0 {
                dist.large_files as f64 / total_files * 100.0
            } else {
                0.0
            }
        )?;
        writeln!(
            f,
            " {:<19} {:>8}              {:<19} {:>8}  {:>5.1}%",
            "Partitions",
            format!("{}", report.metrics.partition_count),
            "Very Large (>1GB)",
            dist.very_large_files,
            if total_files > 0.0 {
                dist.very_large_files as f64 / total_files * 100.0
            } else {
                0.0
            }
        )?;

        // Data Skew Analysis and Metadata Health (side by side)
        writeln!(f)?;
        writeln!(f, " {:<41} Metadata Health", "Data Skew Analysis")?;
        writeln!(f, "{}", "━".repeat(80))?;

        let skew = &report.metrics.data_skew;
        let meta = &report.metrics.metadata_health;

        let largest_mb = skew.largest_partition_size as f64 / (1024.0 * 1024.0);
        let smallest_mb = skew.smallest_partition_size as f64 / (1024.0 * 1024.0);
        let avg_partition_mb = skew.avg_partition_size as f64 / (1024.0 * 1024.0);
        let meta_size_mb = meta.metadata_total_size_bytes as f64 / (1024.0 * 1024.0);
        let avg_meta_mb = meta.avg_metadata_file_size / (1024.0 * 1024.0);

        writeln!(
            f,
            " {:<19} {:>8}              {:<19} {:>8}",
            "Partition Skew",
            format!("{:.2}", skew.partition_skew_score),
            "Count",
            format!("{}", meta.metadata_file_count)
        )?;
        writeln!(
            f,
            " {:<19} {:>8}              {:<19} {:>8}",
            "File Size Skew",
            format!("{:.2}", skew.file_size_skew_score),
            "Size",
            format!("{:.2} MB", meta_size_mb)
        )?;
        writeln!(
            f,
            " {:<19} {:>8}              {:<19} {:>8}",
            "Largest Partition",
            if skew.avg_partition_size > 0 {
                format!("{:.2} MB", largest_mb)
            } else {
                "N/A".to_string()
            },
            "Avg Size",
            if meta.metadata_file_count > 0 {
                format!("{:.2} MB", avg_meta_mb)
            } else {
                "N/A".to_string()
            }
        )?;
        writeln!(
            f,
            " {:<19} {:>8}              {:<19} {:>8}",
            "Smallest Partition",
            if skew.avg_partition_size > 0 {
                format!("{:.2} MB", smallest_mb)
            } else {
                "N/A".to_string()
            },
            "Manifests",
            format!("{}", meta.manifest_file_count)
        )?;
        // Truncate file names if too long
        let first_file = meta.first_file_name.as_deref().unwrap_or("N/A");
        let first_file_display = if first_file.len() > 30 {
            format!("...{}", &first_file[first_file.len() - 27..])
        } else {
            first_file.to_string()
        };

        let last_file = meta.last_file_name.as_deref().unwrap_or("N/A");
        let last_file_display = if last_file.len() > 30 {
            format!("...{}", &last_file[last_file.len() - 27..])
        } else {
            last_file.to_string()
        };

        writeln!(
            f,
            " {:<19} {:>8}              {:<12} {:>15}",
            "Avg Partition Size",
            if skew.avg_partition_size > 0 {
                format!("{:.2} MB", avg_partition_mb)
            } else {
                "N/A".to_string()
            },
            "First File",
            first_file_display
        )?;
        writeln!(
            f,
            " {:<19} {:>8}              {:<12} {:>15}",
            "", "", "Last File", last_file_display
        )?;

        // Snapshot Health and Unreferenced Files (side by side)
        writeln!(f)?;
        writeln!(f, " {:<41} Unreferenced Files", "Snapshot Health")?;
        writeln!(f, "{}", "━".repeat(80))?;

        let snap = &report.metrics.snapshot_health;
        let has_unreferenced = !report.metrics.unreferenced_files.is_empty();
        let wasted_gb = report.metrics.unreferenced_size_bytes as f64 / (1024.0 * 1024.0 * 1024.0);
        let wasted_str = if wasted_gb >= 1.0 {
            format!("{:.2} GB", wasted_gb)
        } else {
            let wasted_mb = report.metrics.unreferenced_size_bytes as f64 / (1024.0 * 1024.0);
            format!("{:.2} MB", wasted_mb)
        };

        writeln!(
            f,
            " {:<19} {:>8}              {:<19} {:>8}",
            "Snapshot Count",
            format!("{}", snap.snapshot_count),
            "Count",
            if has_unreferenced {
                format!("{}", report.metrics.unreferenced_files.len())
            } else {
                "0".to_string()
            }
        )?;
        writeln!(
            f,
            " {:<19} {:>8}              {:<19} {:>8}",
            "Retention Risk",
            format!("{:.1}%", snap.snapshot_retention_risk * 100.0),
            "Wasted Space",
            if has_unreferenced {
                wasted_str
            } else {
                "0 MB".to_string()
            }
        )?;
        writeln!(
            f,
            " {:<19} {:>8}",
            "Oldest Snapshot",
            if snap.oldest_snapshot_age_days > 0.0 {
                format!("{:.1} days", snap.oldest_snapshot_age_days)
            } else {
                "N/A".to_string()
            }
        )?;
        writeln!(
            f,
            " {:<19} {:>8}              {:<39}",
            "Newest Snapshot",
            if snap.newest_snapshot_age_days > 0.0 {
                format!("{:.1} days", snap.newest_snapshot_age_days)
            } else {
                "N/A".to_string()
            },
            if has_unreferenced {
                "WARNING: Files exist in storage"
            } else {
                ""
            }
        )?;
        writeln!(
            f,
            " {:<19} {:>8}              {:<39}",
            "Avg Snapshot Age",
            if snap.avg_snapshot_age_days > 0.0 {
                format!("{:.1} days", snap.avg_snapshot_age_days)
            } else {
                "N/A".to_string()
            },
            if has_unreferenced {
                "but not referenced in metadata"
            } else {
                ""
            }
        )?;

        // Clustering (Iceberg) and Deletion Vectors (Delta) - side by side
        // Only show clustering if there are actual clustering columns defined
        let has_clustering = report
            .metrics
            .clustering
            .as_ref()
            .is_some_and(|c| !c.clustering_columns.is_empty());
        let has_deletion_vectors = report.metrics.deletion_vector_metrics.is_some();

        if has_clustering || has_deletion_vectors {
            writeln!(f)?;
            writeln!(
                f,
                " {:<41} {}",
                if has_clustering { "Clustering" } else { "" },
                if has_deletion_vectors {
                    "Deletion Vectors"
                } else {
                    ""
                }
            )?;
            writeln!(f, "{}", "━".repeat(80))?;

            let max_rows = if has_clustering { 4 } else { 5 };

            for i in 0..max_rows {
                let left = if has_clustering {
                    if let Some(ref clustering) = report.metrics.clustering {
                        match i {
                            0 => format!(
                                " {:<19} {:>8}",
                                "Avg Cluster Size",
                                format!(
                                    "{:.2} MB",
                                    clustering.avg_cluster_size_bytes / (1024.0 * 1024.0)
                                )
                            ),
                            1 => format!(
                                " {:<19} {:>8}",
                                "Clusters",
                                format!("{}", clustering.cluster_count)
                            ),
                            2 => format!(
                                " {:<19} {:>8}",
                                "Avg Files/Cluster",
                                format!("{:.2}", clustering.avg_files_per_cluster)
                            ),
                            3 => clustering
                                .clustering_columns
                                .iter()
                                .enumerate()
                                .map(|(i, v)| {
                                    if i == 0 {
                                        format!(" {:<14} {:>13}", "Columns", v)
                                    } else {
                                        format!(" {:<14} {:>13}", "", v)
                                    }
                                })
                                .collect::<Vec<_>>()
                                .join("\n"),
                            _ => format!("{:<40}", ""),
                        }
                    } else {
                        format!("{:<40}", "")
                    }
                } else {
                    format!("{:<40}", "")
                };

                let right = if let Some(ref dv_metrics) = report.metrics.deletion_vector_metrics {
                    let dv_size_mb =
                        dv_metrics.total_deletion_vector_size_bytes as f64 / (1024.0 * 1024.0);
                    let dv_size_str = if dv_size_mb >= 1.0 {
                        format!("{:.2} MB", dv_size_mb)
                    } else {
                        let dv_size_kb =
                            dv_metrics.total_deletion_vector_size_bytes as f64 / 1024.0;
                        format!("{:.2} KB", dv_size_kb)
                    };

                    match i {
                        0 => format!(
                            " {:<19} {:>8}",
                            "Vectors",
                            format!("{}", dv_metrics.deletion_vector_count)
                        ),
                        1 => format!(" {:<19} {:>8}", "DV Size", dv_size_str),
                        2 => format!(
                            " {:<19} {:>8}",
                            "Deleted Rows",
                            format!("{}", dv_metrics.deleted_rows_count)
                        ),
                        3 => format!(
                            " {:<19} {:>8}",
                            "Oldest Age (days)",
                            format!("{:.1}", dv_metrics.deletion_vector_age_days)
                        ),
                        4 => format!(
                            " {:<19} {:>8}",
                            "Impact (0-1)",
                            format!("{:.2}", dv_metrics.deletion_vector_impact_score)
                        ),
                        _ => format!("{:<40}", ""),
                    }
                } else {
                    format!("{:<40}", "")
                };

                if has_clustering && has_deletion_vectors {
                    writeln!(f, "{}             {}", left, right)?;
                } else if has_clustering {
                    writeln!(f, "{}", left)?;
                } else {
                    writeln!(f, "{:<40}  {}", "", right)?;
                }
            }
        }

        // Schema Evolution and Time Travel - side by side
        let has_schema = report.metrics.schema_evolution.is_some();
        let has_time_travel = report.metrics.time_travel_metrics.is_some();

        if has_schema || has_time_travel {
            writeln!(f)?;
            writeln!(
                f,
                " {:<41} {}",
                if has_schema { "Schema Evolution" } else { "" },
                if has_time_travel {
                    "Time Travel Analysis"
                } else {
                    ""
                }
            )?;
            writeln!(f, "{}", "━".repeat(80))?;

            for i in 0..7 {
                let left = if let Some(ref schema_metrics) = report.metrics.schema_evolution {
                    match i {
                        0 => format!(
                            " {:<19} {:>8}",
                            "Total Changes",
                            format!("{}", schema_metrics.total_schema_changes)
                        ),
                        1 => format!(
                            " {:<19} {:>8}",
                            "Breaking",
                            format!("{}", schema_metrics.breaking_changes)
                        ),
                        2 => format!(
                            " {:<19} {:>8}",
                            "Non-Breaking",
                            format!("{}", schema_metrics.non_breaking_changes)
                        ),
                        3 => format!(
                            " {:<19} {:>8}",
                            "Stability (0-1)",
                            format!("{:.2}", schema_metrics.schema_stability_score)
                        ),
                        4 => format!(
                            " {:<19} {:>8}",
                            "Days Since Last",
                            format!("{:.1}d", schema_metrics.days_since_last_change)
                        ),
                        5 => format!(
                            " {:<19} {:>8}",
                            "Change Freq",
                            format!("{:.1}/d", schema_metrics.schema_change_frequency)
                        ),
                        6 => format!(
                            " {:<19} {:>8}",
                            "Version",
                            format!("{}", schema_metrics.current_schema_version)
                        ),
                        _ => format!("{:<40}", ""),
                    }
                } else {
                    format!("{:<40}", "")
                };

                let right = if let Some(ref tt_metrics) = report.metrics.time_travel_metrics {
                    let historical_gb =
                        tt_metrics.total_historical_size_bytes as f64 / (1024.0 * 1024.0 * 1024.0);
                    let historical_str = if historical_gb >= 1.0 {
                        format!("{:.2} GB", historical_gb)
                    } else {
                        let historical_mb =
                            tt_metrics.total_historical_size_bytes as f64 / (1024.0 * 1024.0);
                        format!("{:.2} MB", historical_mb)
                    };

                    match i {
                        0 => format!(
                            " {:<19} {:>8}",
                            "Snapshots",
                            format!("{}", tt_metrics.total_snapshots)
                        ),
                        1 => format!(
                            " {:<19} {:>8}",
                            "Oldest (days)",
                            format!("{:.1}", tt_metrics.oldest_snapshot_age_days)
                        ),
                        2 => format!(
                            " {:<19} {:>8}",
                            "Newest (days)",
                            format!("{:.1}", tt_metrics.newest_snapshot_age_days)
                        ),
                        3 => format!(" {:<19} {:>8}", "Historical Size", historical_str),
                        4 => format!(
                            " {:<19} {:>8}",
                            "Cost Impact (0-1)",
                            format!("{:.2}", tt_metrics.storage_cost_impact_score)
                        ),
                        5 => format!(
                            " {:<19} {:>8}",
                            "Reten Eff (0-1)",
                            format!("{:.2}", tt_metrics.retention_efficiency_score)
                        ),
                        6 => format!(
                            " {:<19} {:>8}",
                            "Recommended (days)",
                            format!("{}", tt_metrics.recommended_retention_days)
                        ),
                        _ => format!("{:<40}", ""),
                    }
                } else {
                    format!("{:<40}", "")
                };

                if has_schema && has_time_travel {
                    writeln!(f, "{}             {}", left, right)?;
                } else if has_schema {
                    writeln!(f, "{}", left)?;
                } else {
                    writeln!(f, "{:<40}  {}", "", right)?;
                }
            }
        }

        // Table Constraints and File Compaction - side by side
        let has_constraints = report.metrics.table_constraints.is_some();
        let has_compaction = report.metrics.file_compaction.is_some();

        if has_constraints || has_compaction {
            writeln!(f)?;
            writeln!(
                f,
                " {:<41} {}",
                if has_constraints {
                    "Table Constraints"
                } else {
                    ""
                },
                if has_compaction {
                    "File Compaction"
                } else {
                    ""
                }
            )?;
            writeln!(f, "{}", "━".repeat(80))?;

            let max_rows = 9;

            for i in 0..max_rows {
                let left = if let Some(ref constraint_metrics) = report.metrics.table_constraints {
                    match i {
                        0 => format!(
                            " {:<19} {:>8}",
                            "Total",
                            format!("{}", constraint_metrics.total_constraints)
                        ),
                        1 => format!(
                            " {:<19} {:>8}",
                            "Check",
                            format!("{}", constraint_metrics.check_constraints)
                        ),
                        2 => format!(
                            " {:<19} {:>8}",
                            "NOT NULL",
                            format!("{}", constraint_metrics.not_null_constraints)
                        ),
                        3 => format!(
                            " {:<19} {:>8}",
                            "Unique",
                            format!("{}", constraint_metrics.unique_constraints)
                        ),
                        4 => format!(
                            " {:<19} {:>8}",
                            "Foreign Key",
                            format!("{}", constraint_metrics.foreign_key_constraints)
                        ),
                        5 => format!(
                            " {:<20} {:>7}",
                            "Violation Risk (0-1)",
                            format!("{:.2}", constraint_metrics.constraint_violation_risk)
                        ),
                        6 => format!(
                            " {:<19} {:>8}",
                            "Quality Score (0-1)",
                            format!("{:.2}", constraint_metrics.data_quality_score)
                        ),
                        7 => format!(
                            " {:<19} {:>8}",
                            "Coverage (0-1)",
                            format!("{:.2}", constraint_metrics.constraint_coverage_score)
                        ),
                        _ => format!("{:<29}", ""),
                    }
                } else {
                    format!("{:<40}", "")
                };

                let right = if let Some(ref compaction_metrics) = report.metrics.file_compaction {
                    let small_files_mb =
                        compaction_metrics.small_files_size_bytes as f64 / (1024.0 * 1024.0);
                    let savings_mb = compaction_metrics.estimated_compaction_savings_bytes as f64
                        / (1024.0 * 1024.0);
                    let savings_str = if savings_mb >= 1.0 {
                        format!("{:.2} MB", savings_mb)
                    } else {
                        let savings_kb =
                            compaction_metrics.estimated_compaction_savings_bytes as f64 / 1024.0;
                        format!("{:.2} KB", savings_kb)
                    };
                    let target_mb = compaction_metrics.recommended_target_file_size_bytes as f64
                        / (1024.0 * 1024.0);

                    match i {
                        0 => format!(
                            " {:<19} {:>8}",
                            "Opportunity (0-1)",
                            format!("{:.2}", compaction_metrics.compaction_opportunity_score)
                        ),
                        1 => format!(
                            " {:<19} {:>8}",
                            "Small Files",
                            format!("{}", compaction_metrics.small_files_count)
                        ),
                        2 => format!(
                            " {:<19} {:>8}",
                            "Small Size",
                            format!("{:.2} MB", small_files_mb)
                        ),
                        3 => format!(
                            " {:<19} {:>8}",
                            "Potential Files",
                            format!("{}", compaction_metrics.potential_compaction_files)
                        ),
                        4 => format!(" {:<19} {:>8}", "Savings", savings_str),
                        5 => format!(
                            " {:<19} {:>8}",
                            "Target Size",
                            format!("{:.0} MB", target_mb)
                        ),
                        6 => format!(
                            " {:<19} {:>8}",
                            "Priority",
                            compaction_metrics.compaction_priority.to_uppercase()
                        ),
                        7 => format!(
                            " {:<19} {:>8}",
                            "Z-Order",
                            if compaction_metrics.z_order_opportunity {
                                "Yes"
                            } else {
                                "No"
                            }
                        ),
                        8 => {
                            if !compaction_metrics.z_order_columns.is_empty() {
                                let print_rows = compaction_metrics
                                    .z_order_columns
                                    .iter()
                                    .enumerate()
                                    .map(|(i, v)| {
                                        if i == 0 {
                                            format!(" {:<14} {:>13}", "Z-Columns", v)
                                        } else {
                                            format!(" {:<14} {:>13}", "", v)
                                        }
                                    })
                                    .collect::<Vec<_>>();

                                print_rows.join("\n")

                                // format!(
                                //     " {:<19} {:>8}",
                                //     "Z-Columns",
                                //     compaction_metrics.z_order_columns.join(", ")
                                // )
                            } else {
                                format!("{:<40}", "")
                            }
                        }
                        _ => format!("{:<40}", ""),
                    }
                } else {
                    format!("{:<40}", "")
                };

                // Skip empty rows (e.g., row 8 when no Z-Order columns)
                let left_empty = left.trim().is_empty();
                let right_empty = right.trim().is_empty();

                if left_empty && right_empty {
                    continue;
                }

                if has_constraints && has_compaction {
                    writeln!(f, "{}             {}", left, right)?;
                } else if has_constraints {
                    writeln!(f, "{}", left)?;
                } else {
                    writeln!(f, "{:<40}  {}", "", right)?;
                }
            }
        }

        // Format-Specific Metrics
        if let Some(ref delta_metrics) = report.metrics.delta_table_specific_metrics {
            write!(f, "{}", delta_metrics)?;
        }
        if let Some(ref iceberg_metrics) = report.metrics.iceberg_table_specific_metrics {
            write!(f, "{}", iceberg_metrics)?;
        }
        #[cfg(feature = "hudi")]
        if let Some(ref hudi_metrics) = report.metrics.hudi_table_specific_metrics {
            write!(f, "{}", hudi_metrics)?;
        }
        #[cfg(feature = "lance")]
        if let Some(ref lance_metrics) = report.metrics.lance_table_specific_metrics {
            write!(f, "{}", lance_metrics)?;
        }

        // Recommendations (full width)
        writeln!(f)?;
        writeln!(f, " Recommendations")?;
        writeln!(f, "{}", "━".repeat(80))?;
        if !report.metrics.recommendations.is_empty() {
            for (i, rec) in report.metrics.recommendations.iter().enumerate() {
                writeln!(f, " {}. {}", i + 1, rec)?;
            }
        } else {
            writeln!(f, "  No recommendations - table is in excellent health!")?;
        }

        Ok(())
    }
}

impl HealthReport {
    pub fn to_json(&self, exclude_files: bool) -> Result<String, JsonError> {
        if exclude_files {
            let mut report = self.clone();
            report.metrics.unreferenced_files = Vec::new();
            report
                .metrics
                .partitions
                .iter_mut()
                .for_each(|p| p.files = Vec::new());
            serde_json::to_string_pretty(&report)
        } else {
            serde_json::to_string_pretty(self)
        }
    }
}

impl Default for HealthMetrics {
    fn default() -> Self {
        Self::new()
    }
}

impl HealthMetrics {
    pub fn new() -> Self {
        Self {
            total_files: 0,
            total_size_bytes: 0,
            unreferenced_files: Vec::new(),
            unreferenced_size_bytes: 0,
            partition_count: 0,
            partitions: Vec::new(),
            clustering: None,
            avg_file_size_bytes: 0.0,
            file_size_distribution: FileSizeDistribution {
                small_files: 0,
                medium_files: 0,
                large_files: 0,
                very_large_files: 0,
            },
            recommendations: Vec::new(),
            health_score: 0.0,
            data_skew: DataSkewMetrics {
                partition_skew_score: 0.0,
                file_size_skew_score: 0.0,
                largest_partition_size: 0,
                smallest_partition_size: 0,
                avg_partition_size: 0,
                partition_size_std_dev: 0.0,
            },
            metadata_health: MetadataHealth {
                metadata_file_count: 0,
                metadata_total_size_bytes: 0,
                avg_metadata_file_size: 0.0,
                metadata_growth_rate: 0.0,
                manifest_file_count: 0,
                first_file_name: None,
                last_file_name: None,
            },
            snapshot_health: SnapshotHealth {
                snapshot_count: 0,
                oldest_snapshot_age_days: 0.0,
                newest_snapshot_age_days: 0.0,
                avg_snapshot_age_days: 0.0,
                snapshot_retention_risk: 0.0,
            },
            deletion_vector_metrics: None,
            schema_evolution: None,
            time_travel_metrics: None,
            table_constraints: None,
            file_compaction: None,
            delta_table_specific_metrics: None,
            #[cfg(feature = "hudi")]
            hudi_table_specific_metrics: None,
            iceberg_table_specific_metrics: None,
            #[cfg(feature = "lance")]
            lance_table_specific_metrics: None,
        }
    }

    pub fn calculate_health_score(&self) -> f64 {
        let mut score = 1.0;

        // Penalize unreferenced files
        if self.total_files > 0 {
            let unreferenced_ratio = self.unreferenced_files.len() as f64 / self.total_files as f64;
            score -= unreferenced_ratio * 0.3;
        }

        // Penalize small files (inefficient)
        if self.total_files > 0 {
            let small_file_ratio =
                self.file_size_distribution.small_files as f64 / self.total_files as f64;
            score -= small_file_ratio * 0.2;
        }

        // Penalize very large files (potential performance issues)
        if self.total_files > 0 {
            let very_large_ratio =
                self.file_size_distribution.very_large_files as f64 / self.total_files as f64;
            score -= very_large_ratio * 0.1;
        }

        // Reward good partitioning
        if self.partition_count > 0 && self.total_files > 0 {
            let avg_files_per_partition = self.total_files as f64 / self.partition_count as f64;
            if avg_files_per_partition > 100.0 {
                score -= 0.1; // Too many files per partition
            } else if avg_files_per_partition < 5.0 {
                score -= 0.05; // Too few files per partition
            }
        }

        // Penalize data skew
        score -= self.data_skew.partition_skew_score * 0.15;
        score -= self.data_skew.file_size_skew_score * 0.1;

        // Penalize metadata bloat
        if self.metadata_health.metadata_total_size_bytes > 100 * 1024 * 1024 {
            // > 100MB
            score -= 0.05;
        }

        // Penalize snapshot retention issues
        score -= self.snapshot_health.snapshot_retention_risk * 0.1;

        // Penalize deletion vector impact
        if let Some(ref dv_metrics) = self.deletion_vector_metrics {
            score -= dv_metrics.deletion_vector_impact_score * 0.15;
        }

        // Factor in schema stability
        if let Some(ref schema_metrics) = self.schema_evolution {
            score -= (1.0 - schema_metrics.schema_stability_score) * 0.2;
        }

        // Factor in time travel storage costs
        if let Some(ref tt_metrics) = self.time_travel_metrics {
            score -= tt_metrics.storage_cost_impact_score * 0.1;
            score -= (1.0 - tt_metrics.retention_efficiency_score) * 0.05;
        }

        // Factor in data quality from constraints
        if let Some(ref constraint_metrics) = self.table_constraints {
            score -= (1.0 - constraint_metrics.data_quality_score) * 0.15;
            score -= constraint_metrics.constraint_violation_risk * 0.1;
        }

        // Factor in file compaction opportunities
        if let Some(ref compaction_metrics) = self.file_compaction {
            score -= (1.0 - compaction_metrics.compaction_opportunity_score) * 0.1;
        }

        score.clamp(0.0, 1.0)
    }

    pub fn calculate_data_skew(&mut self) {
        if self.partitions.is_empty() {
            return;
        }

        let partition_sizes: Vec<u64> =
            self.partitions.iter().map(|p| p.total_size_bytes).collect();
        let file_counts: Vec<usize> = self.partitions.iter().map(|p| p.file_count).collect();

        // Calculate partition size skew
        if !partition_sizes.is_empty() {
            let total_size: u64 = partition_sizes.iter().sum();
            let avg_size = total_size as f64 / partition_sizes.len() as f64;

            let variance = partition_sizes
                .iter()
                .map(|&size| (size as f64 - avg_size).powi(2))
                .sum::<f64>()
                / partition_sizes.len() as f64;

            let std_dev = variance.sqrt();
            let coefficient_of_variation = if avg_size > 0.0 {
                std_dev / avg_size
            } else {
                0.0
            };

            self.data_skew.partition_skew_score = coefficient_of_variation.min(1.0);
            self.data_skew.largest_partition_size = *partition_sizes.iter().max().unwrap_or(&0);
            self.data_skew.smallest_partition_size = *partition_sizes.iter().min().unwrap_or(&0);
            self.data_skew.avg_partition_size = avg_size as u64;
            self.data_skew.partition_size_std_dev = std_dev;
        }

        // Calculate file count skew
        if !file_counts.is_empty() {
            let total_files: usize = file_counts.iter().sum();
            let avg_files = total_files as f64 / file_counts.len() as f64;

            let variance = file_counts
                .iter()
                .map(|&count| (count as f64 - avg_files).powi(2))
                .sum::<f64>()
                / file_counts.len() as f64;

            let std_dev = variance.sqrt();
            let coefficient_of_variation = if avg_files > 0.0 {
                std_dev / avg_files
            } else {
                0.0
            };

            self.data_skew.file_size_skew_score = coefficient_of_variation.min(1.0);
        }
    }

    pub fn calculate_snapshot_health(&mut self, snapshot_count: usize) {
        self.snapshot_health.snapshot_count = snapshot_count;

        // Simplified snapshot age calculation (would need actual timestamps)
        self.snapshot_health.oldest_snapshot_age_days = 0.0;
        self.snapshot_health.newest_snapshot_age_days = 0.0;
        self.snapshot_health.avg_snapshot_age_days = 0.0;

        // Calculate retention risk based on snapshot count
        if snapshot_count > 100 {
            self.snapshot_health.snapshot_retention_risk = 0.8;
        } else if snapshot_count > 50 {
            self.snapshot_health.snapshot_retention_risk = 0.5;
        } else if snapshot_count > 20 {
            self.snapshot_health.snapshot_retention_risk = 0.2;
        } else {
            self.snapshot_health.snapshot_retention_risk = 0.0;
        }
    }

    pub fn generate_recommendations(&mut self) {
        // Check for unreferenced files
        if !self.unreferenced_files.is_empty() {
            self.recommendations.push(format!(
                "Found {} unreferenced files ({} bytes). Consider cleaning up orphaned data files.",
                self.unreferenced_files.len(),
                self.unreferenced_size_bytes
            ));
        }

        // Check file size distribution
        let total_files = self.total_files as f64;
        if total_files > 0.0 {
            let small_file_ratio = self.file_size_distribution.small_files as f64 / total_files;
            if small_file_ratio > 0.5 {
                self.recommendations.push(
                    "High percentage of small files detected. Consider compacting to improve query performance.".to_string()
                );
            }

            let very_large_ratio =
                self.file_size_distribution.very_large_files as f64 / total_files;
            if very_large_ratio > 0.1 {
                self.recommendations.push(
                    "Some very large files detected. Consider splitting large files for better parallelism.".to_string()
                );
            }
        }

        // Check partitioning
        if self.partition_count > 0 {
            let avg_files_per_partition = total_files / self.partition_count as f64;
            if avg_files_per_partition > 100.0 {
                self.recommendations.push(
                    "High number of files per partition. Consider repartitioning to reduce file count.".to_string()
                );
            } else if avg_files_per_partition < 5.0 {
                self.recommendations.push(
                    "Low number of files per partition. Consider consolidating partitions."
                        .to_string(),
                );
            }
        }

        // Check for empty partitions
        let empty_partitions = self.partitions.iter().filter(|p| p.file_count == 0).count();
        if empty_partitions > 0 {
            self.recommendations.push(format!(
                "Found {} empty partitions. Consider removing empty partition directories.",
                empty_partitions
            ));
        }

        // Check data skew
        if self.data_skew.partition_skew_score > 0.5 {
            self.recommendations.push(
                "High partition skew detected. Consider repartitioning to balance data distribution.".to_string()
            );
        }

        if self.data_skew.file_size_skew_score > 0.5 {
            self.recommendations.push(
                "High file size skew detected. Consider running OPTIMIZE to balance file sizes."
                    .to_string(),
            );
        }

        // Check metadata health
        if self.metadata_health.metadata_total_size_bytes > 50 * 1024 * 1024 {
            // > 50MB
            self.recommendations.push(
                "Large metadata size detected. Consider running VACUUM to clean up old transaction logs.".to_string()
            );
        }

        // Check snapshot health
        if self.snapshot_health.snapshot_retention_risk > 0.7 {
            self.recommendations.push(
                "High snapshot retention risk. Consider running VACUUM to remove old snapshots."
                    .to_string(),
            );
        }

        // Check clustering
        if let Some(ref clustering) = self.clustering {
            if clustering.avg_files_per_cluster > 50.0 {
                self.recommendations.push(
                    "High number of files per cluster. Consider optimizing clustering strategy."
                        .to_string(),
                );
            }

            if clustering.clustering_columns.len() > 4 {
                self.recommendations.push(
                    "Too many clustering columns detected. Consider reducing to 4 or fewer columns for optimal performance.".to_string()
                );
            }

            if clustering.clustering_columns.is_empty() {
                self.recommendations.push(
                    "No clustering detected. Consider enabling liquid clustering for better query performance.".to_string()
                );
            }
        }

        // Check deletion vectors
        if let Some(ref dv_metrics) = self.deletion_vector_metrics {
            if dv_metrics.deletion_vector_impact_score > 0.7 {
                self.recommendations.push(
                    "High deletion vector impact detected. Consider running VACUUM to clean up old deletion vectors.".to_string()
                );
            }

            if dv_metrics.deletion_vector_count > 50 {
                self.recommendations.push(
                    "Many deletion vectors detected. Consider optimizing delete operations to reduce fragmentation.".to_string()
                );
            }

            if dv_metrics.deletion_vector_age_days > 30.0 {
                self.recommendations.push(
                    "Old deletion vectors detected. Consider running VACUUM to clean up deletion vectors older than 30 days.".to_string()
                );
            }
        }

        // Check schema evolution
        if let Some(ref schema_metrics) = self.schema_evolution {
            if schema_metrics.schema_stability_score < 0.5 {
                self.recommendations.push(
                    "Unstable schema detected. Consider planning schema changes more carefully to improve performance.".to_string()
                );
            }

            if schema_metrics.breaking_changes > 5 {
                self.recommendations.push(
                    "Many breaking schema changes detected. Consider using schema evolution features to avoid breaking changes.".to_string()
                );
            }

            if schema_metrics.schema_change_frequency > 1.0 {
                self.recommendations.push(
                    "High schema change frequency detected. Consider batching schema changes to reduce performance impact.".to_string()
                );
            }

            if schema_metrics.days_since_last_change < 1.0 {
                self.recommendations.push(
                    "Recent schema changes detected. Monitor query performance for potential issues.".to_string()
                );
            }
        }

        // Check time travel storage costs
        if let Some(ref tt_metrics) = self.time_travel_metrics {
            if tt_metrics.storage_cost_impact_score > 0.7 {
                self.recommendations.push(
                    "High time travel storage costs detected. Consider running VACUUM to clean up old snapshots.".to_string()
                );
            }

            if tt_metrics.retention_efficiency_score < 0.5 {
                self.recommendations.push(
                    "Inefficient snapshot retention detected. Consider optimizing retention policy.".to_string()
                );
            }

            if tt_metrics.total_snapshots > 1000 {
                self.recommendations.push(
                    "High snapshot count detected. Consider reducing retention period to improve performance.".to_string()
                );
            }
        }

        // Check table constraints
        if let Some(ref constraint_metrics) = self.table_constraints {
            if constraint_metrics.data_quality_score < 0.5 {
                self.recommendations.push(
                    "Low data quality score detected. Consider adding more table constraints."
                        .to_string(),
                );
            }

            if constraint_metrics.constraint_violation_risk > 0.7 {
                self.recommendations.push(
                    "High constraint violation risk detected. Monitor data quality and consider data validation.".to_string()
                );
            }

            if constraint_metrics.constraint_coverage_score < 0.3 {
                self.recommendations.push(
                    "Low constraint coverage detected. Consider adding check constraints for better data quality.".to_string()
                );
            }
        }

        // Check file compaction opportunities
        if let Some(ref compaction_metrics) = self.file_compaction {
            if compaction_metrics.compaction_opportunity_score > 0.7 {
                self.recommendations.push(
                    "High file compaction opportunity detected. Consider running OPTIMIZE to improve performance.".to_string()
                );
            }

            if compaction_metrics.compaction_priority == "critical" {
                self.recommendations.push(
                    "Critical compaction priority detected. Run OPTIMIZE immediately to improve query performance.".to_string()
                );
            }

            if compaction_metrics.z_order_opportunity {
                self.recommendations.push(
                    format!("Z-ordering opportunity detected. Consider running OPTIMIZE ZORDER BY ({}) to improve query performance.",
                            compaction_metrics.z_order_columns.join(", ")).to_string()
                );
            }

            if compaction_metrics.estimated_compaction_savings_bytes > 100 * 1024 * 1024 {
                // > 100MB
                let savings_mb = compaction_metrics.estimated_compaction_savings_bytes as f64
                    / (1024.0 * 1024.0);
                self.recommendations.push(
                    format!("Significant compaction savings available: {:.1} MB. Consider running OPTIMIZE.", savings_mb).to_string()
                );
            }
        }

        // Check Lance-specific index recommendations
        #[cfg(feature = "lance")]
        if let Some(ref lance_metrics) = self.lance_table_specific_metrics {
            let index_info = &lance_metrics.index_info;

            // Recommend creating indices for large tables without any indices
            if index_info.num_indices == 0 {
                if let Some(num_rows) = lance_metrics.metadata.num_rows {
                    if num_rows > 10_000 {
                        self.recommendations.push(
                            "No indices found on Lance table. Consider creating vector or scalar indices for frequently queried columns.".to_string()
                        );
                    }
                }
            }

            // Check for tables with many fragments that could benefit from indexing
            if lance_metrics.fragment_info.num_fragments > 100 && index_info.num_indices == 0 {
                self.recommendations.push(
                    "Large number of fragments detected without indices. Consider creating indices to improve query performance.".to_string()
                );
            }

            // Check for high deletion ratio that might affect index performance
            if let Some(num_deleted) = lance_metrics.metadata.num_deleted_rows {
                if let Some(num_rows) = lance_metrics.metadata.num_rows {
                    if num_rows > 0 {
                        let deletion_ratio = num_deleted as f64 / (num_rows + num_deleted) as f64;
                        if deletion_ratio > 0.2 && index_info.num_indices > 0 {
                            self.recommendations.push(
                                "High deletion ratio detected with existing indices. Consider rebuilding indices after compaction.".to_string()
                            );
                        }
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_chrome_tracing_with_real_data_reproduces_overflow() {
        // This test reproduces the overflow bug with real Chrome tracing data
        // The input has timestamps in microseconds (very large numbers)
        let chrome_trace_input = r#"[{"cat":"PERF","name":"storage_config_new_dur","ph":"B","pid":"1","ts":1762455078689000},{"cat":"PERF","name":"storage_config_new_dur","ph":"E","pid":"1","ts":1762455078690000}]"#;

        let events: Vec<serde_json::Value> =
            serde_json::from_str(chrome_trace_input).expect("Failed to parse Chrome tracing JSON");

        // Extract timing data - timestamps are in microseconds
        let begin_ts = events[0]["ts"].as_u64().unwrap() as u128;
        let end_ts = events[1]["ts"].as_u64().unwrap() as u128;

        println!("Begin timestamp (microseconds): {}", begin_ts);
        println!("End timestamp (microseconds): {}", end_ts);
        println!("Duration (microseconds): {}", end_ts - begin_ts);

        // The current code expects milliseconds and multiplies by 1000
        // If we naively use these microsecond values as milliseconds, we get overflow
        let mut collection = LinkedList::new();

        // This is what would cause overflow - treating microseconds as milliseconds
        // collection.push_back(("storage_config_new_dur".to_string(), begin_ts, end_ts - begin_ts));

        // The correct approach: timestamps in the input are already in microseconds
        // So we should NOT multiply by 1000 in to_chrome_tracing(), OR
        // we need to store timestamps in milliseconds in our internal format

        // For now, let's test with the corrected approach (divide by 1000 to get milliseconds)
        collection.push_back((
            "storage_config_new_dur".to_string(),
            begin_ts / 1000,            // Convert to milliseconds
            (end_ts - begin_ts) / 1000, // Duration in milliseconds
        ));

        let metrics = TimedLikeMetrics {
            duration_collection: collection,
        };

        // This should work without overflow now
        let output = metrics
            .to_chrome_tracing()
            .expect("Should generate Chrome tracing output");

        let output_events: Vec<serde_json::Value> =
            serde_json::from_str(&output).expect("Should parse output");

        // Verify the output
        assert_eq!(output_events.len(), 2);

        // The output timestamps should be in microseconds (original format)
        let output_begin_ts = output_events[0]["ts"].as_u64().unwrap();
        let output_end_ts = output_events[1]["ts"].as_u64().unwrap();

        println!("Output begin timestamp: {}", output_begin_ts);
        println!("Output end timestamp: {}", output_end_ts);

        // Verify the timestamps are approximately correct (within rounding error)
        assert!(
            (output_begin_ts as i128 - begin_ts as i128).abs() < 1000,
            "Begin timestamp should be approximately preserved"
        );
        assert!(
            (output_end_ts as i128 - end_ts as i128).abs() < 1000,
            "End timestamp should be approximately preserved"
        );
    }

    #[test]
    #[should_panic(expected = "attempt to multiply with overflow")]
    fn test_chrome_tracing_overflow_bug() {
        // This test demonstrates the overflow bug when using very large timestamps
        let mut collection = LinkedList::new();

        // Use a timestamp that will overflow when multiplied by 1000
        // u128::MAX / 1000 = 340282366920938463463374607431768211
        // Anything larger than this will overflow
        let large_timestamp: u128 = u128::MAX / 500; // This will overflow when multiplied by 1000

        collection.push_back(("test_metric".to_string(), large_timestamp, 1000));

        let metrics = TimedLikeMetrics {
            duration_collection: collection,
        };

        // This should panic with overflow in debug mode
        let _ = metrics.to_chrome_tracing();
    }

    #[test]
    fn test_parse_full_chrome_trace_and_regenerate() {
        // This test parses the FULL Chrome tracing JSON provided by the user
        // and attempts to regenerate it, which should expose any overflow issues
        let chrome_trace_input = r#"[{"cat":"PERF","name":"storage_config_new_dur","ph":"B","pid":"1","ts":1762455078689000},{"cat":"PERF","name":"storage_config_new_dur","ph":"E","pid":"1","ts":1762455078690000},{"cat":"PERF","name":"analyzer_new_dur","ph":"B","pid":"1","ts":1762455078691000},{"cat":"PERF","name":"analyzer_new_dur","ph":"E","pid":"1","ts":1762455078972000},{"cat":"PERF","name":"validate_connection_dur","ph":"B","pid":"1","ts":1762455078973000},{"cat":"PERF","name":"validate_connection_dur","ph":"E","pid":"1","ts":1762455080930000},{"cat":"PERF","name":"discover_partitions","ph":"B","pid":"1","ts":1762455080932000},{"cat":"PERF","name":"discover_partitions","ph":"E","pid":"1","ts":1762455081493000},{"cat":"PERF","name":"list_files_parallel","ph":"B","pid":"1","ts":1762455081495000},{"cat":"PERF","name":"list_files_parallel","ph":"E","pid":"1","ts":1762455082170000},{"cat":"PERF","name":"detect_table_type","ph":"B","pid":"1","ts":1762455082171000},{"cat":"PERF","name":"detect_table_type","ph":"E","pid":"1","ts":1762455082172000},{"cat":"PERF","name":"categorize_files","ph":"B","pid":"1","ts":1762455082173000},{"cat":"PERF","name":"categorize_files","ph":"E","pid":"1","ts":1762455082173000},{"cat":"PERF","name":"find_referenced_files","ph":"B","pid":"1","ts":1762455082174000},{"cat":"PERF","name":"find_referenced_files","ph":"E","pid":"1","ts":1762455082683000},{"cat":"PERF","name":"find_unreferenced_files","ph":"B","pid":"1","ts":1762455082684000},{"cat":"PERF","name":"find_unreferenced_files","ph":"E","pid":"1","ts":1762455082685000},{"cat":"PERF","name":"analyze_partitioning","ph":"B","pid":"1","ts":1762455082687000},{"cat":"PERF","name":"analyze_partitioning","ph":"E","pid":"1","ts":1762455082689000},{"cat":"PERF","name":"update_metrics_from_metadata","ph":"B","pid":"1","ts":1762455082689000},{"cat":"PERF","name":"update_metrics_from_metadata","ph":"E","pid":"1","ts":1762455083173000},{"cat":"PERF","name":"calculate_file_size_distribution","ph":"B","pid":"1","ts":1762455083175000},{"cat":"PERF","name":"calculate_file_size_distribution","ph":"E","pid":"1","ts":1762455083175000},{"cat":"PERF","name":"calculate_metadata_health","ph":"B","pid":"1","ts":1762455083176000},{"cat":"PERF","name":"calculate_metadata_health","ph":"E","pid":"1","ts":1762455083176000},{"cat":"PERF","name":"calculate_data_skew","ph":"B","pid":"1","ts":1762455083177000},{"cat":"PERF","name":"calculate_data_skew","ph":"E","pid":"1","ts":1762455083179000},{"cat":"PERF","name":"calculate_snapshot_health","ph":"B","pid":"1","ts":1762455083179000},{"cat":"PERF","name":"calculate_snapshot_health","ph":"E","pid":"1","ts":1762455083179000},{"cat":"PERF","name":"analyze_file_compaction","ph":"B","pid":"1","ts":1762455083180000},{"cat":"PERF","name":"analyze_file_compaction","ph":"E","pid":"1","ts":1762455083180000},{"cat":"PERF","name":"generate_recommendations","ph":"B","pid":"1","ts":1762455083181000},{"cat":"PERF","name":"generate_recommendations","ph":"E","pid":"1","ts":1762455083181000},{"cat":"PERF","name":"calculate_health_score","ph":"B","pid":"1","ts":1762455083182000},{"cat":"PERF","name":"calculate_health_score","ph":"E","pid":"1","ts":1762455083182000},{"cat":"PERF","name":"analyze_after_validation_dur","ph":"B","pid":"1","ts":1762455081495000},{"cat":"PERF","name":"analyze_after_validation_dur","ph":"E","pid":"1","ts":1762455083183000},{"cat":"PERF","name":"delta_reader","ph":"B","pid":"1","ts":1762455083183000},{"cat":"PERF","name":"delta_reader","ph":"E","pid":"1","ts":1762455085985000},{"cat":"PERF","name":"analyze_total_dur","ph":"B","pid":"1","ts":1762455078972000},{"cat":"PERF","name":"analyze_total_dur","ph":"E","pid":"1","ts":1762455085987000},{"cat":"PERF","name":"total_dur","ph":"B","pid":"1","ts":1762455078689000},{"cat":"PERF","name":"total_dur","ph":"E","pid":"1","ts":1762455085987000}]"#;

        // Parse the Chrome tracing JSON
        let events: Vec<serde_json::Value> =
            serde_json::from_str(chrome_trace_input).expect("Failed to parse Chrome tracing JSON");

        // Extract timing data from the parsed events
        let mut timing_map: HashMap<String, (u128, u128)> = HashMap::new();

        for event in &events {
            let name = event["name"].as_str().expect("Event should have a name");
            let ts = event["ts"].as_u64().expect("Event should have a timestamp") as u128;
            let phase = event["ph"].as_str().expect("Event should have a phase");

            if phase == "B" {
                // Begin event - store start time (in microseconds)
                timing_map.entry(name.to_string()).or_insert((ts, 0)).0 = ts;
            } else if phase == "E" {
                // End event - calculate duration (in microseconds)
                if let Some(entry) = timing_map.get_mut(name) {
                    entry.1 = ts - entry.0;
                }
            }
        }

        // Create TimedLikeMetrics from the parsed data
        // Convert from microseconds to milliseconds for internal storage
        let mut collection = LinkedList::new();
        for (name, (start_ts_us, duration_us)) in timing_map.iter() {
            collection.push_back((
                name.clone(),
                start_ts_us / 1000, // Convert microseconds to milliseconds
                duration_us / 1000, // Convert microseconds to milliseconds
            ));
        }

        let metrics = TimedLikeMetrics {
            duration_collection: collection,
        };

        // Generate Chrome tracing output - this should work without overflow
        let output = metrics
            .to_chrome_tracing()
            .expect("Should generate Chrome tracing output without overflow");

        // Parse the generated output
        let output_events: Vec<serde_json::Value> =
            serde_json::from_str(&output).expect("Should parse generated output");

        // Verify we have the correct number of events
        assert_eq!(
            output_events.len(),
            44,
            "Should have 44 events (22 metrics * 2)"
        );

        // Verify all expected metrics are present
        let metric_names: std::collections::HashSet<String> = output_events
            .iter()
            .filter_map(|e| e["name"].as_str().map(String::from))
            .collect();

        assert!(metric_names.contains("storage_config_new_dur"));
        assert!(metric_names.contains("analyzer_new_dur"));
        assert!(metric_names.contains("validate_connection_dur"));
        assert!(metric_names.contains("total_dur"));
        assert!(metric_names.contains("delta_reader"));
    }

    #[test]
    fn test_chrome_tracing_empty_metrics() {
        let metrics = TimedLikeMetrics {
            duration_collection: LinkedList::new(),
        };

        let output = metrics
            .to_chrome_tracing()
            .expect("Should handle empty metrics");

        let events: Vec<serde_json::Value> =
            serde_json::from_str(&output).expect("Should parse empty array");

        assert_eq!(
            events.len(),
            0,
            "Empty metrics should produce empty events array"
        );
    }

    #[test]
    fn test_chrome_tracing_single_metric() {
        let mut collection = LinkedList::new();
        collection.push_back(("test_metric".to_string(), 1000, 500));

        let metrics = TimedLikeMetrics {
            duration_collection: collection,
        };

        let output = metrics
            .to_chrome_tracing()
            .expect("Should generate output for single metric");

        let events: Vec<serde_json::Value> =
            serde_json::from_str(&output).expect("Should parse output");

        assert_eq!(
            events.len(),
            2,
            "Single metric should produce 2 events (B and E)"
        );

        // Verify Begin event
        assert_eq!(events[0]["name"].as_str(), Some("test_metric"));
        assert_eq!(events[0]["ph"].as_str(), Some("B"));
        assert_eq!(events[0]["ts"].as_u64(), Some(1000000)); // 1000ms * 1000

        // Verify End event
        assert_eq!(events[1]["name"].as_str(), Some("test_metric"));
        assert_eq!(events[1]["ph"].as_str(), Some("E"));
        assert_eq!(events[1]["ts"].as_u64(), Some(1500000)); // (1000 + 500)ms * 1000
    }

    #[test]
    fn test_chrome_tracing_duration_calculation() {
        let mut collection = LinkedList::new();
        // Add metrics with known durations
        collection.push_back(("metric1".to_string(), 0, 100));
        collection.push_back(("metric2".to_string(), 50, 200));
        collection.push_back(("metric3".to_string(), 100, 50));

        let metrics = TimedLikeMetrics {
            duration_collection: collection,
        };

        let output = metrics.to_chrome_tracing().expect("Should generate output");

        let events: Vec<serde_json::Value> =
            serde_json::from_str(&output).expect("Should parse output");

        // Should have 6 events (3 metrics * 2 events each)
        assert_eq!(events.len(), 6);

        // Verify metric1 duration
        let metric1_begin = events
            .iter()
            .find(|e| e["name"] == "metric1" && e["ph"] == "B")
            .expect("Should find metric1 begin");
        let metric1_end = events
            .iter()
            .find(|e| e["name"] == "metric1" && e["ph"] == "E")
            .expect("Should find metric1 end");

        let duration = metric1_end["ts"].as_u64().unwrap() - metric1_begin["ts"].as_u64().unwrap();
        assert_eq!(
            duration, 100000,
            "metric1 duration should be 100ms (100000 microseconds)"
        );
    }

    /// This test documents the proper way to use Chrome tracing data with TimedLikeMetrics
    ///
    /// Chrome tracing format uses microseconds for timestamps, but TimedLikeMetrics
    /// expects milliseconds internally and multiplies by 1000 when generating output.
    ///
    /// IMPORTANT: When parsing Chrome tracing JSON, you MUST divide timestamps by 1000
    /// to convert from microseconds to milliseconds before storing in TimedLikeMetrics.
    #[test]
    fn test_chrome_tracing_format_documentation() {
        // Chrome tracing uses microseconds
        let chrome_ts_microseconds: u128 = 1762455078689000;

        // TimedLikeMetrics expects milliseconds
        let internal_ts_milliseconds: u128 = chrome_ts_microseconds / 1000;

        // When to_chrome_tracing() is called, it multiplies by 1000 to get back to microseconds
        let output_ts_microseconds: u128 = internal_ts_milliseconds * 1000;

        // Verify the round-trip works correctly
        assert_eq!(
            chrome_ts_microseconds, output_ts_microseconds,
            "Chrome tracing timestamps should round-trip correctly"
        );

        println!("Chrome tracing format:");
        println!("  Input (microseconds):    {}", chrome_ts_microseconds);
        println!("  Internal (milliseconds): {}", internal_ts_milliseconds);
        println!("  Output (microseconds):   {}", output_ts_microseconds);
    }

    /// This test verifies that the ASCII Gantt chart bug is FIXED
    /// It uses the ACTUAL Chrome tracing data with absolute timestamps
    /// and should NOT panic after the fix to ascii_gantt.rs
    #[test]
    fn test_chrome_trace_with_absolute_timestamps_fixed() {
        let chrome_trace_input = r#"[{"cat":"PERF","name":"storage_config_new_dur","ph":"B","pid":"1","ts":1762455078689000},{"cat":"PERF","name":"storage_config_new_dur","ph":"E","pid":"1","ts":1762455078690000},{"cat":"PERF","name":"analyzer_new_dur","ph":"B","pid":"1","ts":1762455078691000},{"cat":"PERF","name":"analyzer_new_dur","ph":"E","pid":"1","ts":1762455078972000},{"cat":"PERF","name":"validate_connection_dur","ph":"B","pid":"1","ts":1762455078973000},{"cat":"PERF","name":"validate_connection_dur","ph":"E","pid":"1","ts":1762455080930000},{"cat":"PERF","name":"discover_partitions","ph":"B","pid":"1","ts":1762455080932000},{"cat":"PERF","name":"discover_partitions","ph":"E","pid":"1","ts":1762455081493000},{"cat":"PERF","name":"list_files_parallel","ph":"B","pid":"1","ts":1762455081495000},{"cat":"PERF","name":"list_files_parallel","ph":"E","pid":"1","ts":1762455082170000},{"cat":"PERF","name":"detect_table_type","ph":"B","pid":"1","ts":1762455082171000},{"cat":"PERF","name":"detect_table_type","ph":"E","pid":"1","ts":1762455082172000},{"cat":"PERF","name":"categorize_files","ph":"B","pid":"1","ts":1762455082173000},{"cat":"PERF","name":"categorize_files","ph":"E","pid":"1","ts":1762455082173000},{"cat":"PERF","name":"find_referenced_files","ph":"B","pid":"1","ts":1762455082174000},{"cat":"PERF","name":"find_referenced_files","ph":"E","pid":"1","ts":1762455082683000},{"cat":"PERF","name":"find_unreferenced_files","ph":"B","pid":"1","ts":1762455082684000},{"cat":"PERF","name":"find_unreferenced_files","ph":"E","pid":"1","ts":1762455082685000},{"cat":"PERF","name":"analyze_partitioning","ph":"B","pid":"1","ts":1762455082687000},{"cat":"PERF","name":"analyze_partitioning","ph":"E","pid":"1","ts":1762455082689000},{"cat":"PERF","name":"update_metrics_from_metadata","ph":"B","pid":"1","ts":1762455082689000},{"cat":"PERF","name":"update_metrics_from_metadata","ph":"E","pid":"1","ts":1762455083173000},{"cat":"PERF","name":"calculate_file_size_distribution","ph":"B","pid":"1","ts":1762455083175000},{"cat":"PERF","name":"calculate_file_size_distribution","ph":"E","pid":"1","ts":1762455083175000},{"cat":"PERF","name":"calculate_metadata_health","ph":"B","pid":"1","ts":1762455083176000},{"cat":"PERF","name":"calculate_metadata_health","ph":"E","pid":"1","ts":1762455083176000},{"cat":"PERF","name":"calculate_data_skew","ph":"B","pid":"1","ts":1762455083177000},{"cat":"PERF","name":"calculate_data_skew","ph":"E","pid":"1","ts":1762455083179000},{"cat":"PERF","name":"calculate_snapshot_health","ph":"B","pid":"1","ts":1762455083179000},{"cat":"PERF","name":"calculate_snapshot_health","ph":"E","pid":"1","ts":1762455083179000},{"cat":"PERF","name":"analyze_file_compaction","ph":"B","pid":"1","ts":1762455083180000},{"cat":"PERF","name":"analyze_file_compaction","ph":"E","pid":"1","ts":1762455083180000},{"cat":"PERF","name":"generate_recommendations","ph":"B","pid":"1","ts":1762455083181000},{"cat":"PERF","name":"generate_recommendations","ph":"E","pid":"1","ts":1762455083181000},{"cat":"PERF","name":"calculate_health_score","ph":"B","pid":"1","ts":1762455083182000},{"cat":"PERF","name":"calculate_health_score","ph":"E","pid":"1","ts":1762455083182000},{"cat":"PERF","name":"analyze_after_validation_dur","ph":"B","pid":"1","ts":1762455081495000},{"cat":"PERF","name":"analyze_after_validation_dur","ph":"E","pid":"1","ts":1762455083183000},{"cat":"PERF","name":"delta_reader","ph":"B","pid":"1","ts":1762455083183000},{"cat":"PERF","name":"delta_reader","ph":"E","pid":"1","ts":1762455085985000},{"cat":"PERF","name":"analyze_total_dur","ph":"B","pid":"1","ts":1762455078972000},{"cat":"PERF","name":"analyze_total_dur","ph":"E","pid":"1","ts":1762455085987000},{"cat":"PERF","name":"total_dur","ph":"B","pid":"1","ts":1762455078689000},{"cat":"PERF","name":"total_dur","ph":"E","pid":"1","ts":1762455085987000}]"#;

        // Parse the Chrome tracing JSON
        let events: Vec<serde_json::Value> =
            serde_json::from_str(chrome_trace_input).expect("Failed to parse Chrome tracing JSON");

        // Extract timing data from the parsed events
        let mut timing_map: HashMap<String, (u128, u128)> = HashMap::new();

        for event in &events {
            let name = event["name"].as_str().expect("Event should have a name");
            let ts = event["ts"].as_u64().expect("Event should have a timestamp") as u128;
            let phase = event["ph"].as_str().expect("Event should have a phase");

            if phase == "B" {
                timing_map.entry(name.to_string()).or_insert((ts, 0)).0 = ts;
            } else if phase == "E" {
                if let Some(entry) = timing_map.get_mut(name) {
                    entry.1 = ts - entry.0;
                }
            }
        }

        // Create TimedLikeMetrics with ABSOLUTE timestamps (in milliseconds)
        // This is the scenario that was causing the overflow bug
        let mut collection = LinkedList::new();
        for (name, (start_ts_us, duration_us)) in timing_map.iter() {
            // Convert from microseconds to milliseconds
            // These will be LARGE numbers like 1762455078689
            collection.push_back((name.clone(), start_ts_us / 1000, duration_us / 1000));
        }

        let metrics = TimedLikeMetrics {
            duration_collection: collection,
        };

        // This should NOW work without panic after the fix to ascii_gantt.rs
        let gantt_output = metrics
            .duration_collection_as_gantt(None)
            .expect("Should generate ASCII Gantt chart with absolute timestamps after fix");

        println!("\nASCII Gantt Chart with absolute timestamps:");
        println!("{}", gantt_output);

        // Verify the output contains expected metrics
        assert!(gantt_output.contains("storage_config_new_dur"));
        assert!(gantt_output.contains("analyzer_new_dur"));
        assert!(gantt_output.contains("total_dur"));
        assert!(gantt_output.contains("Timeline"));
    }

    /// This test parses the FULL Chrome tracing data and works correctly
    /// by using RELATIVE timestamps (offset from the minimum) instead of absolute timestamps
    #[test]
    fn test_chrome_trace_with_relative_timestamps() {
        let chrome_trace_input = r#"[{"cat":"PERF","name":"storage_config_new_dur","ph":"B","pid":"1","ts":1762455078689000},{"cat":"PERF","name":"storage_config_new_dur","ph":"E","pid":"1","ts":1762455078690000},{"cat":"PERF","name":"analyzer_new_dur","ph":"B","pid":"1","ts":1762455078691000},{"cat":"PERF","name":"analyzer_new_dur","ph":"E","pid":"1","ts":1762455078972000},{"cat":"PERF","name":"validate_connection_dur","ph":"B","pid":"1","ts":1762455078973000},{"cat":"PERF","name":"validate_connection_dur","ph":"E","pid":"1","ts":1762455080930000},{"cat":"PERF","name":"discover_partitions","ph":"B","pid":"1","ts":1762455080932000},{"cat":"PERF","name":"discover_partitions","ph":"E","pid":"1","ts":1762455081493000},{"cat":"PERF","name":"list_files_parallel","ph":"B","pid":"1","ts":1762455081495000},{"cat":"PERF","name":"list_files_parallel","ph":"E","pid":"1","ts":1762455082170000},{"cat":"PERF","name":"detect_table_type","ph":"B","pid":"1","ts":1762455082171000},{"cat":"PERF","name":"detect_table_type","ph":"E","pid":"1","ts":1762455082172000},{"cat":"PERF","name":"categorize_files","ph":"B","pid":"1","ts":1762455082173000},{"cat":"PERF","name":"categorize_files","ph":"E","pid":"1","ts":1762455082173000},{"cat":"PERF","name":"find_referenced_files","ph":"B","pid":"1","ts":1762455082174000},{"cat":"PERF","name":"find_referenced_files","ph":"E","pid":"1","ts":1762455082683000},{"cat":"PERF","name":"find_unreferenced_files","ph":"B","pid":"1","ts":1762455082684000},{"cat":"PERF","name":"find_unreferenced_files","ph":"E","pid":"1","ts":1762455082685000},{"cat":"PERF","name":"analyze_partitioning","ph":"B","pid":"1","ts":1762455082687000},{"cat":"PERF","name":"analyze_partitioning","ph":"E","pid":"1","ts":1762455082689000},{"cat":"PERF","name":"update_metrics_from_metadata","ph":"B","pid":"1","ts":1762455082689000},{"cat":"PERF","name":"update_metrics_from_metadata","ph":"E","pid":"1","ts":1762455083173000},{"cat":"PERF","name":"calculate_file_size_distribution","ph":"B","pid":"1","ts":1762455083175000},{"cat":"PERF","name":"calculate_file_size_distribution","ph":"E","pid":"1","ts":1762455083175000},{"cat":"PERF","name":"calculate_metadata_health","ph":"B","pid":"1","ts":1762455083176000},{"cat":"PERF","name":"calculate_metadata_health","ph":"E","pid":"1","ts":1762455083176000},{"cat":"PERF","name":"calculate_data_skew","ph":"B","pid":"1","ts":1762455083177000},{"cat":"PERF","name":"calculate_data_skew","ph":"E","pid":"1","ts":1762455083179000},{"cat":"PERF","name":"calculate_snapshot_health","ph":"B","pid":"1","ts":1762455083179000},{"cat":"PERF","name":"calculate_snapshot_health","ph":"E","pid":"1","ts":1762455083179000},{"cat":"PERF","name":"analyze_file_compaction","ph":"B","pid":"1","ts":1762455083180000},{"cat":"PERF","name":"analyze_file_compaction","ph":"E","pid":"1","ts":1762455083180000},{"cat":"PERF","name":"generate_recommendations","ph":"B","pid":"1","ts":1762455083181000},{"cat":"PERF","name":"generate_recommendations","ph":"E","pid":"1","ts":1762455083181000},{"cat":"PERF","name":"calculate_health_score","ph":"B","pid":"1","ts":1762455083182000},{"cat":"PERF","name":"calculate_health_score","ph":"E","pid":"1","ts":1762455083182000},{"cat":"PERF","name":"analyze_after_validation_dur","ph":"B","pid":"1","ts":1762455081495000},{"cat":"PERF","name":"analyze_after_validation_dur","ph":"E","pid":"1","ts":1762455083183000},{"cat":"PERF","name":"delta_reader","ph":"B","pid":"1","ts":1762455083183000},{"cat":"PERF","name":"delta_reader","ph":"E","pid":"1","ts":1762455085985000},{"cat":"PERF","name":"analyze_total_dur","ph":"B","pid":"1","ts":1762455078972000},{"cat":"PERF","name":"analyze_total_dur","ph":"E","pid":"1","ts":1762455085987000},{"cat":"PERF","name":"total_dur","ph":"B","pid":"1","ts":1762455078689000},{"cat":"PERF","name":"total_dur","ph":"E","pid":"1","ts":1762455085987000}]"#;

        // Parse the Chrome tracing JSON
        let events: Vec<serde_json::Value> =
            serde_json::from_str(chrome_trace_input).expect("Failed to parse Chrome tracing JSON");

        // Extract timing data from the parsed events
        let mut timing_map: HashMap<String, (u128, u128)> = HashMap::new();

        for event in &events {
            let name = event["name"].as_str().expect("Event should have a name");
            let ts = event["ts"].as_u64().expect("Event should have a timestamp") as u128;
            let phase = event["ph"].as_str().expect("Event should have a phase");

            if phase == "B" {
                timing_map.entry(name.to_string()).or_insert((ts, 0)).0 = ts;
            } else if phase == "E" {
                if let Some(entry) = timing_map.get_mut(name) {
                    entry.1 = ts - entry.0;
                }
            }
        }

        // Find the minimum timestamp to use as offset
        let min_timestamp = timing_map
            .values()
            .map(|(start, _)| *start)
            .min()
            .unwrap_or(0);

        println!("Min timestamp (microseconds): {}", min_timestamp);
        println!("Min timestamp (milliseconds): {}", min_timestamp / 1000);

        // Create TimedLikeMetrics with RELATIVE timestamps (offset from minimum)
        let mut collection = LinkedList::new();
        for (name, (start_ts_us, duration_us)) in timing_map.iter() {
            // Use relative timestamps: subtract the minimum and convert to milliseconds
            let relative_start_ms = (start_ts_us - min_timestamp) / 1000;
            let duration_ms = duration_us / 1000;

            collection.push_back((name.clone(), relative_start_ms, duration_ms));
        }

        let metrics = TimedLikeMetrics {
            duration_collection: collection,
        };

        // Test Chrome tracing generation - should work fine
        let chrome_output = metrics
            .to_chrome_tracing()
            .expect("Should generate Chrome tracing output");

        let output_events: Vec<serde_json::Value> =
            serde_json::from_str(&chrome_output).expect("Should parse output");

        assert_eq!(output_events.len(), 44, "Should have 44 events");

        // Test ASCII Gantt generation - should work now with relative timestamps
        let gantt_output = metrics
            .duration_collection_as_gantt(None)
            .expect("Should generate ASCII Gantt chart with relative timestamps");

        println!("\nASCII Gantt Chart:");
        println!("{}", gantt_output);

        // Verify the output contains expected metrics
        assert!(gantt_output.contains("storage_config_new_dur"));
        assert!(gantt_output.contains("analyzer_new_dur"));
        assert!(gantt_output.contains("total_dur"));
    }

    // HealthMetrics tests
    #[test]
    fn test_health_metrics_new() {
        let metrics = HealthMetrics::new();

        assert_eq!(metrics.total_files, 0);
        assert_eq!(metrics.total_size_bytes, 0);
        assert_eq!(metrics.partition_count, 0);
        assert_eq!(metrics.avg_file_size_bytes, 0.0);
        assert_eq!(metrics.health_score, 0.0);
        assert_eq!(metrics.file_size_distribution.small_files, 0);
        assert_eq!(metrics.file_size_distribution.medium_files, 0);
        assert_eq!(metrics.file_size_distribution.large_files, 0);
        assert_eq!(metrics.file_size_distribution.very_large_files, 0);
        assert!(metrics.unreferenced_files.is_empty());
        assert!(metrics.partitions.is_empty());
        assert!(metrics.recommendations.is_empty());
        assert!(metrics.clustering.is_none());
        assert!(metrics.deletion_vector_metrics.is_none());
        assert!(metrics.schema_evolution.is_none());
        assert!(metrics.time_travel_metrics.is_none());
        assert!(metrics.table_constraints.is_none());
        assert!(metrics.file_compaction.is_none());
    }

    #[test]
    fn test_health_metrics_default() {
        let metrics = HealthMetrics::default();

        assert_eq!(metrics.total_files, 0);
        assert_eq!(metrics.health_score, 0.0);
    }

    #[test]
    fn test_calculate_health_score_perfect() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 100;
        metrics.file_size_distribution.medium_files = 100; // All medium files

        let score = metrics.calculate_health_score();

        assert!(
            (0.9..=1.0).contains(&score),
            "Perfect health should score high"
        );
    }

    #[test]
    fn test_calculate_health_score_with_unreferenced_files() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 100;
        metrics.unreferenced_files = vec![
            FileInfo {
                path: "file1.parquet".to_string(),
                size_bytes: 1024,
                last_modified: None,
                is_referenced: false,
            };
            30
        ]; // 30% unreferenced

        let score = metrics.calculate_health_score();

        // Should be penalized by 30% * 0.3 = 0.09
        assert!(score < 1.0);
        assert!((0.85..=0.95).contains(&score));
    }

    #[test]
    fn test_calculate_health_score_with_small_files() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 100;
        metrics.file_size_distribution.small_files = 60; // 60% small files

        let score = metrics.calculate_health_score();

        // Should be penalized by 60% * 0.2 = 0.12
        assert!(score < 1.0);
        assert!((0.8..=0.9).contains(&score));
    }

    #[test]
    fn test_calculate_health_score_with_very_large_files() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 100;
        metrics.file_size_distribution.very_large_files = 20; // 20% very large

        let score = metrics.calculate_health_score();

        // Should be penalized by 20% * 0.1 = 0.02
        assert!((0.95..=1.0).contains(&score));
    }

    #[test]
    fn test_calculate_health_score_with_data_skew() {
        let mut metrics = HealthMetrics::new();
        metrics.data_skew.partition_skew_score = 0.8; // High partition skew
        metrics.data_skew.file_size_skew_score = 0.6; // Moderate file size skew

        let score = metrics.calculate_health_score();

        // Should be penalized by 0.8 * 0.15 + 0.6 * 0.1 = 0.12 + 0.06 = 0.18
        assert!((0.75..=0.85).contains(&score));
    }

    #[test]
    fn test_calculate_health_score_clamped() {
        let mut metrics = HealthMetrics::new();
        // Set extreme values that would result in negative score
        metrics.total_files = 100;
        metrics.unreferenced_files = vec![
            FileInfo {
                path: "file.parquet".to_string(),
                size_bytes: 1024,
                last_modified: None,
                is_referenced: false,
            };
            100
        ];
        metrics.file_size_distribution.small_files = 100;
        metrics.data_skew.partition_skew_score = 1.0;
        metrics.data_skew.file_size_skew_score = 1.0;

        let score = metrics.calculate_health_score();

        // Score should be clamped to [0.0, 1.0]
        assert!((0.0..=1.0).contains(&score));
    }

    #[test]
    fn test_calculate_data_skew_empty_partitions() {
        let mut metrics = HealthMetrics::new();

        metrics.calculate_data_skew();

        assert_eq!(metrics.data_skew.partition_skew_score, 0.0);
        assert_eq!(metrics.data_skew.file_size_skew_score, 0.0);
    }

    #[test]
    fn test_calculate_data_skew_balanced() {
        let mut metrics = HealthMetrics::new();
        // Create balanced partitions
        metrics.partitions = vec![
            PartitionInfo {
                partition_values: HashMap::new(),
                file_count: 10,
                total_size_bytes: 1000,
                avg_file_size_bytes: 100.0,
                files: Vec::new(),
            };
            5
        ];

        metrics.calculate_data_skew();

        // Perfectly balanced should have low skew
        assert!(metrics.data_skew.partition_skew_score < 0.1);
        assert_eq!(metrics.data_skew.largest_partition_size, 1000);
        assert_eq!(metrics.data_skew.smallest_partition_size, 1000);
        assert_eq!(metrics.data_skew.avg_partition_size, 1000);
    }

    #[test]
    fn test_calculate_data_skew_unbalanced() {
        let mut metrics = HealthMetrics::new();
        // Create unbalanced partitions
        metrics.partitions = vec![
            PartitionInfo {
                partition_values: HashMap::new(),
                file_count: 100,
                total_size_bytes: 10000,
                avg_file_size_bytes: 100.0,
                files: Vec::new(),
            },
            PartitionInfo {
                partition_values: HashMap::new(),
                file_count: 10,
                total_size_bytes: 1000,
                avg_file_size_bytes: 100.0,
                files: Vec::new(),
            },
            PartitionInfo {
                partition_values: HashMap::new(),
                file_count: 5,
                total_size_bytes: 500,
                avg_file_size_bytes: 100.0,
                files: Vec::new(),
            },
        ];

        metrics.calculate_data_skew();

        // Unbalanced should have higher skew
        assert!(metrics.data_skew.partition_skew_score > 0.3);
        assert_eq!(metrics.data_skew.largest_partition_size, 10000);
        assert_eq!(metrics.data_skew.smallest_partition_size, 500);
    }

    #[test]
    fn test_calculate_snapshot_health_low_count() {
        let mut metrics = HealthMetrics::new();

        metrics.calculate_snapshot_health(10);

        assert_eq!(metrics.snapshot_health.snapshot_count, 10);
        assert_eq!(metrics.snapshot_health.snapshot_retention_risk, 0.0);
    }

    #[test]
    fn test_calculate_snapshot_health_medium_count() {
        let mut metrics = HealthMetrics::new();

        metrics.calculate_snapshot_health(30);

        assert_eq!(metrics.snapshot_health.snapshot_count, 30);
        assert_eq!(metrics.snapshot_health.snapshot_retention_risk, 0.2);
    }

    #[test]
    fn test_calculate_snapshot_health_high_count() {
        let mut metrics = HealthMetrics::new();

        metrics.calculate_snapshot_health(75);

        assert_eq!(metrics.snapshot_health.snapshot_count, 75);
        assert_eq!(metrics.snapshot_health.snapshot_retention_risk, 0.5);
    }

    #[test]
    fn test_calculate_snapshot_health_very_high_count() {
        let mut metrics = HealthMetrics::new();

        metrics.calculate_snapshot_health(150);

        assert_eq!(metrics.snapshot_health.snapshot_count, 150);
        assert_eq!(metrics.snapshot_health.snapshot_retention_risk, 0.8);
    }

    #[test]
    fn test_generate_recommendations_unreferenced_files() {
        let mut metrics = HealthMetrics::new();
        metrics.unreferenced_files = vec![
            FileInfo {
                path: "file1.parquet".to_string(),
                size_bytes: 1024,
                last_modified: None,
                is_referenced: false,
            },
            FileInfo {
                path: "file2.parquet".to_string(),
                size_bytes: 2048,
                last_modified: None,
                is_referenced: false,
            },
        ];
        metrics.unreferenced_size_bytes = 3072;

        metrics.generate_recommendations();

        assert!(!metrics.recommendations.is_empty());
        assert!(metrics.recommendations[0].contains("unreferenced files"));
        assert!(metrics.recommendations[0].contains("3072"));
    }

    #[test]
    fn test_generate_recommendations_small_files() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 100;
        metrics.file_size_distribution.small_files = 60; // 60% small files

        metrics.generate_recommendations();

        assert!(!metrics.recommendations.is_empty());
        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("small files") && r.contains("compacting")));
    }

    #[test]
    fn test_generate_recommendations_very_large_files() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 100;
        metrics.file_size_distribution.very_large_files = 15; // 15% very large

        metrics.generate_recommendations();

        assert!(!metrics.recommendations.is_empty());
        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("very large files") && r.contains("splitting")));
    }

    #[test]
    fn test_generate_recommendations_too_many_files_per_partition() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 1000;
        metrics.partition_count = 5; // 200 files per partition

        metrics.generate_recommendations();

        assert!(!metrics.recommendations.is_empty());
        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("files per partition") && r.contains("repartitioning")));
    }

    #[test]
    fn test_generate_recommendations_too_few_files_per_partition() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 10;
        metrics.partition_count = 5; // 2 files per partition

        metrics.generate_recommendations();

        assert!(!metrics.recommendations.is_empty());
        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("Low number of files") && r.contains("consolidating")));
    }

    #[test]
    fn test_generate_recommendations_empty_partitions() {
        let mut metrics = HealthMetrics::new();
        metrics.partitions = vec![
            PartitionInfo {
                partition_values: HashMap::new(),
                file_count: 0,
                total_size_bytes: 0,
                avg_file_size_bytes: 0.0,
                files: Vec::new(),
            },
            PartitionInfo {
                partition_values: HashMap::new(),
                file_count: 10,
                total_size_bytes: 1000,
                avg_file_size_bytes: 100.0,
                files: Vec::new(),
            },
        ];

        metrics.generate_recommendations();

        assert!(!metrics.recommendations.is_empty());
        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("empty partitions")));
    }

    #[test]
    fn test_generate_recommendations_high_partition_skew() {
        let mut metrics = HealthMetrics::new();
        metrics.data_skew.partition_skew_score = 0.8;

        metrics.generate_recommendations();

        assert!(!metrics.recommendations.is_empty());
        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("partition skew") && r.contains("repartitioning")));
    }

    #[test]
    fn test_generate_recommendations_high_file_size_skew() {
        let mut metrics = HealthMetrics::new();
        metrics.data_skew.file_size_skew_score = 0.7;

        metrics.generate_recommendations();

        assert!(!metrics.recommendations.is_empty());
        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("file size skew") && r.contains("OPTIMIZE")));
    }

    #[test]
    fn test_generate_recommendations_large_metadata() {
        let mut metrics = HealthMetrics::new();
        metrics.metadata_health.metadata_total_size_bytes = 60 * 1024 * 1024; // 60MB

        metrics.generate_recommendations();

        assert!(!metrics.recommendations.is_empty());
        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("metadata size") && r.contains("VACUUM")));
    }

    #[test]
    fn test_generate_recommendations_high_snapshot_retention_risk() {
        let mut metrics = HealthMetrics::new();
        metrics.snapshot_health.snapshot_retention_risk = 0.9;

        metrics.generate_recommendations();

        assert!(!metrics.recommendations.is_empty());
        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("snapshot retention risk") && r.contains("VACUUM")));
    }

    #[test]
    fn test_generate_recommendations_clustering_high_files_per_cluster() {
        let mut metrics = HealthMetrics::new();
        metrics.clustering = Some(ClusteringInfo {
            clustering_columns: vec!["col1".to_string()],
            cluster_count: 5,
            avg_files_per_cluster: 60.0, // > 50
            avg_cluster_size_bytes: 1024.0 * 1024.0,
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("files per cluster") && r.contains("optimizing")));
    }

    #[test]
    fn test_generate_recommendations_clustering_too_many_columns() {
        let mut metrics = HealthMetrics::new();
        metrics.clustering = Some(ClusteringInfo {
            clustering_columns: vec![
                "col1".to_string(),
                "col2".to_string(),
                "col3".to_string(),
                "col4".to_string(),
                "col5".to_string(),
            ],
            cluster_count: 10,
            avg_files_per_cluster: 5.0,
            avg_cluster_size_bytes: 1024.0 * 1024.0,
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("Too many clustering columns")));
    }

    #[test]
    fn test_generate_recommendations_clustering_no_columns() {
        let mut metrics = HealthMetrics::new();
        metrics.clustering = Some(ClusteringInfo {
            clustering_columns: vec![],
            cluster_count: 0,
            avg_files_per_cluster: 0.0,
            avg_cluster_size_bytes: 0.0,
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("No clustering detected")));
    }

    #[test]
    fn test_generate_recommendations_deletion_vectors_high_impact() {
        let mut metrics = HealthMetrics::new();
        metrics.deletion_vector_metrics = Some(DeletionVectorMetrics {
            deletion_vector_count: 10,
            total_deletion_vector_size_bytes: 1024,
            avg_deletion_vector_size_bytes: 102.4,
            deletion_vector_age_days: 5.0,
            deleted_rows_count: 100,
            deletion_vector_impact_score: 0.8, // > 0.7
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("deletion vector impact") && r.contains("VACUUM")));
    }

    #[test]
    fn test_generate_recommendations_deletion_vectors_many_vectors() {
        let mut metrics = HealthMetrics::new();
        metrics.deletion_vector_metrics = Some(DeletionVectorMetrics {
            deletion_vector_count: 60, // > 50
            total_deletion_vector_size_bytes: 1024,
            avg_deletion_vector_size_bytes: 17.0,
            deletion_vector_age_days: 5.0,
            deleted_rows_count: 100,
            deletion_vector_impact_score: 0.3,
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("Many deletion vectors")));
    }

    #[test]
    fn test_generate_recommendations_deletion_vectors_old() {
        let mut metrics = HealthMetrics::new();
        metrics.deletion_vector_metrics = Some(DeletionVectorMetrics {
            deletion_vector_count: 5,
            total_deletion_vector_size_bytes: 1024,
            avg_deletion_vector_size_bytes: 204.8,
            deletion_vector_age_days: 45.0, // > 30
            deleted_rows_count: 100,
            deletion_vector_impact_score: 0.3,
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("Old deletion vectors")));
    }

    #[test]
    fn test_generate_recommendations_schema_unstable() {
        let mut metrics = HealthMetrics::new();
        metrics.schema_evolution = Some(SchemaEvolutionMetrics {
            total_schema_changes: 10,
            breaking_changes: 2,
            non_breaking_changes: 8,
            schema_stability_score: 0.3, // < 0.5
            days_since_last_change: 30.0,
            schema_change_frequency: 0.5,
            current_schema_version: 10,
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("Unstable schema")));
    }

    #[test]
    fn test_generate_recommendations_schema_many_breaking_changes() {
        let mut metrics = HealthMetrics::new();
        metrics.schema_evolution = Some(SchemaEvolutionMetrics {
            total_schema_changes: 10,
            breaking_changes: 7, // > 5
            non_breaking_changes: 3,
            schema_stability_score: 0.6,
            days_since_last_change: 30.0,
            schema_change_frequency: 0.5,
            current_schema_version: 10,
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("breaking schema changes")));
    }

    #[test]
    fn test_generate_recommendations_schema_high_frequency() {
        let mut metrics = HealthMetrics::new();
        metrics.schema_evolution = Some(SchemaEvolutionMetrics {
            total_schema_changes: 10,
            breaking_changes: 1,
            non_breaking_changes: 9,
            schema_stability_score: 0.7,
            days_since_last_change: 30.0,
            schema_change_frequency: 1.5, // > 1.0
            current_schema_version: 10,
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("schema change frequency")));
    }

    #[test]
    fn test_generate_recommendations_schema_recent_change() {
        let mut metrics = HealthMetrics::new();
        metrics.schema_evolution = Some(SchemaEvolutionMetrics {
            total_schema_changes: 5,
            breaking_changes: 0,
            non_breaking_changes: 5,
            schema_stability_score: 0.9,
            days_since_last_change: 0.5, // < 1.0
            schema_change_frequency: 0.1,
            current_schema_version: 5,
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("Recent schema changes")));
    }

    #[test]
    fn test_generate_recommendations_time_travel_high_cost() {
        let mut metrics = HealthMetrics::new();
        metrics.time_travel_metrics = Some(TimeTravelMetrics {
            total_snapshots: 50,
            oldest_snapshot_age_days: 90.0,
            newest_snapshot_age_days: 0.5,
            total_historical_size_bytes: 1024 * 1024 * 1024,
            avg_snapshot_size_bytes: 20.0 * 1024.0 * 1024.0,
            storage_cost_impact_score: 0.8, // > 0.7
            retention_efficiency_score: 0.6,
            recommended_retention_days: 30,
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("time travel storage costs")));
    }

    #[test]
    fn test_generate_recommendations_time_travel_inefficient_retention() {
        let mut metrics = HealthMetrics::new();
        metrics.time_travel_metrics = Some(TimeTravelMetrics {
            total_snapshots: 50,
            oldest_snapshot_age_days: 90.0,
            newest_snapshot_age_days: 0.5,
            total_historical_size_bytes: 1024 * 1024 * 1024,
            avg_snapshot_size_bytes: 20.0 * 1024.0 * 1024.0,
            storage_cost_impact_score: 0.3,
            retention_efficiency_score: 0.3, // < 0.5
            recommended_retention_days: 30,
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("Inefficient snapshot retention")));
    }

    #[test]
    fn test_generate_recommendations_time_travel_high_snapshot_count() {
        let mut metrics = HealthMetrics::new();
        metrics.time_travel_metrics = Some(TimeTravelMetrics {
            total_snapshots: 1500, // > 1000
            oldest_snapshot_age_days: 365.0,
            newest_snapshot_age_days: 0.1,
            total_historical_size_bytes: 10 * 1024 * 1024 * 1024,
            avg_snapshot_size_bytes: 6.7 * 1024.0 * 1024.0,
            storage_cost_impact_score: 0.5,
            retention_efficiency_score: 0.6,
            recommended_retention_days: 30,
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("High snapshot count")));
    }

    #[test]
    fn test_generate_recommendations_constraints_low_quality() {
        let mut metrics = HealthMetrics::new();
        metrics.table_constraints = Some(TableConstraintsMetrics {
            total_constraints: 5,
            check_constraints: 1,
            not_null_constraints: 3,
            unique_constraints: 1,
            foreign_key_constraints: 0,
            constraint_violation_risk: 0.2,
            data_quality_score: 0.3, // < 0.5
            constraint_coverage_score: 0.5,
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("Low data quality score")));
    }

    #[test]
    fn test_generate_recommendations_constraints_high_violation_risk() {
        let mut metrics = HealthMetrics::new();
        metrics.table_constraints = Some(TableConstraintsMetrics {
            total_constraints: 5,
            check_constraints: 1,
            not_null_constraints: 3,
            unique_constraints: 1,
            foreign_key_constraints: 0,
            constraint_violation_risk: 0.8, // > 0.7
            data_quality_score: 0.7,
            constraint_coverage_score: 0.5,
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("constraint violation risk")));
    }

    #[test]
    fn test_generate_recommendations_constraints_low_coverage() {
        let mut metrics = HealthMetrics::new();
        metrics.table_constraints = Some(TableConstraintsMetrics {
            total_constraints: 2,
            check_constraints: 0,
            not_null_constraints: 2,
            unique_constraints: 0,
            foreign_key_constraints: 0,
            constraint_violation_risk: 0.2,
            data_quality_score: 0.7,
            constraint_coverage_score: 0.2, // < 0.3
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("Low constraint coverage")));
    }

    #[test]
    fn test_generate_recommendations_compaction_high_opportunity() {
        let mut metrics = HealthMetrics::new();
        metrics.file_compaction = Some(FileCompactionMetrics {
            compaction_opportunity_score: 0.8, // > 0.7
            small_files_count: 100,
            small_files_size_bytes: 50 * 1024 * 1024,
            potential_compaction_files: 80,
            estimated_compaction_savings_bytes: 20 * 1024 * 1024,
            recommended_target_file_size_bytes: 128 * 1024 * 1024,
            compaction_priority: "high".to_string(),
            z_order_opportunity: false,
            z_order_columns: vec![],
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("file compaction opportunity")));
    }

    #[test]
    fn test_generate_recommendations_compaction_critical_priority() {
        let mut metrics = HealthMetrics::new();
        metrics.file_compaction = Some(FileCompactionMetrics {
            compaction_opportunity_score: 0.5,
            small_files_count: 200,
            small_files_size_bytes: 100 * 1024 * 1024,
            potential_compaction_files: 180,
            estimated_compaction_savings_bytes: 50 * 1024 * 1024,
            recommended_target_file_size_bytes: 128 * 1024 * 1024,
            compaction_priority: "critical".to_string(),
            z_order_opportunity: false,
            z_order_columns: vec![],
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("Critical compaction priority")));
    }

    #[test]
    fn test_generate_recommendations_compaction_z_order_opportunity() {
        let mut metrics = HealthMetrics::new();
        metrics.file_compaction = Some(FileCompactionMetrics {
            compaction_opportunity_score: 0.5,
            small_files_count: 50,
            small_files_size_bytes: 25 * 1024 * 1024,
            potential_compaction_files: 40,
            estimated_compaction_savings_bytes: 10 * 1024 * 1024,
            recommended_target_file_size_bytes: 128 * 1024 * 1024,
            compaction_priority: "medium".to_string(),
            z_order_opportunity: true,
            z_order_columns: vec!["date".to_string(), "region".to_string()],
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("Z-ordering opportunity") && r.contains("date, region")));
    }

    #[test]
    fn test_generate_recommendations_compaction_significant_savings() {
        let mut metrics = HealthMetrics::new();
        metrics.file_compaction = Some(FileCompactionMetrics {
            compaction_opportunity_score: 0.5,
            small_files_count: 500,
            small_files_size_bytes: 500 * 1024 * 1024,
            potential_compaction_files: 400,
            estimated_compaction_savings_bytes: 200 * 1024 * 1024, // > 100MB
            recommended_target_file_size_bytes: 128 * 1024 * 1024,
            compaction_priority: "medium".to_string(),
            z_order_opportunity: false,
            z_order_columns: vec![],
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("Significant compaction savings")));
    }

    // HealthReport tests
    #[test]
    fn test_health_report_to_json() {
        let report = HealthReport {
            table_path: "/path/to/table".to_string(),
            table_type: "delta".to_string(),
            analysis_timestamp: "2024-01-01T00:00:00Z".to_string(),
            metrics: HealthMetrics::new(),
            health_score: 0.85,
            timed_metrics: TimedLikeMetrics {
                duration_collection: LinkedList::new(),
            },
        };

        let json = report.to_json(false).expect("Should serialize to JSON");

        assert!(json.contains("table_path"));
        assert!(json.contains("/path/to/table"));
        assert!(json.contains("delta"));
        assert!(json.contains("0.85"));
    }

    #[test]
    fn test_health_report_to_json_exclude_files() {
        let mut metrics = HealthMetrics::new();
        metrics.unreferenced_files = vec![FileInfo {
            path: "file1.parquet".to_string(),
            size_bytes: 1024,
            last_modified: None,
            is_referenced: false,
        }];
        metrics.partitions = vec![PartitionInfo {
            partition_values: HashMap::new(),
            file_count: 1,
            total_size_bytes: 1024,
            avg_file_size_bytes: 1024.0,
            files: vec![FileInfo {
                path: "file2.parquet".to_string(),
                size_bytes: 1024,
                last_modified: None,
                is_referenced: true,
            }],
        }];

        let report = HealthReport {
            table_path: "/path/to/table".to_string(),
            table_type: "delta".to_string(),
            analysis_timestamp: "2024-01-01T00:00:00Z".to_string(),
            metrics,
            health_score: 0.85,
            timed_metrics: TimedLikeMetrics {
                duration_collection: LinkedList::new(),
            },
        };

        let json = report.to_json(true).expect("Should serialize to JSON");

        // Should not contain file paths when exclude_files is true
        assert!(!json.contains("file1.parquet"));
        assert!(!json.contains("file2.parquet"));
    }

    #[test]
    fn test_health_report_display() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 100;
        metrics.total_size_bytes = 1024 * 1024 * 1024; // 1GB
        metrics.avg_file_size_bytes = 10.0 * 1024.0 * 1024.0; // 10MB
        metrics.partition_count = 5;
        metrics.file_size_distribution.small_files = 20;
        metrics.file_size_distribution.medium_files = 60;
        metrics.file_size_distribution.large_files = 15;
        metrics.file_size_distribution.very_large_files = 5;

        let report = HealthReport {
            table_path: "/path/to/table".to_string(),
            table_type: "delta".to_string(),
            analysis_timestamp: "2024-01-01T00:00:00Z".to_string(),
            metrics,
            health_score: 0.85,
            timed_metrics: TimedLikeMetrics {
                duration_collection: LinkedList::new(),
            },
        };

        let display = format!("{}", report);

        assert!(display.contains("Table Health Report"));
        assert!(display.contains("85.0%"));
        assert!(display.contains("/path/to/table"));
        assert!(display.contains("delta"));
        assert!(display.contains("Total Data Files"));
        assert!(display.contains("100"));
    }

    // FileInfo tests
    #[test]
    fn test_file_info_creation() {
        let file_info = FileInfo {
            path: "data/file.parquet".to_string(),
            size_bytes: 1024 * 1024,
            last_modified: Some("2024-01-01T00:00:00Z".to_string()),
            is_referenced: true,
        };

        assert_eq!(file_info.path, "data/file.parquet");
        assert_eq!(file_info.size_bytes, 1024 * 1024);
        assert_eq!(
            file_info.last_modified,
            Some("2024-01-01T00:00:00Z".to_string())
        );
        assert!(file_info.is_referenced);
    }

    #[test]
    fn test_file_info_serialization() {
        let file_info = FileInfo {
            path: "data/file.parquet".to_string(),
            size_bytes: 1024,
            last_modified: None,
            is_referenced: false,
        };

        let json = serde_json::to_string(&file_info).expect("Should serialize");

        assert!(json.contains("data/file.parquet"));
        assert!(json.contains("1024"));
        assert!(json.contains("false"));
    }

    // PartitionInfo tests
    #[test]
    fn test_partition_info_creation() {
        let mut partition_values = HashMap::new();
        partition_values.insert("year".to_string(), "2024".to_string());
        partition_values.insert("month".to_string(), "01".to_string());

        let partition_info = PartitionInfo {
            partition_values,
            file_count: 10,
            total_size_bytes: 10240,
            avg_file_size_bytes: 1024.0,
            files: Vec::new(),
        };

        assert_eq!(partition_info.file_count, 10);
        assert_eq!(partition_info.total_size_bytes, 10240);
        assert_eq!(partition_info.avg_file_size_bytes, 1024.0);
        assert_eq!(partition_info.partition_values.len(), 2);
    }

    // ClusteringInfo tests
    #[test]
    fn test_clustering_info_creation() {
        let clustering_info = ClusteringInfo {
            clustering_columns: vec!["col1".to_string(), "col2".to_string()],
            cluster_count: 10,
            avg_files_per_cluster: 5.5,
            avg_cluster_size_bytes: 1024.0 * 1024.0,
        };

        assert_eq!(clustering_info.clustering_columns.len(), 2);
        assert_eq!(clustering_info.cluster_count, 10);
        assert_eq!(clustering_info.avg_files_per_cluster, 5.5);
    }

    // DeletionVectorMetrics tests
    #[test]
    fn test_deletion_vector_metrics_creation() {
        let dv_metrics = DeletionVectorMetrics {
            deletion_vector_count: 5,
            total_deletion_vector_size_bytes: 5120,
            avg_deletion_vector_size_bytes: 1024.0,
            deletion_vector_age_days: 15.5,
            deleted_rows_count: 1000,
            deletion_vector_impact_score: 0.6,
        };

        assert_eq!(dv_metrics.deletion_vector_count, 5);
        assert_eq!(dv_metrics.total_deletion_vector_size_bytes, 5120);
        assert_eq!(dv_metrics.deleted_rows_count, 1000);
        assert_eq!(dv_metrics.deletion_vector_impact_score, 0.6);
    }

    // SchemaEvolutionMetrics tests
    #[test]
    fn test_schema_evolution_metrics_creation() {
        let schema_metrics = SchemaEvolutionMetrics {
            total_schema_changes: 10,
            breaking_changes: 2,
            non_breaking_changes: 8,
            schema_stability_score: 0.8,
            days_since_last_change: 5.0,
            schema_change_frequency: 0.5,
            current_schema_version: 11,
        };

        assert_eq!(schema_metrics.total_schema_changes, 10);
        assert_eq!(schema_metrics.breaking_changes, 2);
        assert_eq!(schema_metrics.non_breaking_changes, 8);
        assert_eq!(schema_metrics.schema_stability_score, 0.8);
    }

    // TimeTravelMetrics tests
    #[test]
    fn test_time_travel_metrics_creation() {
        let tt_metrics = TimeTravelMetrics {
            total_snapshots: 50,
            oldest_snapshot_age_days: 30.0,
            newest_snapshot_age_days: 1.0,
            total_historical_size_bytes: 1024 * 1024 * 1024,
            avg_snapshot_size_bytes: 20.0 * 1024.0 * 1024.0,
            storage_cost_impact_score: 0.5,
            retention_efficiency_score: 0.7,
            recommended_retention_days: 30,
        };

        assert_eq!(tt_metrics.total_snapshots, 50);
        assert_eq!(tt_metrics.oldest_snapshot_age_days, 30.0);
        assert_eq!(tt_metrics.recommended_retention_days, 30);
    }

    // TableConstraintsMetrics tests
    #[test]
    fn test_table_constraints_metrics_creation() {
        let constraint_metrics = TableConstraintsMetrics {
            total_constraints: 10,
            check_constraints: 3,
            not_null_constraints: 5,
            unique_constraints: 1,
            foreign_key_constraints: 1,
            constraint_violation_risk: 0.2,
            data_quality_score: 0.9,
            constraint_coverage_score: 0.8,
        };

        assert_eq!(constraint_metrics.total_constraints, 10);
        assert_eq!(constraint_metrics.check_constraints, 3);
        assert_eq!(constraint_metrics.not_null_constraints, 5);
        assert_eq!(constraint_metrics.data_quality_score, 0.9);
    }

    // FileCompactionMetrics tests
    #[test]
    fn test_file_compaction_metrics_creation() {
        let compaction_metrics = FileCompactionMetrics {
            compaction_opportunity_score: 0.8,
            small_files_count: 100,
            small_files_size_bytes: 1024 * 1024,
            potential_compaction_files: 80,
            estimated_compaction_savings_bytes: 512 * 1024,
            recommended_target_file_size_bytes: 128 * 1024 * 1024,
            compaction_priority: "high".to_string(),
            z_order_opportunity: true,
            z_order_columns: vec!["col1".to_string(), "col2".to_string()],
        };

        assert_eq!(compaction_metrics.compaction_opportunity_score, 0.8);
        assert_eq!(compaction_metrics.small_files_count, 100);
        assert_eq!(compaction_metrics.compaction_priority, "high");
        assert!(compaction_metrics.z_order_opportunity);
        assert_eq!(compaction_metrics.z_order_columns.len(), 2);
    }

    // ========== Display implementation coverage tests ==========

    #[test]
    fn test_health_report_display_with_clustering() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 50;
        metrics.total_size_bytes = 500 * 1024 * 1024;
        metrics.clustering = Some(ClusteringInfo {
            clustering_columns: vec!["date".to_string(), "region".to_string()],
            cluster_count: 10,
            avg_files_per_cluster: 5.0,
            avg_cluster_size_bytes: 50.0 * 1024.0 * 1024.0,
        });

        let report = HealthReport {
            table_path: "/test/table".to_string(),
            table_type: "iceberg".to_string(),
            analysis_timestamp: "2024-01-01T00:00:00Z".to_string(),
            metrics,
            health_score: 0.9,
            timed_metrics: TimedLikeMetrics {
                duration_collection: LinkedList::new(),
            },
        };

        let display = format!("{}", report);
        assert!(display.contains("Clustering"));
        assert!(display.contains("Avg Cluster Size"));
        assert!(display.contains("Clusters"));
        assert!(display.contains("10"));
    }

    #[test]
    fn test_health_report_display_with_deletion_vectors() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 100;
        metrics.deletion_vector_metrics = Some(DeletionVectorMetrics {
            deletion_vector_count: 25,
            total_deletion_vector_size_bytes: 2 * 1024 * 1024,
            avg_deletion_vector_size_bytes: 80.0 * 1024.0,
            deletion_vector_age_days: 15.5,
            deleted_rows_count: 50000,
            deletion_vector_impact_score: 0.65,
        });

        let report = HealthReport {
            table_path: "/test/delta_table".to_string(),
            table_type: "delta".to_string(),
            analysis_timestamp: "2024-01-01T00:00:00Z".to_string(),
            metrics,
            health_score: 0.75,
            timed_metrics: TimedLikeMetrics {
                duration_collection: LinkedList::new(),
            },
        };

        let display = format!("{}", report);
        assert!(display.contains("Deletion Vectors"));
        assert!(display.contains("Vectors"));
        assert!(display.contains("25"));
        assert!(display.contains("Deleted Rows"));
        assert!(display.contains("50000"));
    }

    #[test]
    fn test_health_report_display_with_schema_evolution() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 100;
        metrics.schema_evolution = Some(SchemaEvolutionMetrics {
            total_schema_changes: 5,
            breaking_changes: 1,
            non_breaking_changes: 4,
            schema_stability_score: 0.8,
            days_since_last_change: 30.0,
            schema_change_frequency: 0.1,
            current_schema_version: 5,
        });

        let report = HealthReport {
            table_path: "/test/table".to_string(),
            table_type: "delta".to_string(),
            analysis_timestamp: "2024-01-01T00:00:00Z".to_string(),
            metrics,
            health_score: 0.85,
            timed_metrics: TimedLikeMetrics {
                duration_collection: LinkedList::new(),
            },
        };

        let display = format!("{}", report);
        assert!(display.contains("Schema Evolution"));
        assert!(display.contains("Total Changes"));
        assert!(display.contains("Breaking"));
        assert!(display.contains("Non-Breaking"));
        assert!(display.contains("Stability"));
    }

    #[test]
    fn test_health_report_display_with_time_travel() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 100;
        metrics.time_travel_metrics = Some(TimeTravelMetrics {
            total_snapshots: 50,
            oldest_snapshot_age_days: 90.0,
            newest_snapshot_age_days: 0.5,
            total_historical_size_bytes: 2 * 1024 * 1024 * 1024,
            avg_snapshot_size_bytes: 40.0 * 1024.0 * 1024.0,
            storage_cost_impact_score: 0.3,
            retention_efficiency_score: 0.85,
            recommended_retention_days: 30,
        });

        let report = HealthReport {
            table_path: "/test/table".to_string(),
            table_type: "delta".to_string(),
            analysis_timestamp: "2024-01-01T00:00:00Z".to_string(),
            metrics,
            health_score: 0.8,
            timed_metrics: TimedLikeMetrics {
                duration_collection: LinkedList::new(),
            },
        };

        let display = format!("{}", report);
        assert!(display.contains("Time Travel"));
        assert!(display.contains("Snapshots"));
        assert!(display.contains("50"));
        assert!(display.contains("Historical Size"));
    }

    #[test]
    fn test_health_report_display_with_constraints_and_compaction() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 100;
        metrics.table_constraints = Some(TableConstraintsMetrics {
            total_constraints: 10,
            check_constraints: 3,
            not_null_constraints: 5,
            unique_constraints: 1,
            foreign_key_constraints: 1,
            constraint_violation_risk: 0.1,
            data_quality_score: 0.95,
            constraint_coverage_score: 0.7,
        });
        metrics.file_compaction = Some(FileCompactionMetrics {
            compaction_opportunity_score: 0.6,
            small_files_count: 40,
            small_files_size_bytes: 100 * 1024 * 1024,
            potential_compaction_files: 35,
            estimated_compaction_savings_bytes: 50 * 1024 * 1024,
            recommended_target_file_size_bytes: 128 * 1024 * 1024,
            compaction_priority: "MEDIUM".to_string(),
            z_order_opportunity: false,
            z_order_columns: vec![],
        });

        let report = HealthReport {
            table_path: "/test/table".to_string(),
            table_type: "delta".to_string(),
            analysis_timestamp: "2024-01-01T00:00:00Z".to_string(),
            metrics,
            health_score: 0.7,
            timed_metrics: TimedLikeMetrics {
                duration_collection: LinkedList::new(),
            },
        };

        let display = format!("{}", report);
        assert!(display.contains("Table Constraints"));
        assert!(display.contains("File Compaction"));
        assert!(display.contains("NOT NULL"));
        assert!(display.contains("Small Files"));
        assert!(display.contains("40"));
    }

    #[test]
    fn test_health_report_display_with_unreferenced_files() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 100;
        metrics.unreferenced_files = vec![
            FileInfo {
                path: "orphan1.parquet".to_string(),
                size_bytes: 1024 * 1024,
                last_modified: None,
                is_referenced: false,
            },
            FileInfo {
                path: "orphan2.parquet".to_string(),
                size_bytes: 2 * 1024 * 1024,
                last_modified: None,
                is_referenced: false,
            },
        ];
        metrics.unreferenced_size_bytes = 3 * 1024 * 1024;

        let report = HealthReport {
            table_path: "/test/table".to_string(),
            table_type: "delta".to_string(),
            analysis_timestamp: "2024-01-01T00:00:00Z".to_string(),
            metrics,
            health_score: 0.6,
            timed_metrics: TimedLikeMetrics {
                duration_collection: LinkedList::new(),
            },
        };

        let display = format!("{}", report);
        assert!(display.contains("Unreferenced Files"));
        assert!(display.contains("Count"));
        assert!(display.contains("2"));
        assert!(display.contains("Wasted Space"));
    }

    #[test]
    fn test_health_report_display_with_all_optional_fields() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 200;
        metrics.total_size_bytes = 5 * 1024 * 1024 * 1024;
        metrics.avg_file_size_bytes = 25.0 * 1024.0 * 1024.0;
        metrics.partition_count = 20;

        // Add all optional fields
        metrics.clustering = Some(ClusteringInfo {
            clustering_columns: vec!["col1".to_string()],
            cluster_count: 5,
            avg_files_per_cluster: 40.0,
            avg_cluster_size_bytes: 1024.0 * 1024.0 * 1024.0,
        });
        metrics.deletion_vector_metrics = Some(DeletionVectorMetrics {
            deletion_vector_count: 10,
            total_deletion_vector_size_bytes: 500 * 1024,
            avg_deletion_vector_size_bytes: 50.0 * 1024.0,
            deletion_vector_age_days: 5.0,
            deleted_rows_count: 1000,
            deletion_vector_impact_score: 0.2,
        });
        metrics.schema_evolution = Some(SchemaEvolutionMetrics {
            total_schema_changes: 3,
            breaking_changes: 0,
            non_breaking_changes: 3,
            schema_stability_score: 0.95,
            days_since_last_change: 60.0,
            schema_change_frequency: 0.05,
            current_schema_version: 3,
        });
        metrics.time_travel_metrics = Some(TimeTravelMetrics {
            total_snapshots: 100,
            oldest_snapshot_age_days: 180.0,
            newest_snapshot_age_days: 0.1,
            total_historical_size_bytes: 10 * 1024 * 1024 * 1024,
            avg_snapshot_size_bytes: 100.0 * 1024.0 * 1024.0,
            storage_cost_impact_score: 0.5,
            retention_efficiency_score: 0.7,
            recommended_retention_days: 90,
        });
        metrics.table_constraints = Some(TableConstraintsMetrics {
            total_constraints: 15,
            check_constraints: 5,
            not_null_constraints: 8,
            unique_constraints: 1,
            foreign_key_constraints: 1,
            constraint_violation_risk: 0.05,
            data_quality_score: 0.98,
            constraint_coverage_score: 0.85,
        });
        metrics.file_compaction = Some(FileCompactionMetrics {
            compaction_opportunity_score: 0.3,
            small_files_count: 20,
            small_files_size_bytes: 50 * 1024 * 1024,
            potential_compaction_files: 15,
            estimated_compaction_savings_bytes: 20 * 1024 * 1024,
            recommended_target_file_size_bytes: 128 * 1024 * 1024,
            compaction_priority: "LOW".to_string(),
            z_order_opportunity: true,
            z_order_columns: vec!["date".to_string()],
        });

        let report = HealthReport {
            table_path: "/production/data/table".to_string(),
            table_type: "delta".to_string(),
            analysis_timestamp: "2024-06-15T12:00:00Z".to_string(),
            metrics,
            health_score: 0.92,
            timed_metrics: TimedLikeMetrics {
                duration_collection: LinkedList::new(),
            },
        };

        let display = format!("{}", report);

        // Verify all sections are present
        assert!(display.contains("Table Health Report"));
        assert!(display.contains("92.0%"));
        assert!(display.contains("Key Metrics"));
        assert!(display.contains("File Size Distribution"));
        assert!(display.contains("Data Skew Analysis"));
        assert!(display.contains("Metadata Health"));
        assert!(display.contains("Snapshot Health"));
        assert!(display.contains("Clustering"));
        assert!(display.contains("Deletion Vectors"));
        assert!(display.contains("Schema Evolution"));
        assert!(display.contains("Time Travel"));
        assert!(display.contains("Table Constraints"));
        assert!(display.contains("File Compaction"));
    }

    #[test]
    fn test_health_report_display_size_formatting_gb() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 1000;
        metrics.total_size_bytes = 50 * 1024 * 1024 * 1024; // 50 GB

        let report = HealthReport {
            table_path: "/test/large_table".to_string(),
            table_type: "delta".to_string(),
            analysis_timestamp: "2024-01-01T00:00:00Z".to_string(),
            metrics,
            health_score: 0.8,
            timed_metrics: TimedLikeMetrics {
                duration_collection: LinkedList::new(),
            },
        };

        let display = format!("{}", report);
        assert!(display.contains("GB"));
    }

    #[test]
    fn test_health_report_display_metadata_file_names_truncation() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 100;
        metrics.metadata_health.first_file_name =
            Some("very_long_metadata_file_name_that_exceeds_thirty_characters.json".to_string());
        metrics.metadata_health.last_file_name =
            Some("another_very_long_file_name_for_testing_truncation.json".to_string());

        let report = HealthReport {
            table_path: "/test/table".to_string(),
            table_type: "delta".to_string(),
            analysis_timestamp: "2024-01-01T00:00:00Z".to_string(),
            metrics,
            health_score: 0.8,
            timed_metrics: TimedLikeMetrics {
                duration_collection: LinkedList::new(),
            },
        };

        let display = format!("{}", report);
        // Truncated names should contain "..."
        assert!(display.contains("..."));
    }

    #[test]
    fn test_health_report_display_zero_partitions() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 10;
        metrics.partition_count = 0;
        metrics.data_skew.avg_partition_size = 0;

        let report = HealthReport {
            table_path: "/test/unpartitioned".to_string(),
            table_type: "delta".to_string(),
            analysis_timestamp: "2024-01-01T00:00:00Z".to_string(),
            metrics,
            health_score: 0.7,
            timed_metrics: TimedLikeMetrics {
                duration_collection: LinkedList::new(),
            },
        };

        let display = format!("{}", report);
        assert!(display.contains("N/A"));
    }

    #[test]
    fn test_health_report_display_with_recommendations() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 100;
        metrics.recommendations = vec![
            "Consider running OPTIMIZE".to_string(),
            "Too many small files detected".to_string(),
        ];

        let report = HealthReport {
            table_path: "/test/table".to_string(),
            table_type: "delta".to_string(),
            analysis_timestamp: "2024-01-01T00:00:00Z".to_string(),
            metrics,
            health_score: 0.5,
            timed_metrics: TimedLikeMetrics {
                duration_collection: LinkedList::new(),
            },
        };

        let display = format!("{}", report);
        assert!(display.contains("Recommendations"));
        assert!(display.contains("Consider running OPTIMIZE"));
        assert!(display.contains("Too many small files detected"));
    }

    #[test]
    fn test_health_report_display_snapshot_ages() {
        let mut metrics = HealthMetrics::new();
        metrics.total_files = 50;
        metrics.snapshot_health.oldest_snapshot_age_days = 45.5;
        metrics.snapshot_health.newest_snapshot_age_days = 0.5;
        metrics.snapshot_health.avg_snapshot_age_days = 20.0;

        let report = HealthReport {
            table_path: "/test/table".to_string(),
            table_type: "delta".to_string(),
            analysis_timestamp: "2024-01-01T00:00:00Z".to_string(),
            metrics,
            health_score: 0.8,
            timed_metrics: TimedLikeMetrics {
                duration_collection: LinkedList::new(),
            },
        };

        let display = format!("{}", report);
        assert!(display.contains("Oldest Snapshot"));
        assert!(display.contains("45.5 days"));
        assert!(display.contains("Newest Snapshot"));
        assert!(display.contains("0.5 days"));
    }

    #[cfg(feature = "hudi")]
    #[test]
    fn test_health_report_display_with_hudi_metrics() {
        use crate::reader::hudi::metrics::{
            FileStatistics, HudiMetrics, PartitionMetrics, TableMetadata, TimelineMetrics,
        };

        let mut metrics = HealthMetrics::new();
        metrics.total_files = 100;
        metrics.hudi_table_specific_metrics = Some(HudiMetrics {
            table_type: "COPY_ON_WRITE".to_string(),
            table_name: "test_hudi_table".to_string(),
            metadata: TableMetadata {
                name: "test_hudi_table".to_string(),
                base_path: "/data/hudi/test_table".to_string(),
                schema_string: "{}".to_string(),
                field_count: 10,
                partition_columns: vec!["date".to_string()],
                created_time: Some(1700000000000),
                format_provider: "parquet".to_string(),
                format_options: std::collections::HashMap::new(),
            },
            table_properties: {
                let mut props = std::collections::HashMap::new();
                props.insert("hoodie.table.name".to_string(), "test".to_string());
                props
            },
            file_stats: FileStatistics {
                num_files: 50,
                total_size_bytes: 1024 * 1024 * 100,
                avg_file_size_bytes: 1024.0 * 1024.0 * 2.0,
                min_file_size_bytes: 1024,
                max_file_size_bytes: 1024 * 1024 * 10,
                num_log_files: 10,
                total_log_size_bytes: 1024 * 1024 * 20,
            },
            partition_info: PartitionMetrics {
                num_partition_columns: 1,
                num_partitions: 30,
                partition_paths: vec!["date=2024-01-01".to_string()],
                largest_partition_size_bytes: 1024 * 1024 * 50,
                smallest_partition_size_bytes: 1024 * 1024,
                avg_partition_size_bytes: 1024.0 * 1024.0 * 25.0,
            },
            timeline_info: TimelineMetrics {
                total_commits: 100,
                total_delta_commits: 0,
                total_compactions: 5,
                total_cleans: 10,
                total_rollbacks: 2,
                total_savepoints: 1,
                latest_commit_timestamp: Some("20240101120000000".to_string()),
                earliest_commit_timestamp: Some("20231201000000000".to_string()),
                pending_compactions: 0,
            },
        });

        let report = HealthReport {
            table_path: "/data/hudi/test_table".to_string(),
            table_type: "hudi".to_string(),
            analysis_timestamp: "2024-01-01T00:00:00Z".to_string(),
            metrics,
            health_score: 0.85,
            timed_metrics: TimedLikeMetrics {
                duration_collection: LinkedList::new(),
            },
        };

        let display = format!("{}", report);

        // Verify Hudi-specific metrics are displayed
        assert!(display.contains("Hudi Specific Metrics"));
        assert!(display.contains("COPY_ON_WRITE"));
        assert!(display.contains("test_hudi_table"));
        assert!(display.contains("File Statistics"));
        assert!(display.contains("Timeline Info"));
        assert!(display.contains("Total Commits"));
    }

    #[cfg(feature = "lance")]
    #[test]
    fn test_generate_recommendations_lance_no_indices_large_table() {
        use crate::reader::lance::metrics::{
            FileStatistics, FragmentMetrics, IndexMetrics, LanceMetrics, TableMetadata,
        };

        let mut metrics = HealthMetrics::new();
        metrics.lance_table_specific_metrics = Some(LanceMetrics {
            version: 1,
            metadata: TableMetadata {
                uuid: "test-uuid".to_string(),
                schema_string: String::new(),
                field_count: 5,
                created_time: None,
                last_modified_time: None,
                num_rows: Some(50_000), // > 10,000 rows
                num_deleted_rows: None,
            },
            table_properties: std::collections::HashMap::new(),
            file_stats: FileStatistics {
                num_data_files: 10,
                num_deletion_files: 0,
                total_data_size_bytes: 1024 * 1024 * 100,
                total_deletion_size_bytes: 0,
                avg_data_file_size_bytes: 1024.0 * 1024.0 * 10.0,
                min_data_file_size_bytes: 1024 * 1024,
                max_data_file_size_bytes: 1024 * 1024 * 20,
            },
            fragment_info: FragmentMetrics {
                num_fragments: 10,
                num_fragments_with_deletions: 0,
                avg_rows_per_fragment: 5000.0,
                min_rows_per_fragment: 1000,
                max_rows_per_fragment: 10000,
                total_physical_rows: 50000,
            },
            index_info: IndexMetrics {
                num_indices: 0, // No indices
                indexed_columns: vec![],
                index_types: vec![],
                total_index_size_bytes: 0,
            },
            operation_metrics: None,
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("No indices found on Lance table")));
    }

    #[cfg(feature = "lance")]
    #[test]
    fn test_generate_recommendations_lance_many_fragments_no_indices() {
        use crate::reader::lance::metrics::{
            FileStatistics, FragmentMetrics, IndexMetrics, LanceMetrics, TableMetadata,
        };

        let mut metrics = HealthMetrics::new();
        metrics.lance_table_specific_metrics = Some(LanceMetrics {
            version: 1,
            metadata: TableMetadata {
                uuid: "test-uuid".to_string(),
                schema_string: String::new(),
                field_count: 5,
                created_time: None,
                last_modified_time: None,
                num_rows: Some(5_000), // Small table
                num_deleted_rows: None,
            },
            table_properties: std::collections::HashMap::new(),
            file_stats: FileStatistics {
                num_data_files: 150,
                num_deletion_files: 0,
                total_data_size_bytes: 1024 * 1024 * 100,
                total_deletion_size_bytes: 0,
                avg_data_file_size_bytes: 1024.0 * 1024.0,
                min_data_file_size_bytes: 1024,
                max_data_file_size_bytes: 1024 * 1024 * 5,
            },
            fragment_info: FragmentMetrics {
                num_fragments: 150, // > 100 fragments
                num_fragments_with_deletions: 0,
                avg_rows_per_fragment: 33.0,
                min_rows_per_fragment: 10,
                max_rows_per_fragment: 100,
                total_physical_rows: 5000,
            },
            index_info: IndexMetrics {
                num_indices: 0, // No indices
                indexed_columns: vec![],
                index_types: vec![],
                total_index_size_bytes: 0,
            },
            operation_metrics: None,
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("Large number of fragments")));
    }

    #[cfg(feature = "lance")]
    #[test]
    fn test_generate_recommendations_lance_high_deletion_ratio_with_indices() {
        use crate::reader::lance::metrics::{
            FileStatistics, FragmentMetrics, IndexMetrics, LanceMetrics, TableMetadata,
        };

        let mut metrics = HealthMetrics::new();
        metrics.lance_table_specific_metrics = Some(LanceMetrics {
            version: 1,
            metadata: TableMetadata {
                uuid: "test-uuid".to_string(),
                schema_string: String::new(),
                field_count: 5,
                created_time: None,
                last_modified_time: None,
                num_rows: Some(8_000),
                num_deleted_rows: Some(3_000), // 3000 / (8000 + 3000) = 27% > 20%
            },
            table_properties: std::collections::HashMap::new(),
            file_stats: FileStatistics {
                num_data_files: 10,
                num_deletion_files: 5,
                total_data_size_bytes: 1024 * 1024 * 100,
                total_deletion_size_bytes: 1024 * 100,
                avg_data_file_size_bytes: 1024.0 * 1024.0 * 10.0,
                min_data_file_size_bytes: 1024 * 1024,
                max_data_file_size_bytes: 1024 * 1024 * 20,
            },
            fragment_info: FragmentMetrics {
                num_fragments: 10,
                num_fragments_with_deletions: 5,
                avg_rows_per_fragment: 800.0,
                min_rows_per_fragment: 500,
                max_rows_per_fragment: 1500,
                total_physical_rows: 11000,
            },
            index_info: IndexMetrics {
                num_indices: 2, // Has indices
                indexed_columns: vec!["id".to_string(), "embedding".to_string()],
                index_types: vec!["IVF_PQ".to_string()],
                total_index_size_bytes: 1024 * 1024 * 10,
            },
            operation_metrics: None,
        });

        metrics.generate_recommendations();

        assert!(metrics
            .recommendations
            .iter()
            .any(|r| r.contains("High deletion ratio") && r.contains("rebuilding indices")));
    }

    #[cfg(feature = "lance")]
    #[test]
    fn test_health_report_display_with_lance_metrics() {
        use crate::reader::lance::metrics::{
            FileStatistics, FragmentMetrics, IndexMetrics, LanceMetrics, TableMetadata,
        };

        let mut metrics = HealthMetrics::new();
        metrics.lance_table_specific_metrics = Some(LanceMetrics {
            version: 5,
            metadata: TableMetadata {
                uuid: "test-lance-uuid".to_string(),
                schema_string: String::new(),
                field_count: 10,
                created_time: None,
                last_modified_time: None,
                num_rows: Some(100_000),
                num_deleted_rows: Some(500),
            },
            table_properties: std::collections::HashMap::new(),
            file_stats: FileStatistics {
                num_data_files: 50,
                num_deletion_files: 5,
                total_data_size_bytes: 1024 * 1024 * 500,
                total_deletion_size_bytes: 1024 * 100,
                avg_data_file_size_bytes: 1024.0 * 1024.0 * 10.0,
                min_data_file_size_bytes: 1024 * 1024,
                max_data_file_size_bytes: 1024 * 1024 * 50,
            },
            fragment_info: FragmentMetrics {
                num_fragments: 50,
                num_fragments_with_deletions: 5,
                avg_rows_per_fragment: 2000.0,
                min_rows_per_fragment: 500,
                max_rows_per_fragment: 5000,
                total_physical_rows: 100500,
            },
            index_info: IndexMetrics {
                num_indices: 2,
                indexed_columns: vec!["id".to_string(), "embedding".to_string()],
                index_types: vec!["IVF_PQ".to_string()],
                total_index_size_bytes: 1024 * 1024 * 50,
            },
            operation_metrics: None,
        });

        let report = HealthReport {
            table_path: "/data/lance/test_table.lance".to_string(),
            table_type: "lance".to_string(),
            analysis_timestamp: "2024-01-01T00:00:00Z".to_string(),
            metrics,
            health_score: 0.90,
            timed_metrics: TimedLikeMetrics {
                duration_collection: LinkedList::new(),
            },
        };

        let display = format!("{}", report);

        // Verify Lance-specific metrics are displayed
        assert!(display.contains("Lance Specific Metrics"));
        assert!(display.contains("test-lance-uuid"));
        assert!(display.contains("File Statistics"));
        assert!(display.contains("Fragment Info"));
        assert!(display.contains("Index Info"));
    }
}