wrkflw 0.2.1

A GitHub Actions workflow validator and executor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
use crate::evaluator::evaluate_workflow_file;
use crate::executor::{self, ExecutionResult, JobStatus, RuntimeType, StepStatus};
use crate::logging;
use crate::utils::is_workflow_file;
use chrono::Local;
use crossterm::{
    event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::widgets::TableState;
use ratatui::{
    backend::CrosstermBackend,
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{
        Block, BorderType, Borders, Cell, Gauge, List, ListItem, ListState, Paragraph, Row, Table,
        Tabs, Wrap,
    },
    Frame, Terminal,
};
use std::io::{self, stdout};
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use std::thread;
use std::time::{Duration, Instant};

// Represents an individual workflow file
struct Workflow {
    name: String,
    path: PathBuf,
    selected: bool,
    status: WorkflowStatus,
    execution_details: Option<WorkflowExecution>,
}

// Status of a workflow
#[derive(Debug, Clone, PartialEq)]
enum WorkflowStatus {
    NotStarted,
    Running,
    Success,
    Failed,
    Skipped,
}

// Detailed execution information
#[allow(dead_code)]
struct WorkflowExecution {
    jobs: Vec<JobExecution>,
    start_time: chrono::DateTime<Local>,
    end_time: Option<chrono::DateTime<Local>>,
    logs: Vec<String>,
    progress: f64, // 0.0 - 1.0 for progress bar
}

// Job execution details
#[allow(dead_code)]
struct JobExecution {
    name: String,
    status: JobStatus,
    steps: Vec<StepExecution>,
    logs: Vec<String>,
}

// Step execution details
struct StepExecution {
    name: String,
    status: StepStatus,
    output: String,
}

// Application state
struct App {
    workflows: Vec<Workflow>,
    workflow_list_state: ListState,
    selected_tab: usize,
    running: bool,
    show_help: bool,
    runtime_type: RuntimeType,
    validation_mode: bool,
    execution_queue: Vec<usize>, // Indices of workflows to execute
    current_execution: Option<usize>,
    logs: Vec<String>,            // Overall execution logs
    log_scroll: usize,            // Scrolling position for logs
    job_list_state: ListState,    // For viewing job details
    detailed_view: bool,          // Whether we're in detailed view mode
    step_list_state: ListState,   // For selecting steps in detailed view
    step_table_state: TableState, // For the steps table in detailed view
    last_tick: Instant,           // For UI animations and updates
    tick_rate: Duration,          // How often to update the UI
}

impl App {
    fn new(runtime_type: RuntimeType) -> App {
        let mut workflow_list_state = ListState::default();
        workflow_list_state.select(Some(0));

        let mut job_list_state = ListState::default();
        job_list_state.select(Some(0));

        let mut step_list_state = ListState::default();
        step_list_state.select(Some(0));

        let mut step_table_state = TableState::default();
        step_table_state.select(Some(0));

        App {
            workflows: Vec::new(),
            workflow_list_state,
            selected_tab: 0,
            running: false,
            show_help: false,
            runtime_type,
            validation_mode: false,
            execution_queue: Vec::new(),
            current_execution: None,
            logs: Vec::new(),
            log_scroll: 0,
            job_list_state,
            detailed_view: false,
            step_list_state,
            step_table_state,
            last_tick: Instant::now(),
            tick_rate: Duration::from_millis(250), // Update 4 times per second
        }
    }

    // Toggle workflow selection
    fn toggle_selected(&mut self) {
        if let Some(idx) = self.workflow_list_state.selected() {
            if idx < self.workflows.len() {
                self.workflows[idx].selected = !self.workflows[idx].selected;
            }
        }
    }

    fn toggle_emulation_mode(&mut self) {
        self.runtime_type = match self.runtime_type {
            RuntimeType::Docker => RuntimeType::Emulation,
            RuntimeType::Emulation => RuntimeType::Docker,
        };
        self.logs
            .push(format!("Switched to {} mode", self.runtime_type_name()));
    }

    fn toggle_validation_mode(&mut self) {
        self.validation_mode = !self.validation_mode;
        let mode = if self.validation_mode {
            "validation"
        } else {
            "execution"
        };
        self.logs.push(format!("Switched to {} mode", mode));
    }

    fn runtime_type_name(&self) -> &str {
        match self.runtime_type {
            RuntimeType::Docker => "Docker",
            RuntimeType::Emulation => "Emulation",
        }
    }

    // Move cursor up in the workflow list
    fn previous_workflow(&mut self) {
        if self.workflows.is_empty() {
            return;
        }

        let i = match self.workflow_list_state.selected() {
            Some(i) => {
                if i == 0 {
                    self.workflows.len() - 1
                } else {
                    i - 1
                }
            }
            None => 0,
        };
        self.workflow_list_state.select(Some(i));
    }

    // Move cursor down in the workflow list
    fn next_workflow(&mut self) {
        if self.workflows.is_empty() {
            return;
        }

        let i = match self.workflow_list_state.selected() {
            Some(i) => {
                if i >= self.workflows.len() - 1 {
                    0
                } else {
                    i + 1
                }
            }
            None => 0,
        };
        self.workflow_list_state.select(Some(i));
    }

    // Move cursor up in the job list
    fn previous_job(&mut self) {
        let current_workflow_idx = self
            .current_execution
            .or_else(|| self.workflow_list_state.selected());

        if let Some(workflow_idx) = current_workflow_idx {
            if workflow_idx >= self.workflows.len() {
                return;
            }

            if let Some(execution) = &self.workflows[workflow_idx].execution_details {
                if execution.jobs.is_empty() {
                    return;
                }

                let i = match self.job_list_state.selected() {
                    Some(i) => {
                        if i == 0 {
                            execution.jobs.len() - 1
                        } else {
                            i - 1
                        }
                    }
                    None => 0,
                };
                self.job_list_state.select(Some(i));

                // Reset step selection when changing jobs
                self.step_list_state.select(Some(0));
            }
        }
    }

    // Move cursor down in the job list
    fn next_job(&mut self) {
        let current_workflow_idx = self
            .current_execution
            .or_else(|| self.workflow_list_state.selected());

        if let Some(workflow_idx) = current_workflow_idx {
            if workflow_idx >= self.workflows.len() {
                return;
            }

            if let Some(execution) = &self.workflows[workflow_idx].execution_details {
                if execution.jobs.is_empty() {
                    return;
                }

                let i = match self.job_list_state.selected() {
                    Some(i) => {
                        if i >= execution.jobs.len() - 1 {
                            0
                        } else {
                            i + 1
                        }
                    }
                    None => 0,
                };
                self.job_list_state.select(Some(i));

                // Reset step selection when changing jobs
                self.step_list_state.select(Some(0));
            }
        }
    }

    // Move cursor up in step list
    fn previous_step(&mut self) {
        let current_workflow_idx = self
            .current_execution
            .or_else(|| self.workflow_list_state.selected());

        if let Some(workflow_idx) = current_workflow_idx {
            if let Some(execution) = &self.workflows[workflow_idx].execution_details {
                if let Some(job_idx) = self.job_list_state.selected() {
                    if job_idx < execution.jobs.len() {
                        let steps = &execution.jobs[job_idx].steps;
                        if steps.is_empty() {
                            return;
                        }

                        let i = match self.step_list_state.selected() {
                            Some(i) => {
                                if i == 0 {
                                    steps.len() - 1
                                } else {
                                    i - 1
                                }
                            }
                            None => 0,
                        };
                        self.step_list_state.select(Some(i));
                    }
                }
            }
        }
        if let Some(i) = self.step_list_state.selected() {
            self.step_table_state.select(Some(i));
        }
    }

    // Move cursor down in step list
    fn next_step(&mut self) {
        let current_workflow_idx = self
            .current_execution
            .or_else(|| self.workflow_list_state.selected());

        if let Some(workflow_idx) = current_workflow_idx {
            if let Some(execution) = &self.workflows[workflow_idx].execution_details {
                if let Some(job_idx) = self.job_list_state.selected() {
                    if job_idx < execution.jobs.len() {
                        let steps = &execution.jobs[job_idx].steps;
                        if steps.is_empty() {
                            return;
                        }

                        let i = match self.step_list_state.selected() {
                            Some(i) => {
                                if i >= steps.len() - 1 {
                                    0
                                } else {
                                    i + 1
                                }
                            }
                            None => 0,
                        };
                        self.step_list_state.select(Some(i));
                    }
                }
            }
        }
        if let Some(i) = self.step_list_state.selected() {
            self.step_table_state.select(Some(i));
        }
    }

    // Change the tab
    fn switch_tab(&mut self, tab: usize) {
        self.selected_tab = tab;
    }

    // Queue selected workflows for execution
    fn queue_selected_for_execution(&mut self) {
        self.execution_queue.clear();
        for (i, workflow) in self.workflows.iter().enumerate() {
            if workflow.selected {
                self.execution_queue.push(i);
            }
        }
        self.logs.push(format!(
            "Queued {} workflow(s) for execution",
            self.execution_queue.len()
        ));
        logging::info(&format!(
            "Queued {} workflow(s) for execution",
            self.execution_queue.len()
        ));
    }

    // Start workflow execution process
    fn start_execution(&mut self) {
        if self.execution_queue.is_empty() {
            self.logs
                .push("No workflows selected for execution".to_string());
            logging::warning("No workflows selected for execution");
            return;
        }

        self.running = true;
        self.logs.push("Starting workflow execution...".to_string());
        logging::info("Starting workflow execution...");

        if self.validation_mode {
            self.logs
                .push("Starting workflow validation...".to_string());
            logging::info("Starting workflow validation...");
        } else {
            self.logs.push("Starting workflow execution...".to_string());
            logging::info("Starting workflow execution...");
        }

        // Update all queued workflows to "Queued" state
        for &idx in &self.execution_queue {
            self.workflows[idx].status = WorkflowStatus::Skipped;
        }
    }

    // Process execution results and update UI
    fn process_execution_result(&mut self, workflow_idx: usize, result: ExecutionResult) {
        let workflow = &mut self.workflows[workflow_idx];

        // Convert execution results to our internal format
        let mut job_executions = Vec::new();
        for job in result.jobs {
            let mut step_executions = Vec::new();
            for step in job.steps {
                step_executions.push(StepExecution {
                    name: step.name,
                    status: step.status,
                    output: step.output,
                });
            }

            job_executions.push(JobExecution {
                name: job.name,
                status: job.status,
                steps: step_executions,
                logs: vec![job.logs],
            });
        }

        let end_time = Local::now();

        // Determine overall workflow status
        if job_executions
            .iter()
            .any(|j| j.status == JobStatus::Failure)
        {
            workflow.status = WorkflowStatus::Failed;
            logging::error(&format!("Workflow '{}' failed", workflow.name));
        } else {
            workflow.status = WorkflowStatus::Success;
            logging::success(&format!(
                "Workflow '{}' completed successfully",
                workflow.name
            ));
        }

        // Update workflow execution details
        if let Some(exec) = &mut workflow.execution_details {
            exec.jobs = job_executions;
            exec.end_time = Some(end_time);
            exec.progress = 1.0; // Completed
        } else {
            workflow.execution_details = Some(WorkflowExecution {
                jobs: job_executions,
                start_time: end_time - chrono::Duration::seconds(1), // Approximate
                end_time: Some(end_time),
                logs: vec!["Execution completed".to_string()],
                progress: 1.0, // Completed
            });
        }

        // Add workflow completion to logs
        self.logs.push(format!(
            "Workflow '{}' execution completed with status: {:?}",
            workflow.name, workflow.status
        ));
    }

    // Get next workflow for execution
    fn get_next_workflow_to_execute(&mut self) -> Option<usize> {
        if self.execution_queue.is_empty() {
            return None;
        }

        let next = self.execution_queue.remove(0);
        self.workflows[next].status = WorkflowStatus::Running;
        self.current_execution = Some(next);
        self.logs
            .push(format!("Executing workflow: {}", self.workflows[next].name));
        logging::info(&format!(
            "Executing workflow: {}",
            self.workflows[next].name
        ));

        // Initialize execution details
        self.workflows[next].execution_details = Some(WorkflowExecution {
            jobs: Vec::new(),
            start_time: Local::now(),
            end_time: None,
            logs: vec!["Execution started".to_string()],
            progress: 0.0, // Just started
        });

        Some(next)
    }

    // Toggle detailed view mode
    fn toggle_detailed_view(&mut self) {
        self.detailed_view = !self.detailed_view;
    }

    // Scroll logs up
    fn scroll_logs_up(&mut self) {
        self.log_scroll = self.log_scroll.saturating_sub(1);
    }

    // Scroll logs down
    fn scroll_logs_down(&mut self) {
        if !self.logs.is_empty() {
            self.log_scroll = (self.log_scroll + 1).min(self.logs.len() - 1);
        }
    }

    // Update progress for running workflows
    fn update_running_workflow_progress(&mut self) {
        if let Some(idx) = self.current_execution {
            if let Some(execution) = &mut self.workflows[idx].execution_details {
                if execution.end_time.is_none() {
                    // Gradually increase progress for visual feedback
                    execution.progress = (execution.progress + 0.01).min(0.95);
                }
            }
        }
    }

    // Check if tick should happen
    fn tick(&mut self) -> bool {
        let now = Instant::now();
        if now.duration_since(self.last_tick) >= self.tick_rate {
            self.last_tick = now;
            true
        } else {
            false
        }
    }
}

// Find and load all workflow files in a directory
fn load_workflows(dir_path: &Path) -> Vec<Workflow> {
    let mut workflows = Vec::new();

    // Default path is .github/workflows
    let default_workflows_dir = Path::new(".github").join("workflows");
    let is_default_dir = dir_path == &default_workflows_dir || dir_path.ends_with("workflows");

    if let Ok(entries) = std::fs::read_dir(dir_path) {
        for entry in entries {
            if let Ok(entry) = entry {
                let path = entry.path();
                if path.is_file() && (is_workflow_file(&path) || !is_default_dir) {
                    let name = path
                        .file_name()
                        .unwrap_or_default()
                        .to_string_lossy()
                        .into_owned();

                    workflows.push(Workflow {
                        name,
                        path,
                        selected: false,
                        status: WorkflowStatus::NotStarted,
                        execution_details: None,
                    });
                }
            }
        }
    }

    // Sort workflows by name
    workflows.sort_by(|a, b| a.name.cmp(&b.name));
    workflows
}

// Main UI function to run the TUI application
pub fn run_tui(
    workflow_path: Option<&PathBuf>,
    runtime_type: &RuntimeType,
    verbose: bool,
) -> io::Result<()> {
    // Terminal setup
    enable_raw_mode()?;
    let mut stdout = stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    // Set up channel for async communication
    let (tx, rx) = mpsc::channel();

    // Initialize app state
    let mut app = App::new(runtime_type.clone());

    if app.validation_mode {
        app.logs.push("Starting in validation mode".to_string());
        logging::info("Starting in validation mode");
    }

    // Load workflows
    let dir_path = match workflow_path {
        Some(path) if path.is_dir() => path.clone(),
        Some(path) if path.is_file() => {
            // Single workflow file
            let name = path
                .file_name()
                .unwrap_or_default()
                .to_string_lossy()
                .into_owned();

            app.workflows = vec![Workflow {
                name: name.clone(),
                path: path.clone(),
                selected: true,
                status: WorkflowStatus::NotStarted,
                execution_details: None,
            }];

            // Queue the single workflow for execution
            app.execution_queue = vec![0];
            app.start_execution();

            // Return parent dir or current dir if no parent
            path.parent()
                .map(|p| p.to_path_buf())
                .unwrap_or_else(|| PathBuf::from("."))
        }
        _ => PathBuf::from(".github/workflows"),
    };

    // Only load directory if we haven't already loaded a single file
    if app.workflows.is_empty() {
        app.workflows = load_workflows(&dir_path);
    }

    // Main event loop
    let result = loop {
        // Update UI on tick
        if app.tick() {
            app.update_running_workflow_progress();
        }

        // Draw UI
        terminal.draw(|f| {
            render_ui(f, &mut app);
        })?;

        // Handle incoming execution results
        if let Ok((workflow_idx, result)) = rx.try_recv() {
            app.process_execution_result(workflow_idx, result);
            app.current_execution = None;

            // Get next workflow to execute
            if let Some(next_idx) = app.get_next_workflow_to_execute() {
                let tx_clone = tx.clone();
                let workflow_path = app.workflows[next_idx].path.clone();
                let runtime_type = app.runtime_type.clone();

                thread::spawn(move || {
                    let runtime = tokio::runtime::Runtime::new().unwrap();
                    let result = runtime.block_on(async {
                        if app.validation_mode {
                            // Perform validation instead of execution
                            match evaluate_workflow_file(&workflow_path, verbose) {
                                Ok(validation_result) => {
                                    // Create execution result based on validation
                                    let status = if validation_result.is_valid {
                                        JobStatus::Success
                                    } else {
                                        JobStatus::Failure
                                    };

                                    let steps = vec![executor::StepResult {
                                        name: "Validation".to_string(),
                                        status: if validation_result.is_valid {
                                            StepStatus::Success
                                        } else {
                                            StepStatus::Failure
                                        },
                                        output: if validation_result.is_valid {
                                            "Workflow is valid".to_string()
                                        } else {
                                            format!(
                                                "Validation issues:\n{}",
                                                validation_result.issues.join("\n")
                                            )
                                        },
                                    }];

                                    ExecutionResult {
                                        jobs: vec![executor::JobResult {
                                            name: "Validation".to_string(),
                                            status,
                                            steps,
                                            logs: if validation_result.is_valid {
                                                "Workflow validation succeeded".to_string()
                                            } else {
                                                format!(
                                                    "Workflow validation failed:\n{}",
                                                    validation_result.issues.join("\n")
                                                )
                                            },
                                        }],
                                    }
                                }
                                Err(e) => {
                                    // Error during validation
                                    let failed_job = executor::JobResult {
                                        name: "Validation Error".to_string(),
                                        status: JobStatus::Failure,
                                        steps: vec![executor::StepResult {
                                            name: "Validation Error".to_string(),
                                            status: StepStatus::Failure,
                                            output: format!("Error: {}", e),
                                        }],
                                        logs: format!("Error validating workflow: {}", e),
                                    };

                                    ExecutionResult {
                                        jobs: vec![failed_job],
                                    }
                                }
                            }
                        } else {
                            match executor::execute_workflow(&workflow_path, runtime_type, verbose)
                                .await
                            {
                                Ok(result) => result,
                                Err(e) => {
                                    // Create a failed execution result with error message
                                    let failed_job = executor::JobResult {
                                        name: "Error".to_string(),
                                        status: JobStatus::Failure,
                                        steps: vec![executor::StepResult {
                                            name: "Execution Error".to_string(),
                                            status: StepStatus::Failure,
                                            output: format!("Error: {}", e),
                                        }],
                                        logs: format!("Error executing workflow: {}", e),
                                    };

                                    ExecutionResult {
                                        jobs: vec![failed_job],
                                    }
                                }
                            }
                        }
                    });

                    tx_clone.send((next_idx, result)).unwrap();
                });
            } else {
                app.running = false;
                app.logs
                    .push("All workflows completed execution".to_string());
                logging::info("All workflows completed execution");
            }
        }

        // Start execution if we have a queued workflow and nothing is currently running
        if app.running && app.current_execution.is_none() && !app.execution_queue.is_empty() {
            if let Some(next_idx) = app.get_next_workflow_to_execute() {
                let tx_clone = tx.clone();
                let workflow_path = app.workflows[next_idx].path.clone();
                let runtime_type = app.runtime_type.clone();

                thread::spawn(move || {
                    let runtime = tokio::runtime::Runtime::new().unwrap();
                    let result = runtime.block_on(async {
                        if app.validation_mode {
                            // Perform validation instead of execution
                            match evaluate_workflow_file(&workflow_path, verbose) {
                                Ok(validation_result) => {
                                    // Create execution result based on validation
                                    let status = if validation_result.is_valid {
                                        JobStatus::Success
                                    } else {
                                        JobStatus::Failure
                                    };

                                    let steps = vec![executor::StepResult {
                                        name: "Validation".to_string(),
                                        status: if validation_result.is_valid {
                                            StepStatus::Success
                                        } else {
                                            StepStatus::Failure
                                        },
                                        output: if validation_result.is_valid {
                                            "Workflow is valid".to_string()
                                        } else {
                                            format!(
                                                "Validation issues:\n{}",
                                                validation_result.issues.join("\n")
                                            )
                                        },
                                    }];

                                    ExecutionResult {
                                        jobs: vec![executor::JobResult {
                                            name: "Validation".to_string(),
                                            status,
                                            steps,
                                            logs: if validation_result.is_valid {
                                                "Workflow validation succeeded".to_string()
                                            } else {
                                                format!(
                                                    "Workflow validation failed:\n{}",
                                                    validation_result.issues.join("\n")
                                                )
                                            },
                                        }],
                                    }
                                }
                                Err(e) => {
                                    // Error during validation
                                    let failed_job = executor::JobResult {
                                        name: "Validation Error".to_string(),
                                        status: JobStatus::Failure,
                                        steps: vec![executor::StepResult {
                                            name: "Validation Error".to_string(),
                                            status: StepStatus::Failure,
                                            output: format!("Error: {}", e),
                                        }],
                                        logs: format!("Error validating workflow: {}", e),
                                    };

                                    ExecutionResult {
                                        jobs: vec![failed_job],
                                    }
                                }
                            }
                        } else {
                            match executor::execute_workflow(&workflow_path, runtime_type, verbose)
                                .await
                            {
                                Ok(result) => result,
                                Err(e) => {
                                    // Create a failed execution result with error message
                                    let failed_job = executor::JobResult {
                                        name: "Error".to_string(),
                                        status: JobStatus::Failure,
                                        steps: vec![executor::StepResult {
                                            name: "Execution Error".to_string(),
                                            status: StepStatus::Failure,
                                            output: format!("Error: {}", e),
                                        }],
                                        logs: format!("Error executing workflow: {}", e),
                                    };

                                    ExecutionResult {
                                        jobs: vec![failed_job],
                                    }
                                }
                            }
                        }
                    });

                    tx_clone.send((next_idx, result)).unwrap();
                });
            }
        }

        // Handle key events
        if event::poll(Duration::from_millis(100))? {
            if let Event::Key(key) = event::read()? {
                match key.code {
                    KeyCode::Char('q') => {
                        // Exit and clean up
                        break Ok(());
                    }
                    KeyCode::Esc => {
                        if app.detailed_view {
                            app.detailed_view = false;
                        } else if app.show_help {
                            app.show_help = false;
                        } else {
                            // Exit and clean up
                            break Ok(());
                        }
                    }
                    KeyCode::Tab => {
                        // Cycle through tabs
                        app.switch_tab((app.selected_tab + 1) % 4);
                    }
                    KeyCode::BackTab => {
                        // Cycle through tabs backwards
                        app.switch_tab((app.selected_tab + 3) % 4);
                    }
                    KeyCode::Char('1') | KeyCode::Char('w') => app.switch_tab(0),
                    KeyCode::Char('2') | KeyCode::Char('x') => app.switch_tab(1),
                    KeyCode::Char('3') | KeyCode::Char('l') => app.switch_tab(2),
                    KeyCode::Char('4') | KeyCode::Char('h') => app.switch_tab(3),
                    KeyCode::Up | KeyCode::Char('k') => match app.selected_tab {
                        0 => app.previous_workflow(),
                        1 => {
                            if app.detailed_view {
                                app.previous_step();
                            } else {
                                app.previous_job();
                            }
                        }
                        2 => app.scroll_logs_up(),
                        _ => {}
                    },
                    KeyCode::Down | KeyCode::Char('j') => match app.selected_tab {
                        0 => app.next_workflow(),
                        1 => {
                            if app.detailed_view {
                                app.next_step();
                            } else {
                                app.next_job();
                            }
                        }
                        2 => app.scroll_logs_down(),
                        _ => {}
                    },
                    KeyCode::Char(' ') => {
                        if app.selected_tab == 0 && !app.running {
                            app.toggle_selected();
                        }
                    }
                    KeyCode::Enter => {
                        match app.selected_tab {
                            0 => {
                                // In workflows tab, Enter runs the selected workflow
                                if !app.running {
                                    if let Some(idx) = app.workflow_list_state.selected() {
                                        app.workflows[idx].selected = true;
                                        app.queue_selected_for_execution();
                                        app.start_execution();
                                    }
                                }
                            }
                            1 => {
                                // In execution tab, Enter shows job details
                                app.toggle_detailed_view();
                            }
                            _ => {}
                        }
                    }
                    KeyCode::Char('r') => {
                        if !app.running {
                            app.queue_selected_for_execution();
                            app.start_execution();
                        }
                    }
                    KeyCode::Char('a') => {
                        if !app.running {
                            // Select all workflows
                            for workflow in &mut app.workflows {
                                workflow.selected = true;
                            }
                        }
                    }
                    KeyCode::Char('e') => {
                        if !app.running {
                            app.toggle_emulation_mode();
                        }
                    }
                    KeyCode::Char('v') => {
                        if !app.running {
                            app.toggle_validation_mode();
                        }
                    }
                    KeyCode::Char('n') => {
                        if !app.running {
                            // Deselect all workflows
                            for workflow in &mut app.workflows {
                                workflow.selected = false;
                            }
                        }
                    }
                    _ => {}
                }
            }
        }
    };

    // Clean up terminal
    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    terminal.show_cursor()?;

    result
}

// Main render function for the UI
fn render_ui(f: &mut Frame<CrosstermBackend<io::Stdout>>, app: &mut App) {
    // Check if help should be shown as an overlay
    if app.show_help {
        render_help_overlay(f);
        return;
    }

    let size = f.size();

    // Create main layout
    let main_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints(
            [
                Constraint::Length(3), // Title bar and tabs
                Constraint::Min(5),    // Main content
                Constraint::Length(2), // Status bar
            ]
            .as_ref(),
        )
        .split(size);

    // Render title bar with tabs
    render_title_bar(f, app, main_chunks[0]);

    // Render main content based on selected tab
    match app.selected_tab {
        0 => render_workflows_tab(f, app, main_chunks[1]),
        1 => render_execution_tab(f, app, main_chunks[1]),
        2 => render_logs_tab(f, app, main_chunks[1]),
        3 => render_help_tab(f, main_chunks[1]),
        _ => {}
    }

    // Render status bar
    render_status_bar(f, app, main_chunks[2]);
}

// Render the title bar with tabs
fn render_title_bar(f: &mut Frame<CrosstermBackend<io::Stdout>>, app: &App, area: Rect) {
    // Create tabs
    let titles = vec!["Workflows", "Execution", "Logs", "Help"];
    let tabs = Tabs::new(
        titles
            .iter()
            .enumerate()
            .map(|(i, t)| {
                if i == 1 {
                    // Special case for "Execution"
                    let e_part = &t[0..1]; // "E"
                    let x_part = &t[1..2]; // "x"
                    let rest = &t[2..]; // "ecution"
                    Line::from(vec![
                        Span::styled(e_part, Style::default().fg(Color::White)),
                        Span::styled(
                            x_part,
                            Style::default()
                                .fg(Color::Yellow)
                                .add_modifier(Modifier::UNDERLINED),
                        ),
                        Span::styled(rest, Style::default().fg(Color::White)),
                    ])
                } else {
                    // Original styling for other tabs
                    let (first, rest) = t.split_at(1);
                    Line::from(vec![
                        Span::styled(
                            first,
                            Style::default()
                                .fg(Color::Yellow)
                                .add_modifier(Modifier::UNDERLINED),
                        ),
                        Span::styled(rest, Style::default().fg(Color::White)),
                    ])
                }
            })
            .collect(),
    )
    .block(
        Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .title(Span::styled(
                " wrkflw ",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            ))
            .title_alignment(Alignment::Center),
    )
    .highlight_style(
        Style::default()
            .bg(Color::DarkGray)
            .fg(Color::Yellow)
            .add_modifier(Modifier::BOLD),
    )
    .select(app.selected_tab)
    .divider(Span::raw("|"));

    f.render_widget(tabs, area);
}

// Render the workflow list tab
fn render_workflows_tab(f: &mut Frame<CrosstermBackend<io::Stdout>>, app: &mut App, area: Rect) {
    let items: Vec<ListItem> = app
        .workflows
        .iter()
        .map(|w| {
            let checked = if w.selected { "" } else { "  " };
            let status_indicator = match w.status {
                WorkflowStatus::NotStarted => "  ",
                WorkflowStatus::Running => "",
                WorkflowStatus::Success => "",
                WorkflowStatus::Failed => "",
                WorkflowStatus::Skipped => "",
            };

            let status_style = match w.status {
                WorkflowStatus::NotStarted => Style::default(),
                WorkflowStatus::Running => Style::default().fg(Color::Cyan),
                WorkflowStatus::Success => Style::default().fg(Color::Green),
                WorkflowStatus::Failed => Style::default().fg(Color::Red),
                WorkflowStatus::Skipped => Style::default().fg(Color::Gray),
            };

            ListItem::new(Line::from(vec![
                Span::styled(checked, Style::default().fg(Color::Green)),
                Span::styled(status_indicator, status_style),
                Span::raw(&w.name),
            ]))
        })
        .collect();

    let workflows_list = List::new(items)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .title(Span::styled(
                    " Available Workflows ",
                    Style::default().fg(Color::Yellow),
                )),
        )
        .highlight_style(
            Style::default()
                .bg(Color::DarkGray)
                .add_modifier(Modifier::BOLD),
        )
        .highlight_symbol("» ");

    f.render_stateful_widget(workflows_list, area, &mut app.workflow_list_state);
}

fn render_execution_tab(f: &mut Frame<CrosstermBackend<io::Stdout>>, app: &mut App, area: Rect) {
    if app.detailed_view {
        render_job_detail_view(f, app, area);
        return;
    }
    let current_workflow_idx = app
        .current_execution
        .or_else(|| app.workflow_list_state.selected())
        .filter(|&idx| idx < app.workflows.len());

    if let Some(idx) = current_workflow_idx {
        let workflow = &app.workflows[idx];

        // Split the area into sections
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints(
                [
                    Constraint::Length(5), // Workflow info with progress bar
                    Constraint::Min(5),    // Jobs list
                    Constraint::Length(6), // Execution info
                ]
                .as_ref(),
            )
            .margin(1)
            .split(area);

        // Workflow info section
        let status_text = match workflow.status {
            WorkflowStatus::NotStarted => "Not Started",
            WorkflowStatus::Running => "Running",
            WorkflowStatus::Success => "Success",
            WorkflowStatus::Failed => "Failed",
            WorkflowStatus::Skipped => "Skipped",
        };

        let status_style = match workflow.status {
            WorkflowStatus::NotStarted => Style::default().fg(Color::Gray),
            WorkflowStatus::Running => Style::default().fg(Color::Cyan),
            WorkflowStatus::Success => Style::default().fg(Color::Green),
            WorkflowStatus::Failed => Style::default().fg(Color::Red),
            WorkflowStatus::Skipped => Style::default().fg(Color::Yellow),
        };

        let mut workflow_info = vec![
            Line::from(vec![
                Span::styled("Workflow: ", Style::default().fg(Color::Blue)),
                Span::styled(
                    workflow.name.clone(),
                    Style::default()
                        .fg(Color::White)
                        .add_modifier(Modifier::BOLD),
                ),
            ]),
            Line::from(vec![
                Span::styled("Status: ", Style::default().fg(Color::Blue)),
                Span::styled(status_text, status_style),
            ]),
        ];

        // Add progress bar for running workflows
        if let Some(execution) = &workflow.execution_details {
            // Calculate progress
            let progress = execution.progress;

            // Add progress bar
            let gauge_color = match workflow.status {
                WorkflowStatus::Running => Color::Cyan,
                WorkflowStatus::Success => Color::Green,
                WorkflowStatus::Failed => Color::Red,
                _ => Color::Gray,
            };

            let progress_text = match workflow.status {
                WorkflowStatus::Running => format!("{:.0}%", progress * 100.0),
                WorkflowStatus::Success => "Completed".to_string(),
                WorkflowStatus::Failed => "Failed".to_string(),
                _ => "Not started".to_string(),
            };

            // Add empty line before progress bar
            workflow_info.push(Line::from(""));

            // Add the gauge widget to the paragraph data
            workflow_info.push(Line::from(vec![Span::styled(
                format!("Progress: {}", progress_text),
                Style::default().fg(Color::Blue),
            )]));

            let gauge = Gauge::default()
                .block(Block::default())
                .gauge_style(Style::default().fg(gauge_color).bg(Color::Black))
                .percent((progress * 100.0) as u16);

            // Render gauge separately after the paragraph
            let workflow_info_widget = Paragraph::new(workflow_info).block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_type(BorderType::Rounded)
                    .title(Span::styled(
                        " Workflow Information ",
                        Style::default().fg(Color::Yellow),
                    )),
            );

            let gauge_area = Rect {
                x: chunks[0].x + 2,
                y: chunks[0].y + 4,
                width: chunks[0].width - 4,
                height: 1,
            };

            f.render_widget(workflow_info_widget, chunks[0]);
            f.render_widget(gauge, gauge_area);
        } else {
            // No execution details
            let workflow_info_widget = Paragraph::new(workflow_info).block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_type(BorderType::Rounded)
                    .title(Span::styled(
                        " Workflow Information ",
                        Style::default().fg(Color::Yellow),
                    )),
            );
            f.render_widget(workflow_info_widget, chunks[0]);
        }

        // Jobs list section
        if let Some(execution) = &workflow.execution_details {
            if execution.jobs.is_empty() {
                let placeholder = Paragraph::new("No jobs have started execution yet...")
                    .block(
                        Block::default()
                            .borders(Borders::ALL)
                            .border_type(BorderType::Rounded)
                            .title(Span::styled(" Jobs ", Style::default().fg(Color::Yellow))),
                    )
                    .alignment(Alignment::Center);
                f.render_widget(placeholder, chunks[1]);
            } else {
                let job_items: Vec<ListItem> = execution
                    .jobs
                    .iter()
                    .map(|job| {
                        let status_symbol = match job.status {
                            JobStatus::Success => "",
                            JobStatus::Failure => "",
                            JobStatus::Skipped => "",
                        };

                        let status_style = match job.status {
                            JobStatus::Success => Style::default().fg(Color::Green),
                            JobStatus::Failure => Style::default().fg(Color::Red),
                            JobStatus::Skipped => Style::default().fg(Color::Gray),
                        };

                        // Count completed and total steps
                        let total_steps = job.steps.len();
                        let completed_steps = job
                            .steps
                            .iter()
                            .filter(|s| {
                                s.status == StepStatus::Success || s.status == StepStatus::Failure
                            })
                            .count();

                        let steps_info = format!("[{}/{}]", completed_steps, total_steps);

                        ListItem::new(Line::from(vec![
                            Span::styled(status_symbol, status_style),
                            Span::raw(" "),
                            Span::styled(&job.name, Style::default().fg(Color::White)),
                            Span::raw(" "),
                            Span::styled(steps_info, Style::default().fg(Color::DarkGray)),
                        ]))
                    })
                    .collect();

                let jobs_list = List::new(job_items)
                    .block(
                        Block::default()
                            .borders(Borders::ALL)
                            .border_type(BorderType::Rounded)
                            .title(Span::styled(" Jobs ", Style::default().fg(Color::Yellow))),
                    )
                    .highlight_style(
                        Style::default()
                            .bg(Color::DarkGray)
                            .add_modifier(Modifier::BOLD),
                    )
                    .highlight_symbol("» ");

                f.render_stateful_widget(jobs_list, chunks[1], &mut app.job_list_state);
            }

            // Execution info section
            let mut execution_info = Vec::new();

            execution_info.push(Line::from(vec![
                Span::styled("Started: ", Style::default().fg(Color::Blue)),
                Span::styled(
                    execution.start_time.format("%Y-%m-%d %H:%M:%S").to_string(),
                    Style::default().fg(Color::White),
                ),
            ]));

            if let Some(end_time) = execution.end_time {
                execution_info.push(Line::from(vec![
                    Span::styled("Finished: ", Style::default().fg(Color::Blue)),
                    Span::styled(
                        end_time.format("%Y-%m-%d %H:%M:%S").to_string(),
                        Style::default().fg(Color::White),
                    ),
                ]));

                // Calculate duration
                let duration = end_time.signed_duration_since(execution.start_time);
                execution_info.push(Line::from(vec![
                    Span::styled("Duration: ", Style::default().fg(Color::Blue)),
                    Span::styled(
                        format!(
                            "{}m {}s",
                            duration.num_minutes(),
                            duration.num_seconds() % 60
                        ),
                        Style::default().fg(Color::White),
                    ),
                ]));
            } else {
                // Show running time for active workflows
                let current_time = Local::now();
                let running_time = current_time.signed_duration_since(execution.start_time);
                execution_info.push(Line::from(vec![
                    Span::styled("Running for: ", Style::default().fg(Color::Blue)),
                    Span::styled(
                        format!(
                            "{}m {}s",
                            running_time.num_minutes(),
                            running_time.num_seconds() % 60
                        ),
                        Style::default().fg(Color::White),
                    ),
                ]));
            }

            // Add hint for Enter key to see details
            execution_info.push(Line::from(""));
            execution_info.push(Line::from(vec![
                Span::styled("Press ", Style::default().fg(Color::DarkGray)),
                Span::styled("Enter", Style::default().fg(Color::Yellow)),
                Span::styled(" to view job details", Style::default().fg(Color::DarkGray)),
            ]));

            let info_widget = Paragraph::new(execution_info).block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_type(BorderType::Rounded)
                    .title(Span::styled(
                        " Execution Information ",
                        Style::default().fg(Color::Yellow),
                    )),
            );

            f.render_widget(info_widget, chunks[2]);
        } else {
            // No execution details yet
            let placeholder = Paragraph::new("Execution has not started yet...")
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .border_type(BorderType::Rounded)
                        .title(Span::styled(" Jobs ", Style::default().fg(Color::Yellow))),
                )
                .alignment(Alignment::Center);

            f.render_widget(placeholder, chunks[1]);

            let info_placeholder = Paragraph::new("Waiting for execution to start...")
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .border_type(BorderType::Rounded)
                        .title(Span::styled(
                            " Execution Information ",
                            Style::default().fg(Color::Yellow),
                        )),
                )
                .alignment(Alignment::Center);

            f.render_widget(info_placeholder, chunks[2]);
        }
    } else {
        // No workflow execution to display
        let placeholder = Paragraph::new(vec![
            Line::from(""),
            Line::from(vec![Span::styled(
                "No workflow execution data available.",
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            )]),
            Line::from(""),
            Line::from("Select workflows in the Workflows tab and press 'r' to run them."),
            Line::from(""),
            Line::from("Or press Enter on a selected workflow to run it directly."),
        ])
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .title(Span::styled(
                    " Execution ",
                    Style::default().fg(Color::Yellow),
                )),
        )
        .alignment(Alignment::Center);

        f.render_widget(placeholder, area);
    }
}

// Render detailed job view
fn render_job_detail_view(f: &mut Frame<CrosstermBackend<io::Stdout>>, app: &mut App, area: Rect) {
    // Get the current workflow and job
    let current_workflow_idx = app
        .current_execution
        .or_else(|| app.workflow_list_state.selected())
        .filter(|&idx| idx < app.workflows.len());

    if let Some(workflow_idx) = current_workflow_idx {
        let workflow = &app.workflows[workflow_idx];

        if let Some(execution) = &workflow.execution_details {
            if execution.jobs.is_empty() {
                let placeholder = Paragraph::new("This job has no steps or execution data.")
                    .block(
                        Block::default()
                            .borders(Borders::ALL)
                            .border_type(BorderType::Rounded)
                            .title(Span::styled(
                                " Job Details ",
                                Style::default().fg(Color::Yellow),
                            )),
                    )
                    .alignment(Alignment::Center);

                f.render_widget(placeholder, area);
                return;
            }

            // Ensure job index is valid
            let job_idx = app
                .job_list_state
                .selected()
                .unwrap_or(0)
                .min(execution.jobs.len() - 1);
            let job = &execution.jobs[job_idx];

            // Split area for job details
            let chunks = Layout::default()
                .direction(Direction::Vertical)
                .constraints(
                    [
                        Constraint::Length(4), // Job info
                        Constraint::Length(7), // Steps list with border
                        Constraint::Min(3),    // Step output
                    ]
                    .as_ref(),
                )
                .margin(1)
                .split(area);

            // Job info
            let status_style = match job.status {
                JobStatus::Success => Style::default().fg(Color::Green),
                JobStatus::Failure => Style::default().fg(Color::Red),
                JobStatus::Skipped => Style::default().fg(Color::Gray),
            };

            let status_text = match job.status {
                JobStatus::Success => "Success",
                JobStatus::Failure => "Failed",
                JobStatus::Skipped => "Skipped",
            };

            let job_info = Paragraph::new(vec![
                Line::from(vec![
                    Span::styled("Job: ", Style::default().fg(Color::Blue)),
                    Span::styled(
                        job.name.clone(),
                        Style::default()
                            .fg(Color::White)
                            .add_modifier(Modifier::BOLD),
                    ),
                ]),
                Line::from(vec![
                    Span::styled("Status: ", Style::default().fg(Color::Blue)),
                    Span::styled(status_text, status_style),
                ]),
                Line::from(vec![
                    Span::styled("Steps: ", Style::default().fg(Color::Blue)),
                    Span::styled(
                        format!("{}", job.steps.len()),
                        Style::default().fg(Color::White),
                    ),
                ]),
            ])
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_type(BorderType::Rounded)
                    .title(Span::styled(
                        format!(" Job Details ({}/{}) ", job_idx + 1, execution.jobs.len()),
                        Style::default().fg(Color::Yellow),
                    )),
            );

            f.render_widget(job_info, chunks[0]);

            // Steps list with more details
            // Create a table for better aligned step information
            let header_cells = ["Status", "Step Name", "Duration"]
                .iter()
                .map(|h| Cell::from(*h).style(Style::default().fg(Color::Yellow)));

            let header = Row::new(header_cells)
                .style(Style::default().add_modifier(Modifier::BOLD))
                .height(1);

            let rows = job.steps.iter().map(|step| {
                let status_symbol = match step.status {
                    StepStatus::Success => "",
                    StepStatus::Failure => "",
                    StepStatus::Skipped => "",
                };

                let status_style = match step.status {
                    StepStatus::Success => Style::default().fg(Color::Green),
                    StepStatus::Failure => Style::default().fg(Color::Red),
                    StepStatus::Skipped => Style::default().fg(Color::Gray),
                };

                // Calculate fake duration (would be real in a complete app)
                let duration = "1s";

                Row::new(vec![
                    Cell::from(status_symbol).style(status_style),
                    Cell::from(step.name.clone()),
                    Cell::from(duration).style(Style::default().fg(Color::DarkGray)),
                ])
                .height(1)
            });

            let steps_table = Table::new(rows)
                .header(header)
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .border_type(BorderType::Rounded)
                        .title(Span::styled(" Steps ", Style::default().fg(Color::Yellow))),
                )
                .highlight_style(Style::default().bg(Color::DarkGray))
                .highlight_symbol("» ")
                .widths(&[
                    Constraint::Length(8),      // Status column
                    Constraint::Percentage(70), // Name column (takes most space)
                    Constraint::Length(10),     // Duration column
                ]);

            f.render_stateful_widget(steps_table, chunks[1], &mut app.step_table_state);

            // Step output - show output from the selected step
            let output_text = if !job.steps.is_empty() {
                let step_idx = app
                    .step_list_state
                    .selected()
                    .unwrap_or(0)
                    .min(job.steps.len() - 1);
                let step = &job.steps[step_idx];

                let mut output = step.output.clone();
                if output.is_empty() {
                    output = "No output for this step.".to_string();
                }

                // Limit output to prevent performance issues with very long strings
                if output.len() > 2000 {
                    let truncated = &output[..2000];
                    format!("{}\n... (output truncated) ...", truncated)
                } else {
                    output
                }
            } else {
                "No steps to display output for.".to_string()
            };

            let output_widget = Paragraph::new(output_text)
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .border_type(BorderType::Rounded)
                        .title(Span::styled(" Output ", Style::default().fg(Color::Yellow))),
                )
                .wrap(Wrap { trim: true });

            f.render_widget(output_widget, chunks[2]);
        } else {
            // No execution details
            let placeholder = Paragraph::new("No job execution details available.")
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .border_type(BorderType::Rounded)
                        .title(Span::styled(
                            " Job Details ",
                            Style::default().fg(Color::Yellow),
                        )),
                )
                .alignment(Alignment::Center);

            f.render_widget(placeholder, area);
        }
    } else {
        // No workflow selected
        let placeholder = Paragraph::new("No workflow execution available to display details.")
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_type(BorderType::Rounded)
                    .title(Span::styled(
                        " Job Details ",
                        Style::default().fg(Color::Yellow),
                    )),
            )
            .alignment(Alignment::Center);

        f.render_widget(placeholder, area);
    }
}

// Render the logs tab
fn render_logs_tab(f: &mut Frame<CrosstermBackend<io::Stdout>>, app: &App, area: Rect) {
    // Combine application logs with system logs
    let mut all_logs = app.logs.clone();
    all_logs.extend(crate::logging::get_logs());

    // Create visible log lines, with timestamps and color coding
    let log_items: Vec<ListItem> = all_logs
        .iter()
        .map(|log_line| {
            // Try to parse log line to extract type (info, error, etc)
            let style = if log_line.contains("Error")
                || log_line.contains("error")
                || log_line.contains("")
            {
                Style::default().fg(Color::Red)
            } else if log_line.contains("Warning")
                || log_line.contains("warning")
                || log_line.contains("⚠️")
            {
                Style::default().fg(Color::Yellow)
            } else if log_line.contains("Success")
                || log_line.contains("success")
                || log_line.contains("")
            {
                Style::default().fg(Color::Green)
            } else if log_line.contains("Running")
                || log_line.contains("running")
                || log_line.contains("")
            {
                Style::default().fg(Color::Cyan)
            } else {
                Style::default().fg(Color::Gray)
            };

            ListItem::new(Line::from(Span::styled(log_line, style)))
        })
        .collect();

    let logs_list = List::new(log_items)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .title(Span::styled(
                    " Execution Logs ",
                    Style::default().fg(Color::Yellow),
                )),
        )
        .start_corner(ratatui::layout::Corner::BottomLeft); // Show most recent logs at the bottom

    f.render_widget(logs_list, area);
}

// Render the help tab
fn render_help_tab(f: &mut Frame<CrosstermBackend<io::Stdout>>, area: Rect) {
    let help_text = vec![
        Line::from(Span::styled(
            "Keyboard Controls",
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        )),
        Line::from(""),
        Line::from(vec![
            Span::styled(
                "Tab",
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw(" - Switch between tabs"),
        ]),
        Line::from(vec![
            Span::styled(
                "1-4",
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw(" - Switch directly to tab"),
        ]),
        Line::from(vec![
            Span::styled(
                "Up/Down or j/k",
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw(" - Navigate lists"),
        ]),
        Line::from(vec![
            Span::styled(
                "Space",
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw(" - Toggle workflow selection"),
        ]),
        Line::from(vec![
            Span::styled(
                "Enter",
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw(" - Run selected workflow / View job details"),
        ]),
        Line::from(vec![
            Span::styled(
                "r",
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw(" - Run all selected workflows"),
        ]),
        Line::from(vec![
            Span::styled(
                "a",
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw(" - Select all workflows"),
        ]),
        Line::from(vec![
            Span::styled(
                "e",
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw(" - Toggle between Docker and Emulation mode"),
        ]),
        Line::from(vec![
            Span::styled(
                "v",
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw(" - Toggle between Execution and Validation mode"),
        ]),
        Line::from(vec![
            Span::styled(
                "n",
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw(" - Deselect all workflows"),
        ]),
        Line::from(vec![
            Span::styled(
                "Esc",
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw(" - Back / Exit detailed view"),
        ]),
        Line::from(vec![
            Span::styled(
                "q",
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw(" - Quit application"),
        ]),
        Line::from(""),
        Line::from(Span::styled(
            "Runtime Modes",
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        )),
        Line::from(""),
        Line::from(vec![
            Span::styled(
                "Docker",
                Style::default()
                    .fg(Color::Blue)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw(" - Uses Docker to run workflows (default)"),
        ]),
        Line::from(vec![
            Span::styled(
                "Emulation",
                Style::default()
                    .fg(Color::Magenta)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw(" - Emulates GitHub Actions environment locally (no Docker required)"),
        ]),
    ];

    let help_widget = Paragraph::new(help_text)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .title(Span::styled(" Help ", Style::default().fg(Color::Yellow))),
        )
        .wrap(Wrap { trim: true });

    f.render_widget(help_widget, area);
}

// Render a help overlay
fn render_help_overlay(f: &mut Frame<CrosstermBackend<io::Stdout>>) {
    let size = f.size();

    // Create a slightly smaller centered modal
    let width = size.width.min(60);
    let height = size.height.min(20);
    let x = (size.width - width) / 2;
    let y = (size.height - height) / 2;

    let help_area = Rect {
        x,
        y,
        width,
        height,
    };

    // Create a clear background
    let clear = Block::default().style(Style::default().bg(Color::Black));
    f.render_widget(clear, size);

    // Render the help content
    render_help_tab(f, help_area);
}

// Render the status bar
fn render_status_bar(f: &mut Frame<CrosstermBackend<io::Stdout>>, app: &App, area: Rect) {
    let runtime_mode = match app.runtime_type {
        RuntimeType::Docker => "Docker",
        RuntimeType::Emulation => "Emulation",
    };

    let runtime_style = match app.runtime_type {
        RuntimeType::Docker => Style::default()
            .fg(Color::Blue)
            .add_modifier(Modifier::BOLD),
        RuntimeType::Emulation => Style::default()
            .fg(Color::Magenta)
            .add_modifier(Modifier::BOLD),
    };

    let mode_text = if app.validation_mode {
        "VALIDATION"
    } else {
        "EXECUTION"
    };

    let mode_style = if app.validation_mode {
        Style::default()
            .fg(Color::Yellow)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default()
            .fg(Color::Green)
            .add_modifier(Modifier::BOLD)
    };

    // Left side of status bar
    let left_text = Line::from(vec![
        Span::raw("Runtime: "),
        Span::styled(runtime_mode, runtime_style),
        Span::raw(" | "),
        Span::raw("Mode: "),
        Span::styled(mode_text, mode_style),
        Span::raw(" | "),
        Span::styled(
            format!("{} workflow(s) loaded", app.workflows.len()),
            Style::default().fg(Color::White),
        ),
    ]);

    // Right side of status bar
    let right_text = Line::from(vec![
        Span::styled(
            "e",
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw(": Toggle Emulation | "),
        Span::styled(
            "v",
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw(": Toggle Validation | "),
        Span::styled(
            "q",
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw(": Quit"),
    ]);

    // Create a layout with two parts for left and right aligned text
    let status_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
        .split(area);

    let left_status = Paragraph::new(left_text).alignment(Alignment::Left);

    let right_status = Paragraph::new(right_text).alignment(Alignment::Right);

    f.render_widget(left_status, status_chunks[0]);
    f.render_widget(right_status, status_chunks[1]);
}

// Validate a workflow or directory containing workflows
pub fn validate_workflow(path: &PathBuf, verbose: bool) -> io::Result<()> {
    let mut workflows = Vec::new();

    if path.is_dir() {
        let entries = std::fs::read_dir(path)?;

        for entry in entries {
            let entry = entry?;
            let entry_path = entry.path();

            if entry_path.is_file() && is_workflow_file(&entry_path) {
                workflows.push(entry_path);
            }
        }
    } else if path.is_file() {
        workflows.push(path.clone());
    } else {
        return Err(io::Error::new(
            io::ErrorKind::NotFound,
            format!("Path does not exist: {}", path.display()),
        ));
    }

    let mut valid_count = 0;
    let mut invalid_count = 0;

    println!("Validating {} workflow file(s)...", workflows.len());

    for workflow_path in workflows {
        match evaluate_workflow_file(&workflow_path, verbose) {
            Ok(result) => {
                if result.is_valid {
                    println!("✅ Valid: {}", workflow_path.display());
                    valid_count += 1;
                } else {
                    println!("❌ Invalid: {}", workflow_path.display());
                    for (i, issue) in result.issues.iter().enumerate() {
                        println!("   {}. {}", i + 1, issue);
                    }
                    invalid_count += 1;
                }
            }
            Err(e) => {
                println!("❌ Error processing {}: {}", workflow_path.display(), e);
                invalid_count += 1;
            }
        }
    }

    println!(
        "\nSummary: {} valid, {} invalid",
        valid_count, invalid_count
    );

    Ok(())
}

pub async fn execute_workflow_cli(
    path: &PathBuf,
    runtime_type: RuntimeType,
    verbose: bool,
) -> io::Result<()> {
    if !path.exists() {
        return Err(io::Error::new(
            io::ErrorKind::NotFound,
            format!("Workflow file does not exist: {}", path.display()),
        ));
    }

    println!("Validating workflow...");
    match evaluate_workflow_file(path, false) {
        Ok(result) => {
            if !result.is_valid {
                println!("❌ Cannot execute invalid workflow: {}", path.display());
                for (i, issue) in result.issues.iter().enumerate() {
                    println!("   {}. {}", i + 1, issue);
                }
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "Workflow validation failed",
                ));
            }
        }
        Err(e) => {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                format!("Error validating workflow: {}", e),
            ));
        }
    }

    println!("Executing workflow: {}", path.display());
    println!("Runtime mode: {:?}", runtime_type);

    match executor::execute_workflow(path, runtime_type, verbose).await {
        Ok(result) => {
            println!("\nWorkflow execution results:");

            for job in &result.jobs {
                match job.status {
                    JobStatus::Success => {
                        println!("\n✅ Job succeeded: {}", job.name);
                    }
                    JobStatus::Failure => {
                        println!("\n❌ Job failed: {}", job.name);
                    }
                    JobStatus::Skipped => {
                        println!("\n⏭️ Job skipped: {}", job.name);
                    }
                }

                println!("-------------------------");

                for step in job.steps.iter() {
                    match step.status {
                        StepStatus::Success => {
                            println!("{}", step.name);

                            if !step.output.trim().is_empty() && step.output.lines().count() <= 3 {
                                // For short outputs, show directly
                                println!("    {}", step.output.trim());
                            }
                        }
                        StepStatus::Failure => {
                            println!("{}", step.name);

                            // For failures, always show output (truncated)
                            let output = if step.output.len() > 500 {
                                format!("{}... (truncated)", &step.output[..500])
                            } else {
                                step.output.clone()
                            };

                            println!("    {}", output.trim().replace('\n', "\n    "));
                        }
                        StepStatus::Skipped => {
                            println!("  ⏭️ {} (skipped)", step.name);
                        }
                    }
                }
            }

            // Determine overall success
            let failures = result
                .jobs
                .iter()
                .filter(|job| job.status == JobStatus::Failure)
                .count();

            if failures > 0 {
                println!("\n❌ Workflow completed with failures");
                return Err(io::Error::new(
                    io::ErrorKind::Other,
                    "Workflow execution failed",
                ));
            } else {
                println!("\n✅ Workflow completed successfully!");
                Ok(())
            }
        }
        Err(e) => {
            println!("❌ Failed to execute workflow: {}", e);
            Err(io::Error::new(
                io::ErrorKind::Other,
                format!("Workflow execution error: {}", e),
            ))
        }
    }
}

// Main entry point for the TUI interface
pub async fn run_wrkflw_tui(
    path: Option<&PathBuf>,
    runtime_type: RuntimeType,
    verbose: bool,
) -> io::Result<()> {
    match run_tui(path, &runtime_type, verbose) {
        Ok(_) => Ok(()),
        Err(e) => {
            // If the TUI fails to initialize or crashes, fall back to CLI mode
            eprintln!("Failed to start UI: {}", e);

            if let Some(path) = path {
                if path.is_file() {
                    println!("Falling back to CLI mode...");
                    execute_workflow_cli(path, runtime_type, verbose).await
                } else {
                    validate_workflow(path, verbose)
                }
            } else {
                Err(e)
            }
        }
    }
}