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
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
"""
Forms for the core app.
"""
import re
from zoneinfo import available_timezones

from django import forms
from django.utils.text import slugify

from core.models import Script, Environment, ScriptSchedule, Tag, DataStore, DataStoreEntry, DataStoreAPIToken
from core.services import EnvironmentService


# Regex pattern for secret key validation (uppercase, numbers, underscores, must start with letter)
SECRET_KEY_PATTERN = re.compile(r"^[A-Z][A-Z0-9_]*$")


# Common timezone choices (sorted, common ones first)
COMMON_TIMEZONES = [
    "UTC",
    "America/New_York",
    "America/Chicago",
    "America/Denver",
    "America/Los_Angeles",
    "Europe/London",
    "Europe/Paris",
    "Europe/Berlin",
    "Asia/Tokyo",
    "Asia/Shanghai",
    "Asia/Singapore",
    "Australia/Sydney",
]


def get_timezone_choices():
    """Generate timezone choices with common ones first."""
    all_tz = sorted(available_timezones())
    common = [(tz, tz) for tz in COMMON_TIMEZONES if tz in all_tz]
    others = [(tz, tz) for tz in all_tz if tz not in COMMON_TIMEZONES]
    return [("", "---")] + common + [("---", "─" * 20)] + others


class ScriptForm(forms.ModelForm):
    """Form for creating and editing scripts."""

    class Meta:
        model = Script
        fields = [
            "name",
            "description",
            "code",
            "environment",
            "tags",
            "timeout_seconds",
            "is_enabled",
            "notify_on",
            "notify_email",
            "notify_webhook_url",
            "notify_webhook_enabled",
        ]
        widgets = {
            "name": forms.TextInput(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                    "placeholder": "My Script Name",
                }
            ),
            "description": forms.Textarea(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                    "rows": 2,
                    "placeholder": "What does this script do?",
                }
            ),
            "code": forms.Textarea(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text font-mono text-sm placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                    "rows": 15,
                    "placeholder": '# Your Python code here\nprint("Hello, World!")',
                }
            ),
            "environment": forms.Select(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                }
            ),
            "tags": forms.CheckboxSelectMultiple(
                attrs={
                    "class": "tag-checkbox",
                }
            ),
            "timeout_seconds": forms.NumberInput(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                    "min": 1,
                    "max": 86400,
                }
            ),
            "is_enabled": forms.CheckboxInput(
                attrs={
                    "class": "w-5 h-5 text-code-accent bg-code-bg border-code-border rounded focus:ring-code-accent focus:ring-2",
                }
            ),
            "notify_on": forms.Select(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                }
            ),
            "notify_email": forms.EmailInput(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                    "placeholder": "Override default email (optional)",
                }
            ),
            "notify_webhook_url": forms.URLInput(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                    "placeholder": "https://your-service.com/webhook",
                }
            ),
            "notify_webhook_enabled": forms.CheckboxInput(
                attrs={
                    "class": "w-5 h-5 text-code-accent bg-code-bg border-code-border rounded focus:ring-code-accent focus:ring-2",
                }
            ),
        }
        labels = {
            "name": "Script Name",
            "description": "Description",
            "code": "Python Code",
            "environment": "Environment",
            "tags": "Tags",
            "timeout_seconds": "Timeout (seconds)",
            "is_enabled": "Enabled",
            "notify_on": "Notify On",
            "notify_email": "Notification Email",
            "notify_webhook_url": "Webhook URL",
            "notify_webhook_enabled": "Enable Webhook",
        }
        help_texts = {
            "timeout_seconds": "Maximum execution time (1 second to 24 hours)",
            "notify_email": "Leave empty to use global default",
            "notify_webhook_url": "URL to POST notifications to when script completes",
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Only show active environments
        self.fields["environment"].queryset = Environment.objects.filter(is_active=True)

    def clean_code(self):
        code = self.cleaned_data.get("code", "").strip()
        if not code:
            raise forms.ValidationError("Script code cannot be empty.")
        return code

    def clean_timeout_seconds(self):
        timeout = self.cleaned_data.get("timeout_seconds")
        if timeout is not None and (timeout < 1 or timeout > 86400):
            raise forms.ValidationError("Timeout must be between 1 and 86400 seconds (24 hours).")
        return timeout


class TagForm(forms.ModelForm):
    """Form for creating and editing tags."""

    class Meta:
        model = Tag
        fields = ["name", "color"]
        widgets = {
            "name": forms.TextInput(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                    "placeholder": "Tag name",
                }
            ),
            "color": forms.Select(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                }
            ),
        }
        labels = {
            "name": "Tag Name",
            "color": "Color",
        }

    def clean_name(self):
        name = self.cleaned_data.get("name", "").strip()
        if not name:
            raise forms.ValidationError("Tag name is required.")
        # Check uniqueness (excluding current instance for edits)
        qs = Tag.objects.filter(name__iexact=name)
        if self.instance.pk:
            qs = qs.exclude(pk=self.instance.pk)
        if qs.exists():
            raise forms.ValidationError("A tag with this name already exists.")
        return name


class ScheduleForm(forms.ModelForm):
    """Form for configuring script schedules."""

    WEEKDAY_CHOICES = [
        (0, "Monday"),
        (1, "Tuesday"),
        (2, "Wednesday"),
        (3, "Thursday"),
        (4, "Friday"),
        (5, "Saturday"),
        (6, "Sunday"),
    ]

    MONTHDAY_CHOICES = [(i, str(i)) for i in range(1, 32)]

    # Custom field for daily times (comma-separated input)
    daily_times_input = forms.CharField(
        required=False,
        widget=forms.TextInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50",
                "placeholder": "09:00, 18:00",
            }
        ),
        label="Run Times",
        help_text="Comma-separated times in HH:MM format (24-hour)",
    )

    # Weekly mode fields
    weekly_days_input = forms.MultipleChoiceField(
        required=False,
        choices=WEEKDAY_CHOICES,
        widget=forms.CheckboxSelectMultiple(
            attrs={
                "class": "sr-only peer",
            }
        ),
        label="Days of Week",
    )

    weekly_times_input = forms.CharField(
        required=False,
        widget=forms.TextInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50",
                "placeholder": "09:00, 18:00",
            }
        ),
        label="Run Times",
        help_text="Comma-separated times in HH:MM format (24-hour)",
    )

    # Monthly mode fields
    monthly_days_input = forms.MultipleChoiceField(
        required=False,
        choices=MONTHDAY_CHOICES,
        widget=forms.CheckboxSelectMultiple(
            attrs={
                "class": "sr-only peer",
            }
        ),
        label="Days of Month",
    )

    monthly_times_input = forms.CharField(
        required=False,
        widget=forms.TextInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50",
                "placeholder": "09:00, 18:00",
            }
        ),
        label="Run Times",
        help_text="Comma-separated times in HH:MM format (24-hour)",
    )

    timezone = forms.ChoiceField(
        choices=get_timezone_choices,
        initial="UTC",
        widget=forms.Select(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text focus:outline-none focus:ring-2 focus:ring-code-accent/50",
            }
        ),
    )

    class Meta:
        model = ScriptSchedule
        fields = ["run_mode", "interval_minutes", "timezone", "is_active"]
        widgets = {
            "run_mode": forms.RadioSelect(
                attrs={
                    "class": "sr-only peer",
                }
            ),
            "interval_minutes": forms.Select(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text focus:outline-none focus:ring-2 focus:ring-code-accent/50",
                }
            ),
            "is_active": forms.CheckboxInput(
                attrs={
                    "class": "w-5 h-5 text-code-accent bg-code-bg border-code-border rounded focus:ring-code-accent focus:ring-2",
                }
            ),
        }
        labels = {
            "run_mode": "Run Mode",
            "interval_minutes": "Interval",
            "is_active": "Schedule Active",
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Populate daily_times_input from instance
        if self.instance and self.instance.pk and self.instance.daily_times:
            self.fields["daily_times_input"].initial = ", ".join(
                self.instance.daily_times
            )

        # Populate weekly fields from instance
        if self.instance and self.instance.pk:
            if self.instance.weekly_days:
                self.fields["weekly_days_input"].initial = [
                    str(d) for d in self.instance.weekly_days
                ]
            if self.instance.weekly_times:
                self.fields["weekly_times_input"].initial = ", ".join(
                    self.instance.weekly_times
                )

        # Populate monthly fields from instance
        if self.instance and self.instance.pk:
            if self.instance.monthly_days:
                self.fields["monthly_days_input"].initial = [
                    str(d) for d in self.instance.monthly_days
                ]
            if self.instance.monthly_times:
                self.fields["monthly_times_input"].initial = ", ".join(
                    self.instance.monthly_times
                )

    def _parse_times(self, value):
        """Parse and validate comma-separated times input."""
        if not value:
            return []

        value = value.strip()
        if not value:
            return []

        times = []
        for time_str in value.split(","):
            time_str = time_str.strip()
            if not time_str:
                continue

            # Validate HH:MM format
            try:
                parts = time_str.split(":")
                if len(parts) != 2:
                    raise ValueError
                hour, minute = int(parts[0]), int(parts[1])
                if not (0 <= hour <= 23 and 0 <= minute <= 59):
                    raise ValueError
                times.append(f"{hour:02d}:{minute:02d}")
            except ValueError:
                raise forms.ValidationError(
                    f"Invalid time format: '{time_str}'. Use HH:MM (e.g., 09:00)"
                )

        return times

    def clean_daily_times_input(self):
        """Parse and validate daily times input."""
        return self._parse_times(self.cleaned_data.get("daily_times_input", ""))

    def clean_weekly_times_input(self):
        """Parse and validate weekly times input."""
        return self._parse_times(self.cleaned_data.get("weekly_times_input", ""))

    def clean_monthly_times_input(self):
        """Parse and validate monthly times input."""
        return self._parse_times(self.cleaned_data.get("monthly_times_input", ""))

    def clean(self):
        cleaned_data = super().clean()
        run_mode = cleaned_data.get("run_mode")

        if run_mode == ScriptSchedule.RunMode.INTERVAL:
            if not cleaned_data.get("interval_minutes"):
                self.add_error(
                    "interval_minutes", "Interval is required for interval mode."
                )

        elif run_mode == ScriptSchedule.RunMode.DAILY:
            daily_times = cleaned_data.get("daily_times_input", [])
            if not daily_times:
                self.add_error(
                    "daily_times_input",
                    "At least one time is required for daily mode.",
                )

        elif run_mode == ScriptSchedule.RunMode.WEEKLY:
            weekly_days = cleaned_data.get("weekly_days_input", [])
            weekly_times = cleaned_data.get("weekly_times_input", [])
            if not weekly_days:
                self.add_error(
                    "weekly_days_input",
                    "At least one day is required for weekly mode.",
                )
            if not weekly_times:
                self.add_error(
                    "weekly_times_input",
                    "At least one time is required for weekly mode.",
                )

        elif run_mode == ScriptSchedule.RunMode.MONTHLY:
            monthly_days = cleaned_data.get("monthly_days_input", [])
            monthly_times = cleaned_data.get("monthly_times_input", [])
            if not monthly_days:
                self.add_error(
                    "monthly_days_input",
                    "At least one day is required for monthly mode.",
                )
            if not monthly_times:
                self.add_error(
                    "monthly_times_input",
                    "At least one time is required for monthly mode.",
                )

        return cleaned_data

    def save(self, commit=True):
        instance = super().save(commit=False)

        # Set daily_times from parsed input
        instance.daily_times = self.cleaned_data.get("daily_times_input", [])

        # Set weekly fields from parsed input
        weekly_days = self.cleaned_data.get("weekly_days_input", [])
        instance.weekly_days = [int(d) for d in weekly_days] if weekly_days else []
        instance.weekly_times = self.cleaned_data.get("weekly_times_input", [])

        # Set monthly fields from parsed input
        monthly_days = self.cleaned_data.get("monthly_days_input", [])
        instance.monthly_days = [int(d) for d in monthly_days] if monthly_days else []
        instance.monthly_times = self.cleaned_data.get("monthly_times_input", [])

        if commit:
            instance.save()

        return instance


class EnvironmentCreateForm(forms.ModelForm):
    """Form for creating a new environment."""

    python_path = forms.ChoiceField(
        choices=[],
        widget=forms.Select(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
            }
        ),
        label="Python Version",
        help_text="Select Python installation to use for this environment",
    )

    class Meta:
        model = Environment
        fields = ["name", "description"]
        widgets = {
            "name": forms.TextInput(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                    "placeholder": "My Environment",
                }
            ),
            "description": forms.Textarea(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                    "rows": 2,
                    "placeholder": "Environment description (optional)",
                }
            ),
        }
        labels = {
            "name": "Environment Name",
            "description": "Description",
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Populate python_path choices from discovered Python installations
        pythons = EnvironmentService.discover_python_versions()
        choices = [(p["path"], p["display"]) for p in pythons]
        if not choices:
            choices = [("", "No Python installations found")]
        self.fields["python_path"].choices = choices

    def clean_name(self):
        """Validate name and check for path uniqueness."""
        name = self.cleaned_data.get("name", "").strip()
        if not name:
            raise forms.ValidationError("Environment name is required.")

        # Generate path from slugified name
        base_path = slugify(name)
        if not base_path:
            base_path = "environment"

        # Ensure path is unique
        path = base_path
        counter = 1
        while Environment.objects.filter(path=path).exists():
            path = f"{base_path}-{counter}"
            counter += 1

        # Store generated path for use in view
        self._generated_path = path
        return name

    def get_generated_path(self) -> str:
        """Return the generated path after validation."""
        return getattr(self, "_generated_path", slugify(self.cleaned_data.get("name", "env")))


class EnvironmentEditForm(forms.ModelForm):
    """Form for editing environment details (name/description only)."""

    class Meta:
        model = Environment
        fields = ["name", "description"]
        widgets = {
            "name": forms.TextInput(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                    "placeholder": "My Environment",
                }
            ),
            "description": forms.Textarea(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                    "rows": 2,
                    "placeholder": "Environment description (optional)",
                }
            ),
        }
        labels = {
            "name": "Environment Name",
            "description": "Description",
        }


class PackageInstallForm(forms.Form):
    """Form for installing a single package."""

    package_spec = forms.CharField(
        max_length=200,
        widget=forms.TextInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text font-mono placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "placeholder": "requests==2.31.0",
            }
        ),
        label="Package",
        help_text="Package name with optional version (e.g., requests, django>=4.0)",
    )

    def clean_package_spec(self):
        spec = self.cleaned_data.get("package_spec", "").strip()
        if not spec:
            raise forms.ValidationError("Package specification is required.")
        if not EnvironmentService.validate_package_spec(spec):
            raise forms.ValidationError(
                "Invalid package specification. Use format: package or package==version"
            )
        return spec


class BulkInstallForm(forms.Form):
    """Form for bulk package installation from requirements."""

    requirements = forms.CharField(
        widget=forms.Textarea(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text font-mono text-sm placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "rows": 10,
                "placeholder": "requests==2.31.0\ndjango>=4.0\nnumpy",
            }
        ),
        label="Requirements",
        help_text="Paste requirements.txt content (one package per line)",
        required=False,
    )

    requirements_file = forms.FileField(
        required=False,
        widget=forms.FileInput(
            attrs={
                "class": "block w-full text-sm text-code-muted file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-code-accent file:text-white hover:file:bg-code-accent/90 cursor-pointer",
                "accept": ".txt",
            }
        ),
        label="Or upload requirements.txt",
    )

    def clean(self):
        cleaned_data = super().clean()
        text = cleaned_data.get("requirements", "").strip()
        file = cleaned_data.get("requirements_file")

        if not text and not file:
            raise forms.ValidationError(
                "Provide requirements text or upload a file."
            )

        # If file provided, read its content
        if file:
            try:
                content = file.read().decode("utf-8")
                cleaned_data["requirements"] = content
            except UnicodeDecodeError:
                raise forms.ValidationError(
                    "Could not read file. Ensure it's a valid text file."
                )

        # Validate each line
        requirements_text = cleaned_data.get("requirements", "")
        for line in requirements_text.splitlines():
            line = line.strip()
            # Skip empty lines and comments
            if not line or line.startswith("#") or line.startswith("-"):
                continue
            # Extract package spec (first word before any whitespace)
            pkg_spec = line.split()[0] if line.split() else ""
            if pkg_spec and not EnvironmentService.validate_package_spec(pkg_spec):
                raise forms.ValidationError(f"Invalid package specification: {line}")

        return cleaned_data


class SecretCreateForm(forms.Form):
    """Form for creating a new secret."""

    key = forms.CharField(
        max_length=100,
        widget=forms.TextInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text font-mono placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent uppercase",
                "placeholder": "API_KEY",
                "autocomplete": "off",
            }
        ),
        label="Key Name",
        help_text="Uppercase letters, numbers, and underscores only. Must start with a letter.",
    )

    value = forms.CharField(
        widget=forms.Textarea(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text font-mono placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "rows": 3,
                "placeholder": "sk-your-secret-value-here",
                "autocomplete": "off",
            }
        ),
        label="Secret Value",
        help_text="The secret value (will be encrypted at rest)",
    )

    description = forms.CharField(
        required=False,
        widget=forms.Textarea(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "rows": 2,
                "placeholder": "What is this secret used for?",
            }
        ),
        label="Description",
        help_text="Optional description to help remember what this secret is for",
    )

    def clean_key(self):
        """Validate and normalize the key."""
        key = self.cleaned_data.get("key", "").strip().upper()

        if not key:
            raise forms.ValidationError("Key name is required.")

        if not SECRET_KEY_PATTERN.match(key):
            raise forms.ValidationError(
                "Key must start with a letter and contain only uppercase letters, numbers, and underscores."
            )

        # Check for reserved environment variable names
        reserved = {
            "PATH",
            "HOME",
            "USER",
            "SHELL",
            "PWD",
            "PYTHONPATH",
            "VIRTUAL_ENV",
            "PYTHONHOME",
            "PYTHONDONTWRITEBYTECODE",
            "PYTHONUNBUFFERED",
        }
        if key in reserved:
            raise forms.ValidationError(
                f"'{key}' is a reserved environment variable name."
            )

        # Check if key already exists
        from core.models import Secret

        if Secret.objects.filter(key=key).exists():
            raise forms.ValidationError(f"A secret with key '{key}' already exists.")

        return key

    def clean_value(self):
        """Validate the secret value."""
        value = self.cleaned_data.get("value", "")

        if not value:
            raise forms.ValidationError("Secret value is required.")

        # Reasonable max length for secrets
        if len(value) > 10000:
            raise forms.ValidationError(
                "Secret value is too long (max 10,000 characters)."
            )

        return value


class SecretEditForm(forms.Form):
    """Form for editing an existing secret (value and description only)."""

    value = forms.CharField(
        required=False,
        widget=forms.Textarea(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text font-mono placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "rows": 3,
                "placeholder": "Leave blank to keep current value",
                "autocomplete": "off",
            }
        ),
        label="New Secret Value",
        help_text="Leave blank to keep the current value",
    )

    description = forms.CharField(
        required=False,
        widget=forms.Textarea(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "rows": 2,
                "placeholder": "What is this secret used for?",
            }
        ),
        label="Description",
    )

    def clean_value(self):
        """Validate the secret value if provided."""
        value = self.cleaned_data.get("value", "")

        if value and len(value) > 10000:
            raise forms.ValidationError(
                "Secret value is too long (max 10,000 characters)."
            )

        return value


class NotificationSettingsForm(forms.Form):
    """Form for global notification settings."""

    from core.models import GlobalSettings

    EMAIL_BACKEND_CHOICES = [
        (GlobalSettings.EmailBackend.DISABLED, "Disabled"),
        (GlobalSettings.EmailBackend.SMTP, "SMTP"),
        (GlobalSettings.EmailBackend.RESEND, "Resend API"),
    ]

    email_backend = forms.ChoiceField(
        choices=EMAIL_BACKEND_CHOICES,
        initial=GlobalSettings.EmailBackend.DISABLED,
        widget=forms.RadioSelect(
            attrs={
                "class": "sr-only peer",
            }
        ),
        label="Email Backend",
    )

    # SMTP Configuration
    smtp_host = forms.CharField(
        required=False,
        max_length=255,
        widget=forms.TextInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "placeholder": "smtp.example.com",
            }
        ),
        label="SMTP Host",
    )

    smtp_port = forms.IntegerField(
        required=False,
        initial=587,
        widget=forms.NumberInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "min": 1,
                "max": 65535,
            }
        ),
        label="SMTP Port",
    )

    smtp_username = forms.CharField(
        required=False,
        max_length=255,
        widget=forms.TextInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "placeholder": "username@example.com",
            }
        ),
        label="SMTP Username",
    )

    smtp_password = forms.CharField(
        required=False,
        widget=forms.PasswordInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "placeholder": "Leave blank to keep current",
                "autocomplete": "new-password",
            }
        ),
        label="SMTP Password",
    )

    smtp_use_tls = forms.BooleanField(
        required=False,
        initial=True,
        widget=forms.CheckboxInput(
            attrs={
                "class": "w-5 h-5 text-code-accent bg-code-bg border-code-border rounded focus:ring-code-accent focus:ring-2",
            }
        ),
        label="Use TLS",
    )

    smtp_from_email = forms.EmailField(
        required=False,
        widget=forms.EmailInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "placeholder": "noreply@example.com",
            }
        ),
        label="From Email",
    )

    # Resend Configuration
    resend_api_key = forms.CharField(
        required=False,
        widget=forms.PasswordInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "placeholder": "Leave blank to keep current",
                "autocomplete": "new-password",
            }
        ),
        label="Resend API Key",
    )

    resend_from_email = forms.EmailField(
        required=False,
        widget=forms.EmailInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "placeholder": "noreply@yourdomain.com",
            }
        ),
        label="From Email",
    )

    # Default notification email
    default_notification_email = forms.EmailField(
        required=False,
        widget=forms.EmailInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "placeholder": "notifications@example.com",
            }
        ),
        label="Default Notification Email",
        help_text="All script notifications will be sent here unless overridden per-script.",
    )

    def __init__(self, *args, instance=None, **kwargs):
        """Initialize form with existing settings."""
        super().__init__(*args, **kwargs)
        if instance:
            self.fields["email_backend"].initial = instance.email_backend
            self.fields["smtp_host"].initial = instance.smtp_host
            self.fields["smtp_port"].initial = instance.smtp_port
            self.fields["smtp_username"].initial = instance.smtp_username
            self.fields["smtp_use_tls"].initial = instance.smtp_use_tls
            self.fields["smtp_from_email"].initial = instance.smtp_from_email
            self.fields["resend_from_email"].initial = instance.resend_from_email
            self.fields["default_notification_email"].initial = instance.default_notification_email

    def clean(self):
        """Validate configuration based on selected backend."""
        cleaned_data = super().clean()
        backend = cleaned_data.get("email_backend")

        from core.models import GlobalSettings

        if backend == GlobalSettings.EmailBackend.SMTP:
            if not cleaned_data.get("smtp_host"):
                self.add_error("smtp_host", "SMTP host is required for SMTP backend.")
            if not cleaned_data.get("smtp_from_email"):
                self.add_error("smtp_from_email", "From email is required for SMTP backend.")

        elif backend == GlobalSettings.EmailBackend.RESEND:
            if not cleaned_data.get("resend_from_email"):
                self.add_error("resend_from_email", "From email is required for Resend backend.")

        return cleaned_data

    def save(self, instance):
        """Save the notification settings to the GlobalSettings instance."""
        from core.services import EncryptionService

        instance.email_backend = self.cleaned_data["email_backend"]
        instance.smtp_host = self.cleaned_data.get("smtp_host") or ""
        instance.smtp_port = self.cleaned_data.get("smtp_port") or 587
        instance.smtp_username = self.cleaned_data.get("smtp_username") or ""
        instance.smtp_use_tls = self.cleaned_data.get("smtp_use_tls", True)
        instance.smtp_from_email = self.cleaned_data.get("smtp_from_email") or ""
        instance.resend_from_email = self.cleaned_data.get("resend_from_email") or ""
        instance.default_notification_email = self.cleaned_data.get("default_notification_email") or ""

        # Encrypt and save SMTP password if provided
        smtp_password = self.cleaned_data.get("smtp_password")
        if smtp_password:
            instance.smtp_password_encrypted = EncryptionService.encrypt(smtp_password)

        # Encrypt and save Resend API key if provided
        resend_api_key = self.cleaned_data.get("resend_api_key")
        if resend_api_key:
            instance.resend_api_key_encrypted = EncryptionService.encrypt(resend_api_key)

        instance.save()
        return instance


class GeneralSettingsForm(forms.Form):
    """Form for general instance settings."""

    from core.models import GlobalSettings

    DATE_FORMAT_CHOICES = [
        (GlobalSettings.DateFormat.ISO, "YYYY-MM-DD (ISO)"),
        (GlobalSettings.DateFormat.US, "MM/DD/YYYY (US)"),
        (GlobalSettings.DateFormat.EU, "DD/MM/YYYY (EU)"),
        (GlobalSettings.DateFormat.DOT, "DD.MM.YYYY"),
    ]

    TIME_FORMAT_CHOICES = [
        (GlobalSettings.TimeFormat.H24, "24-hour (14:30)"),
        (GlobalSettings.TimeFormat.H12, "12-hour (2:30 PM)"),
    ]

    instance_name = forms.CharField(
        max_length=100,
        required=False,
        widget=forms.TextInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "placeholder": "PyRunner",
            }
        ),
        label="Instance Name",
        help_text="Displayed in the header and email notifications",
    )

    timezone = forms.ChoiceField(
        choices=get_timezone_choices,
        initial="UTC",
        widget=forms.Select(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
            }
        ),
        label="Timezone",
        help_text="Default timezone for displaying dates and times",
    )

    date_format = forms.ChoiceField(
        choices=DATE_FORMAT_CHOICES,
        widget=forms.Select(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
            }
        ),
        label="Date Format",
    )

    time_format = forms.ChoiceField(
        choices=TIME_FORMAT_CHOICES,
        widget=forms.Select(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
            }
        ),
        label="Time Format",
    )

    admin_url_slug = forms.CharField(
        max_length=100,
        required=False,
        widget=forms.TextInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "placeholder": "django-admin",
            }
        ),
        label="Django Admin URL",
        help_text="URL path for Django admin (e.g., 'django-admin' → /django-admin/). Requires app restart.",
    )

    def clean_admin_url_slug(self):
        """Validate admin URL slug format."""
        import re
        slug = self.cleaned_data.get("admin_url_slug", "django-admin").strip().lower()
        if not slug:
            slug = "django-admin"
        # Remove leading/trailing slashes
        slug = slug.strip("/")
        # Validate: alphanumeric, hyphens, underscores only
        if not re.match(r"^[a-z0-9_-]+$", slug):
            raise forms.ValidationError(
                "Admin URL can only contain lowercase letters, numbers, hyphens, and underscores."
            )
        # Prevent conflicts with existing routes
        reserved = ["setup", "auth", "cpanel", "webhook", "static", "media"]
        if slug in reserved:
            raise forms.ValidationError(
                f"'{slug}' is a reserved URL path. Please choose a different name."
            )
        return slug

    def __init__(self, *args, instance=None, **kwargs):
        """Initialize form with existing settings."""
        super().__init__(*args, **kwargs)
        if instance:
            self.fields["instance_name"].initial = instance.instance_name
            self.fields["timezone"].initial = instance.timezone
            self.fields["date_format"].initial = instance.date_format
            self.fields["time_format"].initial = instance.time_format
            self.fields["admin_url_slug"].initial = instance.admin_url_slug

    def save(self, instance):
        """Save the general settings to the GlobalSettings instance."""
        instance.instance_name = self.cleaned_data.get("instance_name") or "PyRunner"
        instance.timezone = self.cleaned_data.get("timezone") or "UTC"
        instance.date_format = self.cleaned_data.get("date_format")
        instance.time_format = self.cleaned_data.get("time_format")
        instance.admin_url_slug = self.cleaned_data.get("admin_url_slug") or "django-admin"
        instance.save(update_fields=[
            "instance_name", "timezone", "date_format", "time_format", "admin_url_slug", "updated_at"
        ])
        return instance


class LogRetentionForm(forms.Form):
    """Form for log retention settings."""

    retention_days = forms.IntegerField(
        min_value=0,
        initial=0,
        widget=forms.NumberInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "min": 0,
            }
        ),
        label="Retention Days",
        help_text="Delete runs older than this many days (0 = keep forever)",
    )

    retention_count = forms.IntegerField(
        min_value=0,
        initial=0,
        widget=forms.NumberInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "min": 0,
            }
        ),
        label="Retention Count",
        help_text="Keep only the last N runs per script (0 = unlimited)",
    )

    auto_cleanup_enabled = forms.BooleanField(
        required=False,
        initial=False,
        widget=forms.CheckboxInput(
            attrs={
                "class": "w-5 h-5 text-code-accent bg-code-bg border-code-border rounded focus:ring-code-accent focus:ring-2",
            }
        ),
        label="Auto Cleanup",
        help_text="Automatically clean up old runs daily at 2 AM",
    )

    def __init__(self, *args, instance=None, **kwargs):
        """Initialize form with existing settings."""
        super().__init__(*args, **kwargs)
        if instance:
            self.fields["retention_days"].initial = instance.retention_days
            self.fields["retention_count"].initial = instance.retention_count
            self.fields["auto_cleanup_enabled"].initial = instance.auto_cleanup_enabled

    def save(self, instance):
        """Save the retention settings to the GlobalSettings instance."""
        from core.services import RetentionService

        instance.retention_days = self.cleaned_data.get("retention_days") or 0
        instance.retention_count = self.cleaned_data.get("retention_count") or 0

        # Handle auto cleanup schedule
        new_auto_cleanup = self.cleaned_data.get("auto_cleanup_enabled", False)
        old_auto_cleanup = instance.auto_cleanup_enabled

        instance.auto_cleanup_enabled = new_auto_cleanup
        instance.save(update_fields=[
            "retention_days", "retention_count", "auto_cleanup_enabled", "updated_at"
        ])

        # Manage the django-q2 schedule
        if new_auto_cleanup and not old_auto_cleanup:
            RetentionService.enable_auto_cleanup()
        elif not new_auto_cleanup and old_auto_cleanup:
            RetentionService.disable_auto_cleanup()

        return instance


class WorkerSettingsForm(forms.Form):
    """Form for Django-Q2 worker configuration."""

    q_workers = forms.IntegerField(
        min_value=1,
        max_value=16,
        initial=2,
        widget=forms.NumberInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "min": 1,
                "max": 16,
            }
        ),
        label="Worker Count",
        help_text="Number of worker processes (1-16). More workers can process more tasks simultaneously.",
    )

    q_timeout = forms.IntegerField(
        min_value=0,
        max_value=86400,
        initial=600,
        widget=forms.NumberInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "min": 0,
                "max": 86400,
            }
        ),
        label="Task Timeout (seconds)",
        help_text="Maximum time a task can run before worker timeout. Use 0 for no timeout (required on Windows). For long-running scripts, also increase the script's own timeout.",
    )

    q_retry = forms.IntegerField(
        min_value=60,
        max_value=86400,
        initial=660,
        widget=forms.NumberInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "min": 60,
                "max": 86400,
            }
        ),
        label="Retry Delay (seconds)",
        help_text="Time before retrying a failed/timed-out task. Should be greater than timeout.",
    )

    q_queue_limit = forms.IntegerField(
        min_value=5,
        max_value=100,
        initial=20,
        widget=forms.NumberInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "min": 5,
                "max": 100,
            }
        ),
        label="Queue Limit",
        help_text="Maximum number of tasks that can be queued at once.",
    )

    def __init__(self, *args, instance=None, **kwargs):
        """Initialize form with existing settings."""
        super().__init__(*args, **kwargs)
        if instance:
            self.fields["q_workers"].initial = instance.q_workers
            self.fields["q_timeout"].initial = instance.q_timeout
            self.fields["q_retry"].initial = instance.q_retry
            self.fields["q_queue_limit"].initial = instance.q_queue_limit

    def clean(self):
        """Validate that retry > timeout."""
        cleaned_data = super().clean()
        timeout = cleaned_data.get("q_timeout", 0)
        retry = cleaned_data.get("q_retry", 660)

        if timeout > 0 and retry <= timeout:
            self.add_error(
                "q_retry",
                f"Retry delay ({retry}s) must be greater than timeout ({timeout}s).",
            )

        return cleaned_data

    def save(self, instance):
        """Save the worker settings to the GlobalSettings instance."""
        from django.utils import timezone

        # Check if any values actually changed
        changed = (
            instance.q_workers != self.cleaned_data["q_workers"]
            or instance.q_timeout != self.cleaned_data["q_timeout"]
            or instance.q_retry != self.cleaned_data["q_retry"]
            or instance.q_queue_limit != self.cleaned_data["q_queue_limit"]
        )

        instance.q_workers = self.cleaned_data["q_workers"]
        instance.q_timeout = self.cleaned_data["q_timeout"]
        instance.q_retry = self.cleaned_data["q_retry"]
        instance.q_queue_limit = self.cleaned_data["q_queue_limit"]

        if changed:
            instance.worker_settings_updated_at = timezone.now()

        instance.save(
            update_fields=[
                "q_workers",
                "q_timeout",
                "q_retry",
                "q_queue_limit",
                "worker_settings_updated_at",
                "updated_at",
            ]
        )
        return instance


class BackupCreateForm(forms.Form):
    """Form for configuring backup creation."""

    backup_format = forms.ChoiceField(
        choices=[
            ("gzip", "Compressed (recommended) - .json.gz"),
            ("json", "Plain JSON - .json"),
        ],
        initial="gzip",
        widget=forms.RadioSelect(
            attrs={
                "class": "w-4 h-4 text-code-accent bg-code-bg border-code-border focus:ring-code-accent",
            }
        ),
        label="Backup format",
        help_text="Compressed backups are 80-95% smaller",
    )

    include_datastores = forms.BooleanField(
        required=False,
        initial=True,
        widget=forms.CheckboxInput(
            attrs={
                "class": "w-5 h-5 text-code-accent bg-code-bg border-code-border rounded focus:ring-code-accent focus:ring-2",
            }
        ),
        label="Include DataStores",
        help_text="Include all DataStores and their key-value entries",
    )

    include_runs = forms.BooleanField(
        required=False,
        initial=True,
        widget=forms.CheckboxInput(
            attrs={
                "class": "w-5 h-5 text-code-accent bg-code-bg border-code-border rounded focus:ring-code-accent focus:ring-2",
            }
        ),
        label="Include run history",
        help_text="Include execution history (stdout/stderr)",
    )

    max_runs = forms.IntegerField(
        initial=1000,
        min_value=0,
        max_value=10000,
        widget=forms.NumberInput(
            attrs={
                "class": "w-full px-4 py-2 bg-code-bg text-code-text border border-code-border rounded-lg focus:ring-2 focus:ring-code-accent focus:border-transparent",
                "placeholder": "1000",
            }
        ),
        label="Maximum runs to include",
        help_text="Limit run history to most recent N runs (0 = all runs)",
    )

    include_package_operations = forms.BooleanField(
        required=False,
        initial=False,
        widget=forms.CheckboxInput(
            attrs={
                "class": "w-5 h-5 text-code-accent bg-code-bg border-code-border rounded focus:ring-code-accent focus:ring-2",
            }
        ),
        label="Include package operations",
        help_text="Include pip installation history",
    )


class BackupRestoreForm(forms.Form):
    """Form for restoring from backup."""

    backup_file = forms.FileField(
        widget=forms.FileInput(
            attrs={
                "class": "block w-full text-sm text-code-text file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-code-accent file:text-white hover:file:bg-opacity-90",
                "accept": ".json,.json.gz,.gz",
            }
        ),
        label="Backup file",
        help_text="JSON or compressed backup file (.json or .json.gz)",
    )

    restore_runs = forms.BooleanField(
        required=False,
        initial=True,
        widget=forms.CheckboxInput(
            attrs={
                "class": "w-5 h-5 text-code-accent bg-code-bg border-code-border rounded focus:ring-code-accent focus:ring-2",
            }
        ),
        label="Restore run history",
        help_text="Import execution history from backup",
    )

    confirm_delete = forms.BooleanField(
        required=True,
        widget=forms.CheckboxInput(
            attrs={
                "class": "w-5 h-5 text-red-500 bg-code-bg border-code-border rounded focus:ring-red-500 focus:ring-2",
            }
        ),
        label="I understand all existing data will be deleted",
        help_text="This action cannot be undone without the automatic backup",
    )


# =============================================================================
# Data Store Forms
# =============================================================================


class DataStoreForm(forms.ModelForm):
    """Form for creating and editing data stores."""

    class Meta:
        model = DataStore
        fields = ["name", "description"]
        widgets = {
            "name": forms.TextInput(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                    "placeholder": "my_data_store",
                }
            ),
            "description": forms.Textarea(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                    "rows": 2,
                    "placeholder": "What is this data store used for?",
                }
            ),
        }
        labels = {
            "name": "Store Name",
            "description": "Description",
        }
        help_texts = {
            "name": "Used in scripts as: DataStore(\"name\")",
        }

    def clean_name(self):
        name = self.cleaned_data.get("name", "").strip()
        if not name:
            raise forms.ValidationError("Store name is required.")
        # Check for valid identifier-like name
        if not name.replace("_", "").replace("-", "").isalnum():
            raise forms.ValidationError(
                "Name can only contain letters, numbers, underscores, and hyphens."
            )
        # Check uniqueness (excluding current instance for edits)
        qs = DataStore.objects.filter(name__iexact=name)
        if self.instance.pk:
            qs = qs.exclude(pk=self.instance.pk)
        if qs.exists():
            raise forms.ValidationError("A data store with this name already exists.")
        return name


class DataStoreEntryForm(forms.Form):
    """Form for creating and editing data store entries."""

    key = forms.CharField(
        max_length=255,
        widget=forms.TextInput(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text font-mono placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "placeholder": "my_key",
            }
        ),
        label="Key",
        help_text="Unique identifier for this entry",
    )

    value = forms.CharField(
        widget=forms.Textarea(
            attrs={
                "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text font-mono text-sm placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                "rows": 6,
                "placeholder": '{"example": "value"}\nor just a string\nor a number like 42',
            }
        ),
        label="Value (JSON)",
        help_text="JSON value: string, number, boolean, array, or object",
    )

    def __init__(self, *args, datastore=None, instance=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.datastore = datastore
        self.instance = instance

        # Pre-populate for editing
        if instance:
            self.fields["key"].initial = instance.key
            self.fields["value"].initial = instance.value_json

    def clean_key(self):
        key = self.cleaned_data.get("key", "").strip()
        if not key:
            raise forms.ValidationError("Key is required.")
        if len(key) > 255:
            raise forms.ValidationError("Key cannot exceed 255 characters.")

        # Check uniqueness within the data store
        if self.datastore:
            qs = DataStoreEntry.objects.filter(datastore=self.datastore, key=key)
            if self.instance:
                qs = qs.exclude(pk=self.instance.pk)
            if qs.exists():
                raise forms.ValidationError(
                    f"Key '{key}' already exists in this data store."
                )
        return key

    def clean_value(self):
        import json

        value = self.cleaned_data.get("value", "").strip()
        if not value:
            raise forms.ValidationError("Value is required.")

        try:
            # Validate it's valid JSON
            json.loads(value)
        except json.JSONDecodeError as e:
            raise forms.ValidationError(f"Invalid JSON: {e}")

        return value


# =============================================================================
# API Token Forms
# =============================================================================


class DataStoreAPITokenForm(forms.ModelForm):
    """Form for creating API tokens."""

    class Meta:
        model = DataStoreAPIToken
        fields = ["name", "datastore", "expires_at"]
        widgets = {
            "name": forms.TextInput(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                    "placeholder": "My Dashboard Token",
                }
            ),
            "datastore": forms.Select(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                }
            ),
            "expires_at": forms.DateTimeInput(
                attrs={
                    "class": "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent",
                    "type": "datetime-local",
                },
                format="%Y-%m-%dT%H:%M",
            ),
        }
        labels = {
            "name": "Token Name",
            "datastore": "Scope",
            "expires_at": "Expires At",
        }
        help_texts = {
            "name": "A friendly name to identify this token",
            "datastore": "Leave empty for access to all datastores, or select a specific datastore",
            "expires_at": "Optional. Leave empty for no expiration.",
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Make datastore optional with a clear empty choice
        self.fields["datastore"].required = False
        self.fields["datastore"].empty_label = "All Datastores (Global Access)"
        self.fields["expires_at"].required = False


# =============================================================================
# Authentication Forms
# =============================================================================

INPUT_CLASS = "w-full px-4 py-3 bg-code-bg border border-code-border rounded-lg text-code-text placeholder-code-muted/50 focus:outline-none focus:ring-2 focus:ring-code-accent/50 focus:border-code-accent"


class PasswordLoginForm(forms.Form):
    """Form for password-based login."""

    email = forms.EmailField(
        widget=forms.EmailInput(
            attrs={
                "class": INPUT_CLASS,
                "placeholder": "you@example.com",
                "autocomplete": "email",
            }
        ),
        label="Email address",
    )
    password = forms.CharField(
        widget=forms.PasswordInput(
            attrs={
                "class": INPUT_CLASS,
                "placeholder": "Your password",
                "autocomplete": "current-password",
            }
        ),
        label="Password",
    )


class SetPasswordForm(forms.Form):
    """Form for setting or changing password."""

    password = forms.CharField(
        min_length=8,
        widget=forms.PasswordInput(
            attrs={
                "class": INPUT_CLASS,
                "placeholder": "New password",
                "autocomplete": "new-password",
            }
        ),
        label="New Password",
        help_text="Minimum 8 characters",
    )
    password_confirm = forms.CharField(
        widget=forms.PasswordInput(
            attrs={
                "class": INPUT_CLASS,
                "placeholder": "Confirm new password",
                "autocomplete": "new-password",
            }
        ),
        label="Confirm Password",
    )

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get("password")
        confirm = cleaned_data.get("password_confirm")
        if password and confirm and password != confirm:
            raise forms.ValidationError("Passwords do not match.")
        return cleaned_data


class AdminSetupForm(forms.Form):
    """Form for initial admin setup with password."""

    email = forms.EmailField(
        widget=forms.EmailInput(
            attrs={
                "class": INPUT_CLASS,
                "placeholder": "admin@example.com",
                "autocomplete": "email",
            }
        ),
        label="Admin Email",
    )
    password = forms.CharField(
        min_length=8,
        widget=forms.PasswordInput(
            attrs={
                "class": INPUT_CLASS,
                "placeholder": "Create a strong password",
                "autocomplete": "new-password",
            }
        ),
        label="Password",
        help_text="Minimum 8 characters",
    )
    password_confirm = forms.CharField(
        widget=forms.PasswordInput(
            attrs={
                "class": INPUT_CLASS,
                "placeholder": "Confirm password",
                "autocomplete": "new-password",
            }
        ),
        label="Confirm Password",
    )

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get("password")
        confirm = cleaned_data.get("password_confirm")
        if password and confirm and password != confirm:
            raise forms.ValidationError("Passwords do not match.")
        return cleaned_data


# =============================================================================
# Services Forms
# =============================================================================


class S3SettingsForm(forms.Form):
    """Form for S3 storage configuration."""

    s3_enabled = forms.BooleanField(
        required=False,
        initial=False,
        widget=forms.CheckboxInput(
            attrs={
                "class": "w-5 h-5 text-code-accent bg-code-bg border-code-border rounded focus:ring-code-accent focus:ring-2",
            }
        ),
        label="Enable S3 Storage",
    )

    s3_endpoint_url = forms.CharField(
        required=False,
        max_length=500,
        widget=forms.TextInput(
            attrs={
                "class": INPUT_CLASS,
                "placeholder": "https://s3.amazonaws.com or https://minio.example.com:9000",
            }
        ),
        label="Endpoint URL",
        help_text="Leave empty for AWS S3. Required for MinIO, DigitalOcean Spaces, etc.",
    )

    s3_region = forms.CharField(
        required=False,
        max_length=50,
        initial="us-east-1",
        widget=forms.TextInput(
            attrs={
                "class": INPUT_CLASS,
                "placeholder": "us-east-1",
            }
        ),
        label="Region",
    )

    s3_bucket_name = forms.CharField(
        required=False,
        max_length=255,
        widget=forms.TextInput(
            attrs={
                "class": INPUT_CLASS,
                "placeholder": "my-backup-bucket",
            }
        ),
        label="Bucket Name",
    )

    s3_access_key = forms.CharField(
        required=False,
        widget=forms.PasswordInput(
            attrs={
                "class": INPUT_CLASS,
                "placeholder": "Leave blank to keep current",
                "autocomplete": "new-password",
            }
        ),
        label="Access Key",
    )

    s3_secret_key = forms.CharField(
        required=False,
        widget=forms.PasswordInput(
            attrs={
                "class": INPUT_CLASS,
                "placeholder": "Leave blank to keep current",
                "autocomplete": "new-password",
            }
        ),
        label="Secret Key",
    )

    s3_use_ssl = forms.BooleanField(
        required=False,
        initial=True,
        widget=forms.CheckboxInput(
            attrs={
                "class": "w-5 h-5 text-code-accent bg-code-bg border-code-border rounded focus:ring-code-accent focus:ring-2",
            }
        ),
        label="Use SSL/TLS",
        help_text="Recommended for security. Disable only for local development.",
    )

    s3_path_style = forms.BooleanField(
        required=False,
        initial=False,
        widget=forms.CheckboxInput(
            attrs={
                "class": "w-5 h-5 text-code-accent bg-code-bg border-code-border rounded focus:ring-code-accent focus:ring-2",
            }
        ),
        label="Path-style addressing",
        help_text="Required for MinIO and some S3-compatible providers.",
    )

    def __init__(self, *args, instance=None, **kwargs):
        """Initialize form with existing settings."""
        super().__init__(*args, **kwargs)
        if instance:
            self.fields["s3_enabled"].initial = instance.s3_enabled
            self.fields["s3_endpoint_url"].initial = instance.s3_endpoint_url
            self.fields["s3_region"].initial = instance.s3_region or "us-east-1"
            self.fields["s3_bucket_name"].initial = instance.s3_bucket_name
            self.fields["s3_use_ssl"].initial = instance.s3_use_ssl
            self.fields["s3_path_style"].initial = instance.s3_path_style

    def save(self, instance):
        """Save the S3 settings to the GlobalSettings instance."""
        from core.services.encryption_service import EncryptionService

        instance.s3_enabled = self.cleaned_data.get("s3_enabled", False)
        instance.s3_endpoint_url = self.cleaned_data.get("s3_endpoint_url") or ""
        instance.s3_region = self.cleaned_data.get("s3_region") or "us-east-1"
        instance.s3_bucket_name = self.cleaned_data.get("s3_bucket_name") or ""
        instance.s3_use_ssl = self.cleaned_data.get("s3_use_ssl", True)
        instance.s3_path_style = self.cleaned_data.get("s3_path_style", False)

        # Encrypt and save access key if provided
        access_key = self.cleaned_data.get("s3_access_key")
        if access_key:
            instance.s3_access_key_encrypted = EncryptionService.encrypt(access_key)

        # Encrypt and save secret key if provided
        secret_key = self.cleaned_data.get("s3_secret_key")
        if secret_key:
            instance.s3_secret_key_encrypted = EncryptionService.encrypt(secret_key)

        instance.save()
        return instance


class S3BackupScheduleForm(forms.Form):
    """Form for S3 scheduled backup configuration."""

    from core.models import GlobalSettings

    WEEKDAY_CHOICES = [
        (0, "Monday"),
        (1, "Tuesday"),
        (2, "Wednesday"),
        (3, "Thursday"),
        (4, "Friday"),
        (5, "Saturday"),
        (6, "Sunday"),
    ]

    s3_backup_enabled = forms.BooleanField(
        required=False,
        initial=False,
        widget=forms.CheckboxInput(
            attrs={
                "class": "w-5 h-5 text-code-accent bg-code-bg border-code-border rounded focus:ring-code-accent focus:ring-2",
            }
        ),
        label="Enable Scheduled Backups",
    )

    s3_backup_schedule = forms.ChoiceField(
        choices=GlobalSettings.S3BackupSchedule.choices,
        initial=GlobalSettings.S3BackupSchedule.DISABLED,
        widget=forms.Select(
            attrs={
                "class": INPUT_CLASS,
            }
        ),
        label="Schedule Frequency",
    )

    s3_backup_time = forms.TimeField(
        initial="02:00",
        widget=forms.TimeInput(
            attrs={
                "class": INPUT_CLASS,
                "type": "time",
            }
        ),
        label="Backup Time",
        help_text="Time to run backups (in instance timezone)",
    )

    s3_backup_day = forms.ChoiceField(
        choices=WEEKDAY_CHOICES,
        initial=0,
        widget=forms.Select(
            attrs={
                "class": INPUT_CLASS,
            }
        ),
        label="Day of Week",
        help_text="For weekly backups",
    )

    s3_backup_prefix = forms.CharField(
        required=False,
        max_length=255,
        initial="pyrunner-backups/",
        widget=forms.TextInput(
            attrs={
                "class": INPUT_CLASS,
                "placeholder": "pyrunner-backups/",
            }
        ),
        label="S3 Path Prefix",
        help_text="Path prefix for backup files in the bucket",
    )

    s3_backup_retention_count = forms.IntegerField(
        min_value=0,
        initial=7,
        widget=forms.NumberInput(
            attrs={
                "class": INPUT_CLASS,
                "min": "0",
            }
        ),
        label="Retention Count",
        help_text="Keep the last N backups (0 = keep all)",
    )

    s3_backup_include_runs = forms.BooleanField(
        required=False,
        initial=False,
        widget=forms.CheckboxInput(
            attrs={
                "class": "w-5 h-5 text-code-accent bg-code-bg border-code-border rounded focus:ring-code-accent focus:ring-2",
            }
        ),
        label="Include Run History",
    )

    s3_backup_max_runs = forms.IntegerField(
        min_value=0,
        initial=1000,
        widget=forms.NumberInput(
            attrs={
                "class": INPUT_CLASS,
                "min": "0",
            }
        ),
        label="Max Runs",
        help_text="Maximum runs to include (0 = all)",
    )

    s3_backup_include_datastores = forms.BooleanField(
        required=False,
        initial=True,
        widget=forms.CheckboxInput(
            attrs={
                "class": "w-5 h-5 text-code-accent bg-code-bg border-code-border rounded focus:ring-code-accent focus:ring-2",
            }
        ),
        label="Include DataStores",
    )

    def __init__(self, *args, instance=None, **kwargs):
        """Initialize form with existing settings."""
        super().__init__(*args, **kwargs)
        if instance:
            self.fields["s3_backup_enabled"].initial = instance.s3_backup_enabled
            self.fields["s3_backup_schedule"].initial = instance.s3_backup_schedule
            self.fields["s3_backup_time"].initial = instance.s3_backup_time
            self.fields["s3_backup_day"].initial = instance.s3_backup_day
            self.fields["s3_backup_prefix"].initial = instance.s3_backup_prefix or "pyrunner-backups/"
            self.fields["s3_backup_retention_count"].initial = instance.s3_backup_retention_count
            self.fields["s3_backup_include_runs"].initial = instance.s3_backup_include_runs
            self.fields["s3_backup_max_runs"].initial = instance.s3_backup_max_runs
            self.fields["s3_backup_include_datastores"].initial = instance.s3_backup_include_datastores

    def save(self, instance):
        """Save the backup schedule settings."""
        from core.services.backup_schedule_service import BackupScheduleService

        instance.s3_backup_enabled = self.cleaned_data.get("s3_backup_enabled", False)
        instance.s3_backup_schedule = self.cleaned_data.get("s3_backup_schedule")
        instance.s3_backup_time = self.cleaned_data.get("s3_backup_time")
        instance.s3_backup_day = int(self.cleaned_data.get("s3_backup_day", 0))
        instance.s3_backup_prefix = self.cleaned_data.get("s3_backup_prefix") or "pyrunner-backups/"
        instance.s3_backup_retention_count = self.cleaned_data.get("s3_backup_retention_count", 7)
        instance.s3_backup_include_runs = self.cleaned_data.get("s3_backup_include_runs", False)
        instance.s3_backup_max_runs = self.cleaned_data.get("s3_backup_max_runs", 1000)
        instance.s3_backup_include_datastores = self.cleaned_data.get("s3_backup_include_datastores", True)

        instance.save()

        # Sync the django-q2 schedule
        BackupScheduleService.sync_schedule()

        return instance