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
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
"""
Data2Model - Automated Machine Learning Pipeline
Fully updated with all fixes:
1. Imputation instead of deletion for null values
2. Per-column null strategy support
3. Optional target column for unsupervised
4. Flexible train-test and train-test-validation splits
5. Dynamic encoding (only when categorical columns exist)
6. Per-column scaling
7. Per-column encoding
8. Proper data type detection (numeric vs categorical)
9. Dashboard with visualizations
10. Target column excluded from preprocessing
11. Download preprocessing components
"""

import numpy as np
import pandas as pd
import pickle
import os
import json
import base64
from io import BytesIO
from datetime import datetime
import matplotlib
matplotlib.use('Agg')  # Non-interactive backend
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import (
    StandardScaler, MinMaxScaler, RobustScaler, Normalizer,
    LabelEncoder, OneHotEncoder, OrdinalEncoder, LabelBinarizer
)
from sklearn.impute import SimpleImputer
from sklearn.metrics import (
    accuracy_score, precision_score, recall_score, f1_score,
    mean_squared_error, r2_score, mean_absolute_error,
    classification_report, confusion_matrix
)
import warnings
warnings.filterwarnings('ignore')

import sys, io
if sys.stdout.encoding != 'utf-8':
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
if sys.stderr.encoding != 'utf-8':
    sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')

# Supervised - Classification
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB

# Supervised - Regression
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, AdaBoostRegressor
from sklearn.svm import SVR
from sklearn.neighbors import KNeighborsRegressor

# Unsupervised
from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering
from sklearn.decomposition import PCA

# Advanced Models
try:
    import xgboost as xgb
    XGBOOST_AVAILABLE = True
except ImportError:
    XGBOOST_AVAILABLE = False

try:
    import lightgbm as lgb
    LIGHTGBM_AVAILABLE = True
except ImportError:
    LIGHTGBM_AVAILABLE = False


# ─────────────────────────────────────────────────────────────────────────────
# FIX 8: Strict data-type detector
# ─────────────────────────────────────────────────────────────────────────────
def detect_column_types(data, categorical_overrides=None):
    """
    Detect numeric vs categorical columns relying purely on dataframe dtypes,
    not heuristics like low cardinality or unique value count, unless explicitly overridden.
    """
    if categorical_overrides is None:
        categorical_overrides = []

    numeric_cols = []
    categorical_cols = []

    for col in data.columns:
        if col in categorical_overrides:
            categorical_cols.append(col)
            continue

        dtype_str = str(data[col].dtype).lower()

        # Check for numeric types (int, float, double, etc.)
        if 'int' in dtype_str or 'float' in dtype_str or 'double' in dtype_str or 'number' in dtype_str:
            numeric_cols.append(col)
        # Check for object, category, boolean, string
        elif 'object' in dtype_str or 'category' in dtype_str or 'bool' in dtype_str or 'str' in dtype_str:
            categorical_cols.append(col)
        else:
            # default fallback
            categorical_cols.append(col)

    return numeric_cols, categorical_cols




class AutoMLPipeline:
    """
    Automated Machine Learning Pipeline
    All 8 system limitations addressed.
    """

    def __init__(self):
        self.model = None
        self.scalers = {}           # per-column scalers
        self.encoders = {}          # per-column encoders
        self.imputers = {}          # per-column imputers
        self.feature_names = None
        self.target_name = None
        self.problem_type = None
        self.model_name = None
        self.preprocessing_steps = []
        self.results = {}
        self.numeric_cols = []
        self.categorical_cols = []

    # ─────────────────────────────────────────────────────────────────────────
    # Data Loading
    # ─────────────────────────────────────────────────────────────────────────
    def load_data(self, file_path, file_type='csv'):
        try:
            if file_type.lower() == 'csv':
                data = pd.read_csv(file_path)
            elif file_type.lower() in ['xlsx', 'excel', 'xls']:
                data = pd.read_excel(file_path)
            elif file_type.lower() == 'json':
                data = pd.read_json(file_path)
            else:
                raise ValueError(f"Unsupported file type: {file_type}")

            # Strip leading/trailing whitespaces from string columns
            for col in data.columns:
                if str(data[col].dtype) in ('object', 'string'):
                    data[col] = data[col].apply(lambda x: str(x).strip() if pd.notnull(x) else x)

            # Standardize and replace common string null placeholders with actual np.nan
            placeholders = ['null', 'NULL', 'Null', 'n/a', 'N/A', 'na', 'NA', 'nan', 'NaN', 'NAN', '-', '?', '']
            data = data.replace(placeholders, np.nan)

            print(f"βœ“ Dataset loaded: {data.shape[0]} rows Γ— {data.shape[1]} columns")
            return data
        except Exception as e:
            raise Exception(f"Error loading data: {str(e)}")

    # ─────────────────────────────────────────────────────────────────────────
    # Data Analysis
    # ─────────────────────────────────────────────────────────────────────────
    def analyze_data(self, data, categorical_overrides=None, target_column=None):
        """Analyze dataset and return summary including smart type detection."""
        # Ensure numeric-looking columns accidentally read as strings are safely converted before detection
        data = data.copy()
        for col in data.columns:
            if col == target_column:
                continue
            if str(data[col].dtype) in ('object', 'string'):
                # Try to convert to numeric
                converted = pd.to_numeric(data[col], errors='coerce')
                non_null_original = data[col].dropna().shape[0]
                non_null_converted = converted.dropna().shape[0]
                if non_null_original > 0 and non_null_converted >= 0.9 * non_null_original:
                    data[col] = converted

        numeric_cols, categorical_cols = detect_column_types(data, categorical_overrides)

        # FIX 3: Exclude target column from preprocessing lists
        if target_column and target_column in numeric_cols:
            numeric_cols.remove(target_column)
        if target_column and target_column in categorical_cols:
            categorical_cols.remove(target_column)

        # Column-level stats
        col_stats = {}
        for col in data.columns:
            col_stats[col] = {
                'dtype': str(data[col].dtype),
                'missing': int(data[col].isnull().sum()),
                'unique': int(data[col].nunique()),
                'detected_type': 'categorical' if col in categorical_cols else 'numeric'
            }

        # Visualization data
        viz_data = self._generate_visualization_data(data, numeric_cols, categorical_cols)

        return {
            'shape': data.shape,
            'columns': list(data.columns),
            'dtypes': {c: str(t) for c, t in data.dtypes.items()},
            'missing_values': data.isnull().sum().to_dict(),
            'numeric_columns': numeric_cols,
            'categorical_columns': categorical_cols,
            'statistics': data.describe().to_dict(),
            'duplicates': int(data.duplicated().sum()),
            'col_stats': col_stats,
            'viz_data': viz_data
        }

    def _generate_visualization_data(self, data, numeric_cols, categorical_cols):
        """Generate data for charts"""
        viz = {}

        # Missing values chart
        missing = data.isnull().sum()
        missing = missing[missing > 0].sort_values(ascending=False)
        viz['missing_labels'] = missing.index.tolist()
        viz['missing_values'] = missing.values.tolist()

        # Data types distribution
        type_counts = {'Numeric': len(numeric_cols), 'Categorical': len(categorical_cols)}
        viz['type_labels'] = list(type_counts.keys())
        viz['type_counts'] = list(type_counts.values())

        # Numeric distributions (first 6 only)
        viz['numeric_distributions'] = []
        for col in numeric_cols[:6]:
            try:
                hist, bins = np.histogram(data[col].dropna(), bins=20)
                viz['numeric_distributions'].append({
                    'column': col,
                    'bins': bins[:-1].tolist(),
                    'counts': hist.tolist()
                })
            except:
                pass

        # Categorical value counts (top 5 columns, top 10 values each)
        viz['categorical_distributions'] = []
        for col in categorical_cols[:5]:
            try:
                vc = data[col].value_counts().head(10)
                viz['categorical_distributions'].append({
                    'column': col,
                    'labels': vc.index.astype(str).tolist(),
                    'counts': vc.values.tolist()
                })
            except:
                pass

        # Correlation matrix (numeric only, max 10 cols)
        if len(numeric_cols) > 1:
            corr_cols = numeric_cols[:10]
            try:
                corr = data[corr_cols].corr()
                viz['correlation'] = {
                    'columns': corr_cols,
                    'matrix': corr.values.tolist()
                }
            except:
                viz['correlation'] = None
        else:
            viz['correlation'] = None

        return viz

    # ─────────────────────────────────────────────────────────────────────────
    # ENHANCEMENT 1: Dashboard Visualizations
    # ─────────────────────────────────────────────────────────────────────────
    def generate_visualizations(self, data, numeric_cols, categorical_cols, max_plots=6):
        """
        Generate dashboard visualizations and return as base64 encoded images.
        Returns dict with encoded plot images.
        """
        plots = {}
        
        # Set style
        sns.set_style("whitegrid")
        plt.rcParams['figure.facecolor'] = 'white'
        
        # 1. Missing Values Heatmap
        if data.isnull().sum().sum() > 0:
            fig, ax = plt.subplots(figsize=(10, 6))
            missing_data = data.isnull().sum()
            missing_data = missing_data[missing_data > 0].sort_values(ascending=False)
            
            if len(missing_data) > 0:
                ax.barh(range(len(missing_data)), missing_data.values, color='#e74c3c')
                ax.set_yticks(range(len(missing_data)))
                ax.set_yticklabels(missing_data.index)
                ax.set_xlabel('Missing Values Count', fontsize=12)
                ax.set_title('Missing Values by Column', fontsize=14, fontweight='bold')
                ax.grid(axis='x', alpha=0.3)
                
                for i, v in enumerate(missing_data.values):
                    ax.text(v + 0.5, i, str(int(v)), va='center', fontsize=10)
                
                plt.tight_layout()
                plots['missing_values'] = self._fig_to_base64(fig)
                plt.close(fig)
        
        # 2. Numeric Features - Histograms (first 6)
        if numeric_cols:
            num_to_plot = min(len(numeric_cols), max_plots)
            fig, axes = plt.subplots(2, 3, figsize=(15, 8))
            axes = axes.flatten()
            
            for idx, col in enumerate(numeric_cols[:num_to_plot]):
                data[col].dropna().hist(bins=30, ax=axes[idx], color='#3498db', edgecolor='black')
                axes[idx].set_title(f'{col}', fontsize=11, fontweight='bold')
                axes[idx].set_xlabel('Value', fontsize=9)
                axes[idx].set_ylabel('Frequency', fontsize=9)
                axes[idx].grid(axis='y', alpha=0.3)
            
            # Hide unused subplots
            for idx in range(num_to_plot, 6):
                axes[idx].axis('off')
            
            plt.suptitle('Numeric Features Distribution', fontsize=14, fontweight='bold', y=1.00)
            plt.tight_layout()
            plots['numeric_histograms'] = self._fig_to_base64(fig)
            plt.close(fig)
        
        # 3. Numeric Features - Box Plots (first 6)
        if numeric_cols:
            num_to_plot = min(len(numeric_cols), max_plots)
            fig, axes = plt.subplots(2, 3, figsize=(15, 8))
            axes = axes.flatten()
            
            for idx, col in enumerate(numeric_cols[:num_to_plot]):
                axes[idx].boxplot(data[col].dropna(), vert=True, patch_artist=True,
                                 boxprops=dict(facecolor='#2ecc71', alpha=0.7),
                                 medianprops=dict(color='red', linewidth=2))
                axes[idx].set_title(f'{col}', fontsize=11, fontweight='bold')
                axes[idx].set_ylabel('Value', fontsize=9)
                axes[idx].grid(axis='y', alpha=0.3)
            
            for idx in range(num_to_plot, 6):
                axes[idx].axis('off')
            
            plt.suptitle('Numeric Features - Outlier Detection', fontsize=14, fontweight='bold', y=1.00)
            plt.tight_layout()
            plots['numeric_boxplots'] = self._fig_to_base64(fig)
            plt.close(fig)
        
        # 4. Correlation Heatmap (if more than 2 numeric columns)
        if len(numeric_cols) >= 2:
            fig, ax = plt.subplots(figsize=(10, 8))
            numeric_data = data[numeric_cols].dropna()
            
            if len(numeric_data) > 0:
                corr = numeric_data.corr()
                mask = np.triu(np.ones_like(corr, dtype=bool))
                
                sns.heatmap(corr, mask=mask, annot=True, fmt='.2f', cmap='coolwarm',
                           center=0, square=True, linewidths=1, cbar_kws={"shrink": 0.8},
                           ax=ax, vmin=-1, vmax=1)
                ax.set_title('Correlation Matrix - Numeric Features', fontsize=14, fontweight='bold')
                plt.tight_layout()
                plots['correlation_heatmap'] = self._fig_to_base64(fig)
                plt.close(fig)
        
        # 5. Categorical Features - Bar Charts (first 6, top 10 values each)
        if categorical_cols:
            cat_to_plot = min(len(categorical_cols), max_plots)
            fig, axes = plt.subplots(2, 3, figsize=(15, 8))
            axes = axes.flatten()
            
            for idx, col in enumerate(categorical_cols[:cat_to_plot]):
                value_counts = data[col].value_counts().head(10)
                axes[idx].barh(range(len(value_counts)), value_counts.values, color='#9b59b6')
                axes[idx].set_yticks(range(len(value_counts)))
                axes[idx].set_yticklabels(value_counts.index, fontsize=9)
                axes[idx].set_xlabel('Count', fontsize=9)
                axes[idx].set_title(f'{col} (Top 10)', fontsize=11, fontweight='bold')
                axes[idx].grid(axis='x', alpha=0.3)
                
                for i, v in enumerate(value_counts.values):
                    axes[idx].text(v + 0.5, i, str(int(v)), va='center', fontsize=8)
            
            for idx in range(cat_to_plot, 6):
                axes[idx].axis('off')
            
            plt.suptitle('Categorical Features Distribution', fontsize=14, fontweight='bold', y=1.00)
            plt.tight_layout()
            plots['categorical_distributions'] = self._fig_to_base64(fig)
            plt.close(fig)
        
        # 6. Data Quality Overview
        fig, axes = plt.subplots(1, 2, figsize=(12, 5))
        
        # Column types pie chart
        type_counts = pd.Series({
            'Numeric': len(numeric_cols),
            'Categorical': len(categorical_cols)
        })
        axes[0].pie(type_counts.values, labels=type_counts.index, autopct='%1.1f%%',
                   colors=['#3498db', '#e67e22'], startangle=90)
        axes[0].set_title('Column Types', fontsize=12, fontweight='bold')
        
        # Missing vs Complete data
        total_cells = data.shape[0] * data.shape[1]
        missing_cells = data.isnull().sum().sum()
        complete_cells = total_cells - missing_cells
        
        completeness = pd.Series({
            'Complete': complete_cells,
            'Missing': missing_cells
        })
        axes[1].pie(completeness.values, labels=completeness.index, autopct='%1.1f%%',
                   colors=['#2ecc71', '#e74c3c'], startangle=90)
        axes[1].set_title('Data Completeness', fontsize=12, fontweight='bold')
        
        plt.suptitle('Dataset Quality Overview', fontsize=14, fontweight='bold', y=1.02)
        plt.tight_layout()
        plots['data_quality'] = self._fig_to_base64(fig)
        plt.close(fig)
        
        return plots
    
    def _fig_to_base64(self, fig):
        """Convert matplotlib figure to base64 encoded string for HTML embedding."""
        buffer = BytesIO()
        fig.savefig(buffer, format='png', dpi=100, bbox_inches='tight')
        buffer.seek(0)
        image_base64 = base64.b64encode(buffer.read()).decode('utf-8')
        buffer.close()
        return f"data:image/png;base64,{image_base64}"

    # ─────────────────────────────────────────────────────────────────────────
    # FIX 1 & 2: Null value imputation per column (no auto-deletion)
    # ─────────────────────────────────────────────────────────────────────────
    # ─────────────────────────────────────────────────────────────────────────
    # FIX 1 & 2: Null value imputation per column (no auto-deletion)
    # ─────────────────────────────────────────────────────────────────────────
    def handle_missing_values(self, data, null_strategies=None, target_column=None):
        """
        Handle missing values using imputation.
        null_strategies: dict  {col_name: 'mean'|'median'|'mode'|'drop'|'zero'|'custom_[val]'}
                         or None (auto: median for numeric, mode for categorical)
        """
        if null_strategies is None:
            null_strategies = {}

        # If it's a supervised problem and the target has missing values, drop those rows immediately to avoid training issues
        if target_column and target_column in data.columns:
            if data[target_column].isnull().any():
                before = len(data)
                data = data.dropna(subset=[target_column])
                print(f"  Dropped {before - len(data)} rows with missing target '{target_column}'")
                self.preprocessing_steps.append(f"Null handling '{target_column}' (Target): drop rows")

        # Set up a list to track zero-filled or custom-filled constant columns for predict
        if not hasattr(self, 'custom_impute_values'):
            self.custom_impute_values = {}

        # Impute all columns (excluding target if present) so that if they have missing values in predict, we can impute them
        cols_to_impute = [col for col in data.columns if col != target_column]

        for col in cols_to_impute:
            strategy = null_strategies.get(col, 'auto')

            # If strategy is auto:
            if strategy == 'auto':
                # Determine fallback based on datatype
                if data[col].dtype in ['object', 'category', 'bool']:
                    strategy = 'most_frequent'
                else:
                    strategy = 'median'

            if strategy == 'drop':
                if data[col].isnull().any():
                    before = len(data)
                    data = data.dropna(subset=[col])
                    print(f"  Dropped {before - len(data)} rows with missing '{col}'")
                    self.preprocessing_steps.append(f"Null handling '{col}': drop rows")
                # Store drop strategy in imputers so predict can handle it
                self.imputers[col] = 'drop'
                continue

            if strategy == 'mode':
                strategy = 'most_frequent'

            # Custom constant value replacement:
            if strategy == 'zero':
                val = 0 if data[col].dtype not in ['object', 'category', 'bool'] else '0'
                self.custom_impute_values[col] = val
                data[col] = data[col].fillna(val)
                self.preprocessing_steps.append(f"Null handling '{col}': fill with custom constant (0)")
                # Fit a constant imputer to be Scikit-learn native
                imputer = SimpleImputer(strategy='constant', fill_value=val)
                imputer.fit(data[[col]])
                self.imputers[col] = imputer
                continue
            elif strategy.startswith('custom_'):
                val = strategy[7:]  # extract the value after "custom_"
                # Try to convert to float/int if numeric
                if data[col].dtype not in ['object', 'category', 'bool']:
                    try:
                        if '.' in val:
                            val = float(val)
                        else:
                            val = int(val)
                    except ValueError:
                        pass
                self.custom_impute_values[col] = val
                data[col] = data[col].fillna(val)
                self.preprocessing_steps.append(f"Null handling '{col}': fill with custom constant ({val})")
                imputer = SimpleImputer(strategy='constant', fill_value=val)
                imputer.fit(data[[col]])
                self.imputers[col] = imputer
                continue

            if strategy == 'mean':
                if data[col].dtype in ['object', 'category', 'bool']:
                    strategy = 'most_frequent'  # fallback for categorical

            # Fit standard SimpleImputer (mean, median, most_frequent)
            try:
                imputer = SimpleImputer(strategy=strategy)
                # Fit on data
                data[[col]] = imputer.fit_transform(data[[col]])
                self.imputers[col] = imputer
                self.preprocessing_steps.append(f"Null handling '{col}': {strategy}")
            except Exception as e:
                print(f"  βœ— Could not impute '{col}' using {strategy}: {e}")

        return data

    # ─────────────────────────────────────────────────────────────────────────
    # FIX 6 & 7: Per-column scaling and encoding
    # ─────────────────────────────────────────────────────────────────────────
    def _get_scaler(self, method):
        if method == 'standard':
            return StandardScaler()
        elif method == 'minmax':
            return MinMaxScaler()
        elif method == 'robust':
            return RobustScaler()
        elif method == 'normalizer':
            return Normalizer()
        return None

    def scale_features(self, X_train, X_test, X_val=None, scaling_config=None, numeric_cols=None):
        """
        Per-column scaling.
        scaling_config: dict {col: method}  e.g. {'age': 'standard', 'income': 'minmax'}
                        or single string 'standard' applied to all numeric cols.
        """
        if numeric_cols is None:
            numeric_cols = list(X_train.select_dtypes(include=['int64', 'float64']).columns)

        if not numeric_cols:
            print("  No numeric columns to scale")
            return (X_train, X_test, X_val) if X_val is not None else (X_train, X_test)

        # Normalise config to dict
        if scaling_config is None or scaling_config == 'none' or scaling_config == 'auto':
            # FIX 2: auto defaults to standard
            default_method = 'standard' if scaling_config == 'auto' else 'none'
            if default_method == 'none':
                if X_val is not None:
                    return X_train, X_test, X_val
                return X_train, X_test
            scaling_config = {col: default_method for col in numeric_cols}

        if isinstance(scaling_config, str):
            scaling_config = {col: scaling_config for col in numeric_cols}

        for col in numeric_cols:
            method = scaling_config.get(col, 'standard')
            # FIX 2: handle auto per-column
            if method == 'auto':
                method = 'standard'
            if method == 'none':
                continue
            scaler = self._get_scaler(method)
            if scaler is None:
                continue
            X_train[col] = scaler.fit_transform(X_train[[col]])
            X_test[col] = scaler.transform(X_test[[col]])
            if X_val is not None:
                X_val[col] = scaler.transform(X_val[[col]])
            self.scalers[col] = scaler
            self.preprocessing_steps.append(f"Scale '{col}': {method}")

        print(f"βœ“ Scaling applied to {len(self.scalers)} columns")

        if X_val is not None:
            return X_train, X_test, X_val
        return X_train, X_test

    def encode_features(self, X_train, X_test, X_val=None, encoding_config=None, categorical_cols=None):
        """
        Per-column categorical encoding.
        encoding_config: dict {col: method}  e.g. {'color': 'onehot', 'grade': 'label'}
                         or single string applied to all categorical cols.
        """
        if categorical_cols is None:
            categorical_cols = list(X_train.select_dtypes(include=['object', 'category']).columns)

        if not categorical_cols:
            print("  No categorical columns to encode")
            if X_val is not None:
                return X_train, X_test, X_val
            return X_train, X_test

        # FIX 5: Only encode if categorical cols actually exist
        if isinstance(encoding_config, str):
            encoding_config = {col: encoding_config for col in categorical_cols}
        if encoding_config is None:
            encoding_config = {}

        onehot_cols = []

        for col in categorical_cols:
            if col not in X_train.columns:
                continue
            method = encoding_config.get(col, 'auto')

            # Auto: one-hot for ≀10 unique, label for higher
            if method == 'auto':
                method = 'onehot' if X_train[col].nunique() <= 10 else 'label'

            if method == 'onehot':
                onehot_cols.append(col)

            elif method == 'label':
                le = LabelEncoder()
                X_train[col] = le.fit_transform(X_train[col].astype(str))
                X_test[col] = le.transform(X_test[col].astype(str))
                if X_val is not None:
                    X_val[col] = le.transform(X_val[col].astype(str))
                self.encoders[col] = le
                self.preprocessing_steps.append(f"Encode '{col}': Label")

            elif method == 'ordinal':
                oe = OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=-1)
                X_train[col] = oe.fit_transform(X_train[[col]])
                X_test[col] = oe.transform(X_test[[col]])
                if X_val is not None:
                    X_val[col] = oe.transform(X_val[[col]])
                self.encoders[col] = oe
                self.preprocessing_steps.append(f"Encode '{col}': Ordinal")

            elif method == 'binary':
                lb = LabelBinarizer()
                encoded_train = lb.fit_transform(X_train[col].astype(str))
                if encoded_train.shape[1] == 1:
                    X_train[col] = encoded_train.ravel()
                    X_test[col] = lb.transform(X_test[col].astype(str)).ravel()
                    if X_val is not None:
                        X_val[col] = lb.transform(X_val[col].astype(str)).ravel()
                else:
                    new_cols = [f"{col}_{c}" for c in lb.classes_]
                    X_train[new_cols] = encoded_train
                    X_test[new_cols] = lb.transform(X_test[col].astype(str))
                    if X_val is not None:
                        X_val[new_cols] = lb.transform(X_val[col].astype(str))
                    X_train.drop(columns=[col], inplace=True)
                    X_test.drop(columns=[col], inplace=True)
                    if X_val is not None:
                        X_val.drop(columns=[col], inplace=True)
                self.encoders[col] = lb
                self.preprocessing_steps.append(f"Encode '{col}': Binary")

            elif method == 'target':
                le = LabelEncoder()
                X_train[col] = le.fit_transform(X_train[col].astype(str))
                X_test[col] = le.transform(X_test[col].astype(str))
                if X_val is not None:
                    X_val[col] = le.transform(X_val[col].astype(str))
                self.encoders[col] = le
                self.preprocessing_steps.append(f"Encode '{col}': Target (Label)")

        # Batch one-hot encoding
        self.onehot_cols = onehot_cols
        if onehot_cols:
            X_train = pd.get_dummies(X_train, columns=onehot_cols, drop_first=True)
            X_test = pd.get_dummies(X_test, columns=onehot_cols, drop_first=True)
            if X_val is not None:
                X_val = pd.get_dummies(X_val, columns=onehot_cols, drop_first=True)

            # Align columns
            X_test = X_test.reindex(columns=X_train.columns, fill_value=0)
            if X_val is not None:
                X_val = X_val.reindex(columns=X_train.columns, fill_value=0)

            for col in onehot_cols:
                self.preprocessing_steps.append(f"Encode '{col}': One-Hot")

        print(f"βœ“ Encoding applied to {len(categorical_cols)} categorical columns")

        if X_val is not None:
            return X_train, X_test, X_val
        return X_train, X_test

    # ─────────────────────────────────────────────────────────────────────────
    # Model Definitions
    # ─────────────────────────────────────────────────────────────────────────
    def _classification_models(self):
        models = {
            'Logistic Regression': LogisticRegression(max_iter=1000, random_state=42),
            'Random Forest': RandomForestClassifier(n_estimators=100, random_state=42),
            'Gradient Boosting': GradientBoostingClassifier(n_estimators=100, random_state=42),
            'Decision Tree': DecisionTreeClassifier(random_state=42),
            'KNN': KNeighborsClassifier(),
            'Naive Bayes': GaussianNB(),
            'SVM': SVC(random_state=42),
            'AdaBoost': AdaBoostClassifier(random_state=42),
        }
        if XGBOOST_AVAILABLE:
            models['XGBoost'] = xgb.XGBClassifier(n_estimators=100, random_state=42,
                                                    use_label_encoder=False, verbosity=0, eval_metric='logloss')
        if LIGHTGBM_AVAILABLE:
            models['LightGBM'] = lgb.LGBMClassifier(n_estimators=100, random_state=42, verbosity=-1)
        return models

    def _regression_models(self):
        models = {
            'Linear Regression': LinearRegression(),
            'Random Forest': RandomForestRegressor(n_estimators=100, random_state=42),
            'Gradient Boosting': GradientBoostingRegressor(n_estimators=100, random_state=42),
            'Decision Tree': DecisionTreeRegressor(random_state=42),
            'KNN': KNeighborsRegressor(),
            'SVR': SVR(),
            'AdaBoost': AdaBoostRegressor(random_state=42),
        }
        if XGBOOST_AVAILABLE:
            models['XGBoost'] = xgb.XGBRegressor(n_estimators=100, random_state=42, verbosity=0)
        if LIGHTGBM_AVAILABLE:
            models['LightGBM'] = lgb.LGBMRegressor(n_estimators=100, random_state=42, verbosity=-1)
        return models

    # ─────────────────────────────────────────────────────────────────────────
    # Train Models
    # ─────────────────────────────────────────────────────────────────────────
    def train_model(self, X_train, y_train, X_test, y_test, problem_type='auto'):
        if problem_type == 'auto':
            problem_type = 'classification' if (
                y_train.dtype == 'object' or y_train.nunique() < 20
            ) else 'regression'

        self.problem_type = problem_type
        models = (self._classification_models() if problem_type == 'classification'
                  else self._regression_models())

        print(f"\n{'='*55}")
        print(f"πŸ€– Training {problem_type.upper()} models...")
        print(f"{'='*55}\n")

        best_model = None
        best_score = -np.inf if problem_type == 'classification' else np.inf
        best_name = None
        rows = []

        for name, model in models.items():
            try:
                print(f"  Training {name}...", end=" ")
                model.fit(X_train, y_train)
                y_pred = model.predict(X_test)

                if problem_type == 'classification':
                    score = accuracy_score(y_test, y_pred)
                    rows.append({'Model': name,
                                 'Accuracy': round(score, 4),
                                 'Precision': round(precision_score(y_test, y_pred, average='weighted', zero_division=0), 4),
                                 'Recall': round(recall_score(y_test, y_pred, average='weighted', zero_division=0), 4),
                                 'F1': round(f1_score(y_test, y_pred, average='weighted', zero_division=0), 4)})
                    print(f"Accuracy: {score:.4f}")
                    if score > best_score:
                        best_score, best_model, best_name = score, model, name
                else:
                    rmse = np.sqrt(mean_squared_error(y_test, y_pred))
                    r2 = r2_score(y_test, y_pred)
                    rows.append({'Model': name,
                                 'RMSE': round(rmse, 4),
                                 'MAE': round(mean_absolute_error(y_test, y_pred), 4),
                                 'R2': round(r2, 4)})
                    print(f"RMSE: {rmse:.4f}  RΒ²: {r2:.4f}")
                    if rmse < best_score:
                        best_score, best_model, best_name = rmse, model, name
            except Exception as e:
                print(f"βœ— {e}")

        self.model = best_model
        self.model_name = best_name
        self.comparison_table = pd.DataFrame(rows)

        print(f"\nπŸ† Best: {best_name}")

        # Final evaluation metrics
        y_pred = best_model.predict(X_test)
        if problem_type == 'classification':
            self.results = {
                'model_name': best_name,
                'problem_type': problem_type,
                'accuracy': accuracy_score(y_test, y_pred),
                'precision': precision_score(y_test, y_pred, average='weighted', zero_division=0),
                'recall': recall_score(y_test, y_pred, average='weighted', zero_division=0),
                'f1_score': f1_score(y_test, y_pred, average='weighted', zero_division=0),
                'preprocessing_steps': self.preprocessing_steps,
            }
        else:
            mse = mean_squared_error(y_test, y_pred)
            self.results = {
                'model_name': best_name,
                'problem_type': problem_type,
                'mse': mse,
                'rmse': np.sqrt(mse),
                'mae': mean_absolute_error(y_test, y_pred),
                'r2_score': r2_score(y_test, y_pred),
                'preprocessing_steps': self.preprocessing_steps,
            }

    def train_unsupervised(self, X, problem_type='clustering'):
        """Train unsupervised model (no target needed)."""
        print(f"\n{'='*55}")
        print(f"πŸ€– Training UNSUPERVISED model: {problem_type}")
        print(f"{'='*55}\n")

        self.problem_type = problem_type

        if problem_type == 'clustering':
            model = KMeans(n_clusters=3, random_state=42)
            model.fit(X)
            labels = model.labels_
            self.model = model
            self.model_name = 'K-Means (k=3)'
            self.results = {
                'model_name': 'K-Means (k=3)',
                'problem_type': 'clustering',
                'inertia': float(model.inertia_),
                'n_clusters': 3,
                'preprocessing_steps': self.preprocessing_steps,
            }
            print(f"βœ“ KMeans trained. Inertia: {model.inertia_:.2f}")

        elif problem_type == 'dimensionality_reduction':
            model = PCA(n_components=2)
            model.fit(X)
            self.model = model
            self.model_name = 'PCA (2 components)'
            self.results = {
                'model_name': 'PCA (2 components)',
                'problem_type': 'dimensionality_reduction',
                'explained_variance': float(model.explained_variance_ratio_.sum()),
                'preprocessing_steps': self.preprocessing_steps,
            }
            print(f"βœ“ PCA trained. Explained variance: {model.explained_variance_ratio_.sum():.2%}")

        else:
            print(f"β„Ή Association rule learning – pass through")
            self.model = None
            self.model_name = 'Association Analysis'
            self.results = {
                'model_name': 'Association Analysis',
                'problem_type': 'association',
                'preprocessing_steps': self.preprocessing_steps,
            }

    # ─────────────────────────────────────────────────────────────────────────
    # Save / Load
    # ─────────────────────────────────────────────────────────────────────────
    def save_model(self, save_dir='saved_models', filename=None):
        os.makedirs(save_dir, exist_ok=True)
        if filename is None:
            ts = datetime.now().strftime('%Y%m%d_%H%M%S')
            filename = f"model_{self.problem_type}_{ts}.pkl"

        path = os.path.join(save_dir, filename)
        payload = {
            'model': self.model,
            'scalers': self.scalers,
            'encoders': self.encoders,
            'imputers': self.imputers,
            'feature_names': self.feature_names,
            'trained_features': getattr(self, 'trained_features', None),
            'onehot_cols': getattr(self, 'onehot_cols', None),
            'custom_impute_values': getattr(self, 'custom_impute_values', {}),
            'drop_columns': getattr(self, 'drop_columns', []),
            'model_name': self.model_name,
            'problem_type': self.problem_type,
            'preprocessing_steps': self.preprocessing_steps,
            'results': self.results,
        }
        with open(path, 'wb') as f:
            pickle.dump(payload, f)
        print(f"βœ“ Model saved: {path}")
        return path

    def load_model(self, path):
        with open(path, 'rb') as f:
            d = pickle.load(f)
        self.model = d['model']
        self.scalers = d.get('scalers', {})
        self.encoders = d.get('encoders', {})
        self.imputers = d.get('imputers', {})
        self.feature_names = d.get('feature_names')
        self.trained_features = d.get('trained_features', None)
        self.onehot_cols = d.get('onehot_cols', None)
        self.custom_impute_values = d.get('custom_impute_values', {})
        self.drop_columns = d.get('drop_columns', [])
        self.model_name = d.get('model_name')
        self.problem_type = d.get('problem_type')
        self.preprocessing_steps = d.get('preprocessing_steps', [])
        self.results = d.get('results', {})
        return self

    def predict(self, X):
        if self.model is None:
            raise Exception("No model trained yet.")

        # Copy to avoid side effects
        X = X.copy()

        # Strip whitespaces from string columns
        for col in X.columns:
            if str(X[col].dtype) in ('object', 'string'):
                X[col] = X[col].apply(lambda x: str(x).strip() if pd.notnull(x) else x)

        # Standardize and replace common string null placeholders with actual np.nan
        placeholders = ['null', 'NULL', 'Null', 'n/a', 'N/A', 'na', 'NA', 'nan', 'NaN', 'NAN', '-', '?', '']
        X = X.replace(placeholders, np.nan)

        # Drop columns that were excluded during training
        if hasattr(self, 'drop_columns') and self.drop_columns:
            cols_to_drop = [c for c in self.drop_columns if c in X.columns]
            if cols_to_drop:
                X = X.drop(columns=cols_to_drop)

        # Safely convert numeric-looking columns read as strings
        for col in X.columns:
            if str(X[col].dtype) in ('object', 'string'):
                converted = pd.to_numeric(X[col], errors='coerce')
                non_null_original = X[col].dropna().shape[0]
                non_null_converted = converted.dropna().shape[0]
                if non_null_original > 0 and non_null_converted >= 0.9 * non_null_original:
                    X[col] = converted

        # 1. Apply Imputers / Null strategies
        for col in X.columns:
            # Handle drop strategy in predict (dropping rows with missing values for that col)
            if col in self.imputers:
                imputer = self.imputers[col]
                if imputer == 'drop':
                    X = X.dropna(subset=[col])
                elif hasattr(imputer, 'transform'):
                    try:
                        X[[col]] = imputer.transform(X[[col]])
                    except Exception as e:
                        print(f"  Warning: Imputer transform failed for '{col}': {e}")
            
            # Fallback custom imputations registered
            if hasattr(self, 'custom_impute_values') and self.custom_impute_values and col in self.custom_impute_values:
                val = self.custom_impute_values[col]
                X[col] = X[col].fillna(val)

        # 2. Apply Encoders
        for col, encoder in self.encoders.items():
            if col in X.columns:
                try:
                    if isinstance(encoder, LabelEncoder):
                        # Handle unseen categories gracefully
                        classes = set(encoder.classes_)
                        X[col] = X[col].astype(str).map(lambda s: s if s in classes else encoder.classes_[0])
                        X[col] = encoder.transform(X[col])
                    elif isinstance(encoder, OrdinalEncoder):
                        X[[col]] = encoder.transform(X[[col]])
                    elif isinstance(encoder, LabelBinarizer):
                        encoded = encoder.transform(X[col].astype(str))
                        if encoded.shape[1] == 1:
                            X[col] = encoded.ravel()
                        else:
                            new_cols = [f"{col}_{c}" for c in encoder.classes_]
                            X[new_cols] = encoded
                            X.drop(columns=[col], inplace=True)
                except Exception as e:
                    print(f"  Warning: Encoding failed for '{col}': {e}")

        # 3. Apply One-Hot dummy encoding
        if hasattr(self, 'onehot_cols') and self.onehot_cols:
            existing_onehot_cols = [col for col in self.onehot_cols if col in X.columns]
            if existing_onehot_cols:
                X = pd.get_dummies(X, columns=existing_onehot_cols, drop_first=True)

        # 4. Apply Scalers
        for col, scaler in self.scalers.items():
            if col in X.columns:
                try:
                    X[[col]] = scaler.transform(X[[col]])
                except Exception as e:
                    print(f"  Warning: Scaler transform failed for '{col}': {e}")

        # 5. Column Alignment with Model Structure
        if hasattr(self, 'trained_features') and self.trained_features:
            # Reindex to match trained features exactly (fills missing dummy columns with 0, discards extra ones)
            X = X.reindex(columns=self.trained_features, fill_value=0)

        return self.model.predict(X)

    # ─────────────────────────────────────────────────────────────────────────
    # ENHANCEMENT 3: Save Preprocessing Components Separately
    # ─────────────────────────────────────────────────────────────────────────
    def save_encoders(self, save_dir='saved_models', filename=None):
        """Save encoders as a separate file."""
        os.makedirs(save_dir, exist_ok=True)
        if filename is None:
            ts = datetime.now().strftime('%Y%m%d_%H%M%S')
            filename = f"encoders_{self.problem_type}_{ts}.pkl"
        
        path = os.path.join(save_dir, filename)
        payload = {
            'encoders': self.encoders,
            'categorical_columns': [col for col in self.feature_names if col in self.encoders] if self.feature_names else [],
            'timestamp': datetime.now().isoformat(),
            'problem_type': self.problem_type,
        }
        with open(path, 'wb') as f:
            pickle.dump(payload, f)
        print(f"βœ“ Encoders saved: {path}")
        return path
    
    def save_scalers(self, save_dir='saved_models', filename=None):
        """Save scalers as a separate file."""
        os.makedirs(save_dir, exist_ok=True)
        if filename is None:
            ts = datetime.now().strftime('%Y%m%d_%H%M%S')
            filename = f"scalers_{self.problem_type}_{ts}.pkl"
        
        path = os.path.join(save_dir, filename)
        payload = {
            'scalers': self.scalers,
            'numeric_columns': [col for col in self.feature_names if col in self.scalers] if self.feature_names else [],
            'timestamp': datetime.now().isoformat(),
            'problem_type': self.problem_type,
        }
        with open(path, 'wb') as f:
            pickle.dump(payload, f)
        print(f"βœ“ Scalers saved: {path}")
        return path
    
    def save_preprocessing_bundle(self, save_dir='saved_models', filename=None):
        """Save all preprocessing components as a bundle with metadata."""
        os.makedirs(save_dir, exist_ok=True)
        if filename is None:
            ts = datetime.now().strftime('%Y%m%d_%H%M%S')
            filename = f"preprocessing_bundle_{self.problem_type}_{ts}.pkl"
        
        path = os.path.join(save_dir, filename)
        payload = {
            'scalers': self.scalers,
            'encoders': self.encoders,
            'imputers': self.imputers,
            'metadata': {
                'feature_names': self.feature_names,
                'trained_features': getattr(self, 'trained_features', None),
                'onehot_cols': getattr(self, 'onehot_cols', None),
                'custom_impute_values': getattr(self, 'custom_impute_values', {}),
                'drop_columns': getattr(self, 'drop_columns', []),
                'numeric_columns': [col for col in self.feature_names if col in self.scalers] if self.feature_names else [],
                'categorical_columns': [col for col in self.feature_names if col in self.encoders] if self.feature_names else [],
                'preprocessing_steps': self.preprocessing_steps,
                'problem_type': self.problem_type,
                'model_name': self.model_name,
                'timestamp': datetime.now().isoformat(),
            }
        }
        with open(path, 'wb') as f:
            pickle.dump(payload, f)
        print(f"βœ“ Preprocessing bundle saved: {path}")
        return path

    # ─────────────────────────────────────────────────────────────────────────
    # ENHANCEMENT: Generate Deployable Web Application
    # ─────────────────────────────────────────────────────────────────────────
    def generate_deployable_app(self, model_path, scaler_path=None, encoder_path=None, save_dir='saved_models'):
        """
        Generate a complete, self-contained Flask web application as a ZIP file.
        The ZIP contains app.py, templates/index.html, model artifacts, requirements.txt, and README.md.
        """
        import zipfile

        os.makedirs(save_dir, exist_ok=True)
        ts = datetime.now().strftime('%Y%m%d_%H%M%S')
        zip_filename = f"deployable_app_{ts}.zip"
        zip_path = os.path.join(save_dir, zip_filename)

        feature_names = self.feature_names or []
        numeric_cols = self.numeric_cols or []
        categorical_cols = self.categorical_cols or []
        categorical_values = getattr(self, 'categorical_values', {})
        target_name = self.target_name or 'target'
        model_name = self.model_name or 'Unknown'
        problem_type = self.problem_type or 'Unknown'

        # ── Generate app.py ──────────────────────────────────────────────
        app_py = self._gen_app_py(feature_names, numeric_cols, categorical_cols, target_name, model_name, problem_type)

        # ── Generate index.html ──────────────────────────────────────────
        index_html = self._gen_index_html(feature_names, numeric_cols, categorical_cols, categorical_values, target_name, model_name, problem_type)

        # ── Generate requirements.txt ────────────────────────────────────
        requirements_txt = "flask>=2.3.0\npandas>=1.5.0\nnumpy>=1.23.0\nscikit-learn>=1.2.0\n"

        # ── Generate README.md ───────────────────────────────────────────
        readme_md = f"""# {model_name} β€” Prediction Web App

This is an auto-generated, self-contained Flask web application for making predictions
using the **{model_name}** model trained by Data2Model.

## Quick Start

```bash
pip install -r requirements.txt
python app.py
```

Then open **http://localhost:5000** in your browser.

## Model Details

| Property       | Value                |
|----------------|----------------------|
| Algorithm      | {model_name}         |
| Problem Type   | {problem_type.title()} |
| Target Column  | {target_name}        |
| Features Used  | {len(feature_names)} |

## Project Structure

```
β”œβ”€β”€ app.py                 # Flask application
β”œβ”€β”€ templates/
β”‚   └── index.html         # Web interface
β”œβ”€β”€ model/
β”‚   β”œβ”€β”€ model.pkl          # Trained model
β”‚   β”œβ”€β”€ scaler.pkl         # Fitted scaler (if applicable)
β”‚   └── encoder.pkl        # Fitted encoder (if applicable)
β”œβ”€β”€ requirements.txt       # Python dependencies
└── README.md              # This file
```

---
*Generated by Data2Model β€” Automated Machine Learning Platform*
"""

        # ── Bundle into ZIP ──────────────────────────────────────────────
        with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
            zf.writestr('app.py', app_py)
            zf.writestr('templates/index.html', index_html)
            zf.writestr('requirements.txt', requirements_txt)
            zf.writestr('README.md', readme_md)

            # Add model pickle
            if model_path and os.path.exists(model_path):
                zf.write(model_path, 'model/model.pkl')
            # Add scaler pickle
            if scaler_path and os.path.exists(scaler_path):
                zf.write(scaler_path, 'model/scaler.pkl')
            # Add encoder pickle
            if encoder_path and os.path.exists(encoder_path):
                zf.write(encoder_path, 'model/encoder.pkl')

        print(f"βœ“ Deployable app saved: {zip_path}")
        return zip_path

    def _gen_app_py(self, feature_names, numeric_cols, categorical_cols, target_name, model_name, problem_type):
        """Generate the app.py source code string."""
        return '''"""
Auto-generated Prediction Web App β€” ''' + model_name + '''
Generated by Data2Model
"""
from flask import Flask, render_template, request, jsonify
import pandas as pd
import numpy as np
import pickle
import os

app = Flask(__name__)

# ── Load model & artifacts ─────────────────────────────────────────────────
MODEL_DIR = os.path.join(os.path.dirname(__file__), 'model')
MODEL_PATH = os.path.join(MODEL_DIR, 'model.pkl')
SCALER_PATH = os.path.join(MODEL_DIR, 'scaler.pkl')
ENCODER_PATH = os.path.join(MODEL_DIR, 'encoder.pkl')

with open(MODEL_PATH, 'rb') as f:
    bundle = pickle.load(f)

model            = bundle['model']
imputers         = bundle.get('imputers', {})
feature_names    = bundle.get('feature_names', [])
trained_features = bundle.get('trained_features', [])
onehot_cols      = bundle.get('onehot_cols', [])
custom_impute    = bundle.get('custom_impute_values', {})
drop_columns     = bundle.get('drop_columns', [])
model_name       = bundle.get('model_name', 'Unknown')
problem_type     = bundle.get('problem_type', 'Unknown')

# Explicitly load separate scaler and encoder files if they exist
scalers = {}
if os.path.exists(SCALER_PATH):
    with open(SCALER_PATH, 'rb') as f:
        scaler_payload = pickle.load(f)
        scalers = scaler_payload.get('scalers', {})

encoders = {}
if os.path.exists(ENCODER_PATH):
    with open(ENCODER_PATH, 'rb') as f:
        encoder_payload = pickle.load(f)
        encoders = encoder_payload.get('encoders', {})

from sklearn.preprocessing import LabelEncoder, OrdinalEncoder, LabelBinarizer


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/predict', methods=['POST'])
def predict():
    try:
        data = {}
        for feat in feature_names:
            val = request.form.get(feat, '')
            if val.strip() == '':
                data[feat] = np.nan
            else:
                try:
                    data[feat] = float(val)
                except ValueError:
                    data[feat] = val

        df = pd.DataFrame([data])

        # Drop excluded columns
        if drop_columns:
            cols_to_drop = [c for c in drop_columns if c in df.columns]
            if cols_to_drop:
                df = df.drop(columns=cols_to_drop)

        # 1. Imputation
        for col in df.columns:
            if col in imputers:
                imp = imputers[col]
                if imp == 'drop':
                    pass
                elif hasattr(imp, 'transform'):
                    try:
                        df[[col]] = imp.transform(df[[col]])
                    except:
                        pass
            if col in custom_impute:
                df[col] = df[col].fillna(custom_impute[col])

        # 2. Encoding
        for col, encoder in encoders.items():
            if col in df.columns:
                try:
                    if isinstance(encoder, LabelEncoder):
                        classes = set(encoder.classes_)
                        df[col] = df[col].astype(str).map(lambda s: s if s in classes else encoder.classes_[0])
                        df[col] = encoder.transform(df[col])
                    elif isinstance(encoder, OrdinalEncoder):
                        df[[col]] = encoder.transform(df[[col]])
                    elif isinstance(encoder, LabelBinarizer):
                        encoded = encoder.transform(df[col].astype(str))
                        if encoded.shape[1] == 1:
                            df[col] = encoded.ravel()
                        else:
                            new_cols = [f"{col}_{c}" for c in encoder.classes_]
                            df[new_cols] = encoded
                            df.drop(columns=[col], inplace=True)
                except:
                    pass

        # 3. One-hot
        if onehot_cols:
            existing = [c for c in onehot_cols if c in df.columns]
            if existing:
                df = pd.get_dummies(df, columns=existing, drop_first=True)

        # 4. Scaling
        for col, scaler in scalers.items():
            if col in df.columns:
                try:
                    df[[col]] = scaler.transform(df[[col]])
                except:
                    pass

        # 5. Align columns
        if trained_features:
            df = df.reindex(columns=trained_features, fill_value=0)

        prediction = model.predict(df)
        result = str(prediction[0])

        return jsonify({'prediction': result, 'success': True})

    except Exception as e:
        return jsonify({'error': str(e), 'success': False})


if __name__ == '__main__':
    print(f"\\n  Model: {model_name}")
    print(f"  Type:  {problem_type}")
    print(f"  Open http://localhost:5000 in your browser\\n")
    app.run(debug=True, host='0.0.0.0', port=5000)
'''

    def _gen_index_html(self, feature_names, numeric_cols, categorical_cols, categorical_values, target_name, model_name, problem_type):
        """Generate a beautiful, self-contained index.html."""

        # Build form fields HTML
        form_fields = ''
        for feat in feature_names:
            if feat in categorical_cols and feat in categorical_values:
                options = categorical_values[feat]
                opts_html = ''.join([f'<option value="{v}">{v}</option>' for v in sorted(str(o) for o in options)])
                form_fields += f'''
                <div class="col-md-6 mb-4">
                    <label class="form-label" for="field_{feat}">{feat}</label>
                    <select class="form-select" id="field_{feat}" name="{feat}">
                        <option value="" selected>Select {feat}...</option>
                        {opts_html}
                    </select>
                    <div class="form-text">Categorical</div>
                </div>'''
            else:
                form_fields += f'''
                <div class="col-md-6 mb-4">
                    <label class="form-label" for="field_{feat}">{feat}</label>
                    <input type="number" step="any" class="form-control" id="field_{feat}" name="{feat}" placeholder="Enter {feat}">
                    <div class="form-text">Numeric</div>
                </div>'''

        return '''<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>''' + model_name + ''' β€” Prediction App</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #6366f1;
            --primary-dark: #4f46e5;
            --accent: #06b6d4;
            --bg-dark: #0f172a;
            --bg-card: #1e293b;
            --bg-input: #334155;
            --text-primary: #f1f5f9;
            --text-muted: #94a3b8;
            --border: #475569;
            --success: #22c55e;
            --danger: #ef4444;
        }

        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: 'Inter', sans-serif;
            background: var(--bg-dark);
            color: var(--text-primary);
            min-height: 100vh;
        }

        /* ── Background animation ─────────────────────────── */
        body::before {
            content: '';
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background:
                radial-gradient(ellipse at 20% 50%, rgba(99, 102, 241, 0.12) 0%, transparent 50%),
                radial-gradient(ellipse at 80% 20%, rgba(6, 182, 212, 0.1) 0%, transparent 50%),
                radial-gradient(ellipse at 50% 80%, rgba(168, 85, 247, 0.08) 0%, transparent 50%);
            z-index: -1;
            animation: bgPulse 8s ease-in-out infinite alternate;
        }
        @keyframes bgPulse {
            0% { opacity: 0.7; }
            100% { opacity: 1; }
        }

        /* ── Navbar ───────────────────────────────────────── */
        .navbar-custom {
            background: rgba(15, 23, 42, 0.85);
            backdrop-filter: blur(20px);
            border-bottom: 1px solid rgba(99, 102, 241, 0.2);
            padding: 1rem 0;
        }
        .navbar-custom .brand {
            font-weight: 800;
            font-size: 1.4rem;
            color: var(--text-primary);
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 0.6rem;
        }
        .navbar-custom .brand i {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            font-size: 1.6rem;
        }
        .badge-model {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            letter-spacing: 0.5px;
        }

        /* ── Hero ─────────────────────────────────────────── */
        .hero {
            text-align: center;
            padding: 3rem 0 2rem;
        }
        .hero h1 {
            font-size: 2.6rem;
            font-weight: 800;
            margin-bottom: 0.6rem;
            background: linear-gradient(135deg, #f1f5f9, #cbd5e1);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        .hero p {
            color: var(--text-muted);
            font-size: 1.1rem;
            max-width: 520px;
            margin: 0 auto;
        }
        .hero-badge {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            background: rgba(99, 102, 241, 0.15);
            border: 1px solid rgba(99, 102, 241, 0.3);
            padding: 8px 18px;
            border-radius: 30px;
            font-size: 0.85rem;
            color: var(--accent);
            margin-top: 1rem;
        }

        /* ── Glass Card ───────────────────────────────────── */
        .glass-card {
            background: rgba(30, 41, 59, 0.7);
            backdrop-filter: blur(16px);
            border: 1px solid rgba(71, 85, 105, 0.4);
            border-radius: 20px;
            padding: 2.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.3);
            transition: border-color 0.3s;
        }
        .glass-card:hover {
            border-color: rgba(99, 102, 241, 0.4);
        }

        .card-title {
            font-weight: 700;
            font-size: 1.3rem;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.6rem;
        }
        .card-title i {
            color: var(--accent);
        }

        /* ── Form ─────────────────────────────────────────── */
        .form-label {
            font-weight: 600;
            font-size: 0.85rem;
            color: var(--text-muted);
            text-transform: uppercase;
            letter-spacing: 0.7px;
            margin-bottom: 0.4rem;
        }
        .form-control, .form-select {
            background: var(--bg-input);
            border: 1px solid var(--border);
            color: var(--text-primary);
            border-radius: 12px;
            padding: 12px 16px;
            font-size: 0.95rem;
            transition: all 0.3s;
        }
        .form-control:focus, .form-select:focus {
            background: rgba(51, 65, 85, 0.9);
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.15);
            color: var(--text-primary);
        }
        .form-control::placeholder { color: var(--text-muted); opacity: 0.6; }
        .form-text { color: var(--text-muted); font-size: 0.75rem; margin-top: 4px; }
        .form-select option { background: var(--bg-card); color: var(--text-primary); }

        /* ── Buttons ──────────────────────────────────────── */
        .btn-predict {
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            border: none;
            color: white;
            padding: 14px 40px;
            border-radius: 14px;
            font-weight: 700;
            font-size: 1.05rem;
            transition: all 0.3s;
            width: 100%;
            position: relative;
            overflow: hidden;
        }
        .btn-predict:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 30px rgba(99, 102, 241, 0.35);
            color: white;
        }
        .btn-predict:active { transform: translateY(0); }

        .btn-reset {
            background: transparent;
            border: 1px solid var(--border);
            color: var(--text-muted);
            padding: 14px 40px;
            border-radius: 14px;
            font-weight: 600;
            font-size: 1rem;
            transition: all 0.3s;
            width: 100%;
        }
        .btn-reset:hover {
            border-color: var(--danger);
            color: var(--danger);
        }

        /* ── Result ───────────────────────────────────────── */
        #resultSection {
            display: none;
            animation: slideUp 0.5s ease;
        }
        @keyframes slideUp {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .result-value {
            font-size: 3rem;
            font-weight: 800;
            background: linear-gradient(135deg, var(--success), var(--accent));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            word-break: break-all;
        }
        .result-label {
            color: var(--text-muted);
            font-size: 0.9rem;
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        .error-value {
            background: linear-gradient(135deg, var(--danger), #f97316);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        /* ── Loading Spinner ──────────────────────────────── */
        .spinner-overlay {
            display: none;
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(15, 23, 42, 0.85);
            backdrop-filter: blur(8px);
            z-index: 9999;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            gap: 1rem;
        }
        .spinner-ring {
            width: 50px; height: 50px;
            border: 4px solid rgba(99, 102, 241, 0.2);
            border-top-color: var(--primary);
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
        }
        @keyframes spin { to { transform: rotate(360deg); } }

        /* ── Footer ───────────────────────────────────────── */
        .footer {
            text-align: center;
            padding: 2rem 0;
            color: var(--text-muted);
            font-size: 0.8rem;
            border-top: 1px solid rgba(71, 85, 105, 0.3);
            margin-top: 3rem;
        }

        /* ── Stats Bar ────────────────────────────────────── */
        .stats-bar {
            display: flex;
            gap: 2rem;
            justify-content: center;
            flex-wrap: wrap;
            margin: 1.5rem 0;
        }
        .stat-item {
            text-align: center;
        }
        .stat-item .stat-val {
            font-size: 1.6rem;
            font-weight: 700;
            color: var(--accent);
        }
        .stat-item .stat-lbl {
            font-size: 0.75rem;
            color: var(--text-muted);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
    </style>
</head>
<body>

    <!-- Navbar -->
    <nav class="navbar-custom">
        <div class="container d-flex justify-content-between align-items-center">
            <a class="brand" href="#">
                <i class="fas fa-brain"></i> ''' + model_name + '''
            </a>
            <span class="badge-model">
                <i class="fas fa-microchip"></i> ''' + problem_type.title() + '''
            </span>
        </div>
    </nav>

    <!-- Hero -->
    <div class="container">
        <div class="hero">
            <h1><i class="fas fa-wand-magic-sparkles"></i> Prediction Engine</h1>
            <p>Enter your data below and get instant predictions powered by machine learning</p>
            <div class="hero-badge">
                <i class="fas fa-bullseye"></i> Predicting: <strong>''' + target_name + '''</strong>
            </div>
        </div>

        <!-- Stats -->
        <div class="stats-bar">
            <div class="stat-item">
                <div class="stat-val">''' + str(len(feature_names)) + '''</div>
                <div class="stat-lbl">Features</div>
            </div>
            <div class="stat-item">
                <div class="stat-val">''' + str(len(numeric_cols)) + '''</div>
                <div class="stat-lbl">Numeric</div>
            </div>
            <div class="stat-item">
                <div class="stat-val">''' + str(len(categorical_cols)) + '''</div>
                <div class="stat-lbl">Categorical</div>
            </div>
        </div>

        <!-- Form Card -->
        <div class="row justify-content-center">
            <div class="col-lg-10">
                <form id="predictForm" class="glass-card">
                    <div class="card-title">
                        <i class="fas fa-sliders"></i> Input Features
                    </div>
                    <div class="row">''' + form_fields + '''
                    </div>
                    <div class="row mt-3">
                        <div class="col-md-8 mb-2">
                            <button type="submit" class="btn-predict" id="predictBtn">
                                <i class="fas fa-bolt"></i> Get Prediction
                            </button>
                        </div>
                        <div class="col-md-4 mb-2">
                            <button type="reset" class="btn-reset" id="resetBtn">
                                <i class="fas fa-rotate-left"></i> Reset
                            </button>
                        </div>
                    </div>
                </form>

                <!-- Result -->
                <div id="resultSection" class="glass-card text-center">
                    <div class="card-title justify-content-center">
                        <i class="fas fa-sparkles"></i> Prediction Result
                    </div>
                    <div class="result-label mb-2">''' + target_name + '''</div>
                    <div id="resultValue" class="result-value">β€”</div>
                </div>
            </div>
        </div>
    </div>

    <!-- Loading -->
    <div class="spinner-overlay" id="spinner">
        <div class="spinner-ring"></div>
        <div style="color: var(--text-muted);">Analyzing...</div>
    </div>

    <!-- Footer -->
    <div class="footer">
        <i class="fas fa-robot"></i> Powered by Data2Model β€” Automated Machine Learning Platform
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const form = document.getElementById('predictForm');
        const resultSection = document.getElementById('resultSection');
        const resultValue = document.getElementById('resultValue');
        const spinner = document.getElementById('spinner');

        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            spinner.style.display = 'flex';
            resultSection.style.display = 'none';

            const formData = new FormData(form);

            try {
                const resp = await fetch('/predict', { method: 'POST', body: formData });
                const data = await resp.json();

                spinner.style.display = 'none';
                resultSection.style.display = 'block';
                resultSection.style.animation = 'none';
                void resultSection.offsetHeight; // trigger reflow
                resultSection.style.animation = 'slideUp 0.5s ease';

                if (data.success) {
                    resultValue.textContent = data.prediction;
                    resultValue.className = 'result-value';
                } else {
                    resultValue.textContent = data.error || 'Prediction failed';
                    resultValue.className = 'result-value error-value';
                }
            } catch (err) {
                spinner.style.display = 'none';
                resultSection.style.display = 'block';
                resultValue.textContent = 'Connection error';
                resultValue.className = 'result-value error-value';
            }
        });

        document.getElementById('resetBtn').addEventListener('click', () => {
            resultSection.style.display = 'none';
        });
    </script>
</body>
</html>'''

    # ─────────────────────────────────────────────────────────────────────────
    # Main Pipeline
    # ─────────────────────────────────────────────────────────────────────────
    def run_complete_pipeline(self,
                              file_path,
                              target_column=None,
                              file_type='csv',
                              problem_type='auto',
                              split_type='train_test',      # FIX 4
                              test_size=0.2,
                              val_size=0.2,
                              null_strategies=None,          # FIX 1 & 2
                              scaling_config='standard',     # FIX 6
                              encoding_config='auto',        # FIX 7
                              categorical_overrides=None,    # FIX 8
                              drop_columns=None):            # NEW: Delete Columns feature
        print("\n" + "="*55)
        print("πŸš€ DATA2MODEL - AUTOMATED ML PIPELINE")
        print("="*55 + "\n")

        # 1. Load
        data = self.load_data(file_path, file_type)

        # Apply column dropping
        self.drop_columns = drop_columns or []
        if self.drop_columns:
            # Ensure target column is not dropped
            if target_column in self.drop_columns:
                self.drop_columns.remove(target_column)
                print(f"  Warning: Target column '{target_column}' cannot be dropped. It was removed from drop list.")
            
            existing_to_drop = [c for c in self.drop_columns if c in data.columns]
            if existing_to_drop:
                data = data.drop(columns=existing_to_drop)
                self.preprocessing_steps.append(f"Dropped columns: {', '.join(existing_to_drop)}")
                print(f"  Dropped {len(existing_to_drop)} columns specified by user.")

        # Ensure numeric-looking columns accidentally read as strings are safely converted before detection/training
        for col in data.columns:
            if col == target_column:
                continue
            if str(data[col].dtype) in ('object', 'string'):
                converted = pd.to_numeric(data[col], errors='coerce')
                non_null_original = data[col].dropna().shape[0]
                non_null_converted = converted.dropna().shape[0]
                if non_null_original > 0 and non_null_converted >= 0.9 * non_null_original:
                    data[col] = converted
                    print(f"  Safely converted numeric-looking column '{col}' to numeric.")

        # 2. Analyse with smart type detection (FIX 8)
        analysis = self.analyze_data(data, categorical_overrides, target_column=target_column)
        self.numeric_cols = analysis['numeric_columns']
        self.categorical_cols = analysis['categorical_columns']
        print(f"  Numeric cols: {len(self.numeric_cols)} | Categorical cols: {len(self.categorical_cols)}")

        # 3. Null handling with imputation (FIX 1 & 2)
        print("\nπŸ”§ Handling missing values...")
        data = self.handle_missing_values(data, null_strategies, target_column=target_column)

        # 4. Remove duplicates
        before = len(data)
        data = data.drop_duplicates()
        if len(data) < before:
            print(f"  Removed {before - len(data)} duplicate rows")

        # ── Unsupervised path (FIX 3: target column not needed) ──────────────
        is_unsupervised = problem_type in ('clustering', 'dimensionality_reduction', 'association')

        if is_unsupervised:
            X = data.copy()
            self.feature_names = list(X.columns)

            # Encode + Scale
            dummy_test = X.copy()
            X, dummy_test = self.encode_features(X, dummy_test,
                                                  encoding_config=encoding_config,
                                                  categorical_cols=self.categorical_cols)
            X, dummy_test = self.scale_features(X, dummy_test,
                                                 scaling_config=scaling_config,
                                                 numeric_cols=self.numeric_cols)

            self.trained_features = list(X.columns)
            self.train_unsupervised(X, problem_type)
            model_path = self.save_model()
            return {
                'model_path': model_path,
                'results': self.results,
                'analysis': analysis,
                'model_name': self.model_name,
                'problem_type': self.problem_type,
                'split_info': 'No split (unsupervised)',
            }

        # ── Supervised path ──────────────────────────────────────────────────
        if target_column is None or target_column not in data.columns:
            raise ValueError(f"Target column '{target_column}' not found.")

        X = data.drop(columns=[target_column])
        y = data[target_column]
        self.feature_names = list(X.columns)
        self.target_name = target_column

        # Remove target from col lists if it was included
        num_cols = [c for c in self.numeric_cols if c != target_column]
        cat_cols = [c for c in self.categorical_cols if c != target_column]

        # Store categorical unique values for deployable app generation
        self.categorical_values = {}
        for col in cat_cols:
            if col in X.columns:
                self.categorical_values[col] = X[col].dropna().unique().tolist()[:50]

        # 5. Split (FIX 4)
        use_val = (split_type == 'train_test_val')
        if use_val:
            X_tr, X_tmp, y_tr, y_tmp = train_test_split(X, y, test_size=(test_size + val_size), random_state=42)
            ratio = val_size / (test_size + val_size)
            X_te, X_val, y_te, y_val = train_test_split(X_tmp, y_tmp, test_size=ratio, random_state=42)
            split_info = f"Train {int((1-test_size-val_size)*100)}% / Test {int(test_size*100)}% / Val {int(val_size*100)}%"
            print(f"\nβœ‚ Split: {split_info}")
            print(f"  Train: {len(X_tr)} | Test: {len(X_te)} | Val: {len(X_val)}")
        else:
            X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=test_size, random_state=42)
            X_val, y_val = None, None
            split_info = f"Train {int((1-test_size)*100)}% / Test {int(test_size*100)}%"
            print(f"\nβœ‚ Split: {split_info}")
            print(f"  Train: {len(X_tr)} | Test: {len(X_te)}")

        # 6. Encode categorical (FIX 5 & 7: only if cat cols exist, per-column)
        print("\nπŸ”€ Encoding categorical features...")
        if use_val:
            X_tr, X_te, X_val = self.encode_features(
                X_tr, X_te, X_val, encoding_config=encoding_config, categorical_cols=cat_cols)
        else:
            X_tr, X_te = self.encode_features(
                X_tr, X_te, encoding_config=encoding_config, categorical_cols=cat_cols)

        # 7. Scale numeric (FIX 6: per-column)
        print("βš– Scaling numeric features...")
        # Update numeric_cols after encoding (some may have been one-hot expanded)
        current_num_cols = [c for c in X_tr.columns if c in num_cols]
        if use_val:
            X_tr, X_te, X_val = self.scale_features(
                X_tr, X_te, X_val, scaling_config=scaling_config, numeric_cols=current_num_cols)
        else:
            X_tr, X_te = self.scale_features(
                X_tr, X_te, scaling_config=scaling_config, numeric_cols=current_num_cols)

        # 8. Train
        print("\nπŸ€– Training models...")
        self.trained_features = list(X_tr.columns)
        self.train_model(X_tr, y_tr, X_te, y_te, problem_type=problem_type)

        # 9. Validation metrics (if val split used)
        if use_val and self.model:
            y_val_pred = self.model.predict(X_val)
            if self.problem_type == 'classification':
                val_acc = accuracy_score(y_val, y_val_pred)
                self.results['validation_accuracy'] = val_acc
                print(f"  Validation Accuracy: {val_acc:.4f}")
            else:
                self.results['validation_rmse'] = np.sqrt(mean_squared_error(y_val, y_val_pred))
                self.results['validation_r2'] = r2_score(y_val, y_val_pred)
                print(f"  Validation RΒ²: {self.results['validation_r2']:.4f}")

        # 10. Save
        model_path = self.save_model()

        # Save preprocessing artifacts only when they were applied
        scaler_path = None
        encoder_path = None
        if self.scalers:
            scaler_path = self.save_scalers()
        if self.encoders or (hasattr(self, 'onehot_cols') and self.onehot_cols):
            encoder_path = self.save_encoders()

        # Generate the deployable app bundle
        deployable_app_path = self.generate_deployable_app(model_path, scaler_path, encoder_path)

        print("\n" + "="*55)
        print("βœ… PIPELINE COMPLETED!")
        print("="*55 + "\n")

        return {
            'model_path': model_path,
            'scaler_path': scaler_path,
            'encoder_path': encoder_path,
            'deployable_app_path': deployable_app_path,
            'scaling_applied': bool(self.scalers),
            'encoding_applied': bool(self.encoders) or (hasattr(self, 'onehot_cols') and bool(self.onehot_cols)),
            'results': self.results,
            'analysis': analysis,
            'model_name': self.model_name,
            'problem_type': self.problem_type,
            'split_info': split_info,
            'use_val': use_val,
        }