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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
import numpy as np
from enum import Enum
from src.geometry.convex_hull_processor import ConvexHullProcessor_2d
from src.geometry.placement_helper import PlacementHelper

from . import process_based_task_generation
from src.vlm_interaction.interact_prompt_helper import (
    StatePromptManager,
    HintPromptManager,
    ReflectionPromptManager,
)
from src.core.process_based_task_generation import TaskType
from src.utils.config_manager import get_benchmark_executor_config, get_config
import os
import copy
import glog
import json
from abc import ABC, abstractmethod
import re

NINE_DIRECTIONS = [
    "rear",
    "rear-left",
    "left",
    "front-left",
    "front",
    "front-right",
    "right",
    "rear-right",
    "center",
]


class InteractStates(Enum):
    DEFAULT = -1
    NAVIGATION = 0
    IDLE = 1
    HOLDING_OCCUPIED_PLATFORM = 2
    HOLDING_EMPTY_PLATFORM = 3
    CALL_END = -2

    @classmethod
    def from_string(cls, state_str):
        state_str = state_str.upper()
        try:
            return cls[state_str]
        except KeyError:
            raise ValueError(f"Invalid InteractState string: {state_str}")

    @classmethod
    def to_string(cls, state):
        if isinstance(state, cls):
            return state.name.lower()
        else:
            raise ValueError(f"Invalid InteractState: {state}")


class ActionType(Enum):
    INVALID = -1
    CALL_END = 0
    NOT_AVAILABLE = 1
    PLACE_IDLE = 2
    PLACE_INVALID = 3
    GOTO_PLATFORM = 100
    PICKUP_OBJECT = 200
    PLACE_ANYWHERE = 300
    PLACE_EMPTY = 301
    PLACE_OCCUPIED = 302

    ROTATE = 400
    SHOW_OBJECT = 500


class InteractSystemState(ABC):
    state_prompt_helper = StatePromptManager(
        prompt_templates="src/utils/prompts/benchmark_prompts.json"
    )

    def __init__(self, state_type):
        self.state = state_type

    @abstractmethod
    def get_action_space(self):
        pass

    @staticmethod
    def validate_action(action_str) -> ActionType:

        if not isinstance(action_str, str) or action_str is None:
            return (ActionType.INVALID,)
        if action_str.startswith("`") and action_str.endswith("`"):
            action_str = action_str[1:-1]
        if action_str.startswith('"') and action_str.endswith('"'):
            action_str = action_str[1:-1]
        if action_str.startswith("'") and action_str.endswith("'"):
            action_str = action_str[1:-1]

        if action_str.endswith("_of_current_platform") or action_str.endswith(
            "_on_current_platform"
        ):
            action_str = action_str[: -len("_of_current_platform")]
        if action_str.upper() == "CALL_END":
            return ActionType.CALL_END, 0
        elif action_str == "rotate_observation_view":
            return ActionType.ROTATE, 0
        elif action_str == "place_at_anywhere":
            return ActionType.PLACE_ANYWHERE, 0

        elif action_str.startswith("goto_"):
            try:
                platform_name = (action_str[len("goto_") :]).strip()
                return ActionType.GOTO_PLATFORM, platform_name
            except:
                return ActionType.INVALID, 0
        elif action_str.startswith("pick_up_object_"):
            try:
                object_num = int(action_str[len("pick_up_object_") :].strip())
                if object_num > 0:
                    return ActionType.PICKUP_OBJECT, object_num
            except:
                return ActionType.INVALID, 0
        elif action_str.startswith("show_freespace_of_object_"):
            try:
                object_num = int(action_str[len("show_freespace_of_object_") :].strip())
                if object_num > 0:
                    return ActionType.SHOW_OBJECT, object_num
            except:
                return ActionType.INVALID, 0
        elif action_str.startswith("place_at_freespace_["):
            try:
                action_str = action_str[len("place_at_freespace_") :]
                action_list = eval(action_str)
                if isinstance(action_list, list):
                    all_numbers = all(
                        isinstance(action, int) and 1 <= action <= 9
                        for action in action_list
                    )
                    all_tuples = all(
                        isinstance(action, tuple) for action in action_list
                    )
                    # import ipdb
                    # ipdb.set_trace()
                    if all_numbers:
                        return ActionType.PLACE_EMPTY, action_list
                    elif all_tuples:
                        return ActionType.PLACE_OCCUPIED, action_list
                    else:
                        return ActionType.INVALID, 0
                else:
                    return ActionType.INVALID, 0
            except:
                return ActionType.INVALID, 0

        return ActionType.INVALID, 0
        pass

    @abstractmethod
    def validate_action_details(action_str):
        pass

    @abstractmethod
    def generate_prompt(context: dict):
        pass


class NavigationState(InteractSystemState):
    action_space_type = [ActionType.CALL_END, ActionType.GOTO_PLATFORM]

    def __init__(self):
        super().__init__(InteractStates.NAVIGATION)

    @staticmethod
    def validate_action_details(action_str, platform_name_list):

        action_type, action_param = NavigationState.validate_action(action_str)
        glog.info(f"Action type: {action_type}, Action param: {action_param}")
        if action_type not in NavigationState.action_space_type:
            return (
                ActionType.NOT_AVAILABLE
                if action_type != ActionType.INVALID
                else ActionType.INVALID
            ), 0

        if action_type == ActionType.CALL_END:
            return action_type, 0
        elif action_type == ActionType.GOTO_PLATFORM:
            if action_param in platform_name_list:
                return action_type, action_param

        return ActionType.INVALID, 0

    @staticmethod
    def generate_prompt(
        scene_description,
        platform_list,
        task_description,
        steps_used,
        total_steps,
        location_action_list,
    ):
        prompt = InteractSystemState.state_prompt_helper.generate_state_prompts(
            state=InteractStates.NAVIGATION.name.lower(),
            context={
                "scene_description": "",
                "platform_list": platform_list,
                "task_description": task_description,
                "steps_used": steps_used,
                "total_steps": total_steps,
                "location_action_list": location_action_list,
            },
        )
        return prompt


class IdleState(InteractSystemState):
    action_space_type = [
        ActionType.ROTATE,
        ActionType.CALL_END,
        ActionType.GOTO_PLATFORM,
        ActionType.PICKUP_OBJECT,
        ActionType.SHOW_OBJECT,
    ]

    def __init__(self):
        super().__init__(InteractStates.IDLE)

    @staticmethod
    def validate_action_details(action_str, platform_name_list, object_num):
        action_type, action_param = IdleState.validate_action(action_str)
        if action_type not in IdleState.action_space_type:
            return (
                ActionType.NOT_AVAILABLE
                if action_type != ActionType.INVALID
                else ActionType.INVALID
            ), 0
        if action_type == ActionType.CALL_END or action_type == ActionType.ROTATE:
            return action_type, 0
        elif action_type == ActionType.GOTO_PLATFORM:
            if action_param in platform_name_list:
                return action_type, action_param
        elif (
            action_type == ActionType.PICKUP_OBJECT
            or action_type == ActionType.SHOW_OBJECT
        ):
            if action_param > 0 and action_param <= object_num:
                return action_type, action_param

        return ActionType.INVALID, 0

    @staticmethod
    def generate_prompt(
        scene_description,
        platform_list,
        task_description,
        steps_used,
        total_steps,
        platform_name,
        holding_object,
        image_type,
        image_info_list,
        location_action_list,
        object_action_list,
        show_freespace_of_object_action_list,
        n_image,
        image_name_list,
    ):
        prompt = InteractSystemState.state_prompt_helper.generate_state_prompts(
            state=InteractStates.IDLE.name.lower(),
            context={
                "scene_description": scene_description,
                "platform_list": platform_list,
                "task_description": task_description,
                "steps_used": steps_used,
                "total_steps": total_steps,
                "platform_name": platform_name,
                "holding_object": holding_object,
                "image_type": image_type,
                "image_info_list": image_info_list,
                "location_action_list": location_action_list,
                "object_action_list": object_action_list,
                "show_freespace_of_object_action_list": show_freespace_of_object_action_list,
                "n_image": n_image,
                "image_name_list": image_name_list,
            },
        )
        return prompt


class HoldingEmptyPlatformState(InteractSystemState):
    action_space_type = [
        ActionType.ROTATE,
        ActionType.CALL_END,
        ActionType.GOTO_PLATFORM,
        ActionType.PLACE_EMPTY,
        ActionType.PLACE_ANYWHERE,
        ActionType.SHOW_OBJECT,
    ]

    def __init__(self):
        super().__init__(InteractStates.HOLDING_EMPTY_PLATFORM)

    @staticmethod
    def validate_action_details(action_str, platform_name_list, object_num):
        action_type, action_param = HoldingEmptyPlatformState.validate_action(
            action_str
        )
        if action_type not in HoldingEmptyPlatformState.action_space_type:
            return (
                ActionType.NOT_AVAILABLE
                if action_type != ActionType.INVALID
                else ActionType.INVALID
            ), 0
        if (
            action_type == ActionType.CALL_END
            or action_type == ActionType.ROTATE
            or action_type == ActionType.PLACE_ANYWHERE
        ):
            return action_type, 0
        elif action_type == ActionType.PLACE_EMPTY:
            if isinstance(action_param, list):
                return action_type, action_param

        elif action_type == ActionType.GOTO_PLATFORM:
            if action_param in platform_name_list:
                return action_type, action_param
        elif action_type == ActionType.SHOW_OBJECT:
            if action_param > 0 and action_param <= object_num:
                return action_type, action_param
        return ActionType.INVALID, 0

    @staticmethod
    def generate_prompt(
        scene_description,
        platform_list,
        task_description,
        steps_used,
        total_steps,
        platform_name,
        holding_object,
        image_type,
        image_info_list,
        location_action_list,
        show_freespace_of_object_action_list,
        n_image,
        image_name_list,
    ):
        prompt = InteractSystemState.state_prompt_helper.generate_state_prompts(
            state=InteractStates.HOLDING_EMPTY_PLATFORM.name.lower(),
            context={
                "scene_description": scene_description,
                "platform_list": platform_list,
                "task_description": task_description,
                "steps_used": steps_used,
                "total_steps": total_steps,
                "platform_name": platform_name,
                "holding_object": holding_object,
                "image_type": image_type,
                "image_info_list": image_info_list,
                "location_action_list": location_action_list,
                "show_freespace_of_object_action_list": show_freespace_of_object_action_list,
                "object_action_list": [],
                "n_image": n_image,
                "image_name_list": image_name_list,
            },
        )
        return prompt


class HoldingOccupiedPlatformState(InteractSystemState):
    action_space_type = [
        ActionType.ROTATE,
        ActionType.CALL_END,
        ActionType.GOTO_PLATFORM,
        ActionType.PLACE_OCCUPIED,
        ActionType.PLACE_ANYWHERE,
        ActionType.SHOW_OBJECT,
    ]

    def __init__(self):
        super().__init__(InteractStates.HOLDING_OCCUPIED_PLATFORM)

    @staticmethod
    def validate_action_details(
        action_str, object_num, platform_name_list, freespace_pair_list
    ):
        action_type, action_param = HoldingOccupiedPlatformState.validate_action(
            action_str
        )
        if action_type not in HoldingOccupiedPlatformState.action_space_type:
            return ActionType.INVALID, 0
        elif (
            action_type == ActionType.CALL_END
            or action_type == ActionType.ROTATE
            or action_type == ActionType.PLACE_ANYWHERE
        ):
            return action_type, 0
        elif action_type == ActionType.GOTO_PLATFORM:
            if action_param in platform_name_list:
                return action_type, action_param
            else:
                return ActionType.INVALID, 0

        elif action_type == ActionType.PLACE_OCCUPIED:
            if isinstance(action_param, list):
                if all(item in freespace_pair_list for item in action_param):
                    return action_type, action_param
                else:
                    return ActionType.INVALID, 0
            else:
                return ActionType.INVALID, 0
        elif action_type == ActionType.SHOW_OBJECT:
            if action_param > 0 and action_param <= object_num:
                return action_type, action_param
            else:
                return ActionType.INVALID, 0
        else:
            return ActionType.INVALID, 0
        return ActionType.INVALID, 0

    @staticmethod
    def generate_prompt(
        scene_description,
        platform_list,
        task_description,
        steps_used,
        total_steps,
        platform_name,
        holding_object,
        image_type,
        image_info_list,
        available_freespace_pair_list,
        n_image,
        image_name_list,
        location_action_list,
        show_freespace_of_object_action_list,
        n_object,
    ):
        prompt = InteractSystemState.state_prompt_helper.generate_state_prompts(
            state=InteractStates.HOLDING_OCCUPIED_PLATFORM.name.lower(),
            context={
                "scene_description": scene_description,
                "platform_list": platform_list,
                "task_description": task_description,
                "steps_used": steps_used,
                "total_steps": total_steps,
                "platform_name": platform_name,
                "holding_object": holding_object,
                "image_type": image_type,
                "image_info_list": image_info_list,
                "available_freespace_pair_list": available_freespace_pair_list,
                "location_action_list": location_action_list,
                "show_freespace_of_object_action_list": show_freespace_of_object_action_list,
                "n_image": n_image,
                "image_name_list": image_name_list,
                "n_object": n_object,
            },
        )
        return prompt


class MistakeLogGenerator:

    def __init__(
        self,
        scene_graph=None,
        task=None,
        task_id=0,
        action_history_list=None,
        state_history_list=None,
        image_path=None,
    ):

        self.scene_graph = scene_graph
        self.task = task
        self.task_id = task_id
        self.action_history_list = action_history_list
        self.mistake_logic = None
        self.state_history_list = state_history_list
        self.reflection_prompt_helper = ReflectionPromptManager(
            prompt_templates="vlm_interactor/prompts/reflection_prompts.json"
        )
        self.picture_width = 683
        self.picture_height = 384
        self.global_config = get_config()
        self.image_path = self.global_config.image4reflection_path

    @staticmethod
    def _rotated(self, action_list):
        for action in action_list:
            if action.startswith("rotate_"):
                return True
        return False
        pass

    @staticmethod
    def _place_repeatedly(self, action_list):
        place_cnt = 0
        for action in action_list:
            if action.startswith("place_at_freespace_"):
                place_cnt += 1
        return place_cnt > 2
        pass

    @staticmethod
    def _too_much_invalid_action(action_list, number=3):
        invalid_cnt = 0
        for action in action_list:
            if "invalid" in action:
                invalid_cnt += 1
        return invalid_cnt >= number
        pass

    @staticmethod
    def __attempted_place_before_looking(action_list):
        show_freespace = False
        for action in action_list:
            if action.startswith("show_freespace_of_object_"):
                show_freespace = True
            if action.startswith("place_") and not show_freespace:
                return True
        return False

    def generate_mistake_log(self):
        def judge_dict_equal_for_partial_score(dict1, dict2):

            if len(dict1) != len(dict2):
                return False
            for key, value in dict1.items():
                if key not in dict2 or dict2[key] != value and dict2[key] != "any":
                    return False

            return True

        for task in self.task.subtask_list:

            intermediate_state_list = task.intermediate_state_list
            n_score = len(intermediate_state_list)

            correct_action_list = [[] for i in range(4)]
            score = 0
            for i, status in enumerate(self.status_history_list):
                if score >= n_score + 1:
                    break
                correct_action_list[score].append(self.action_history_list[i])
                if judge_dict_equal_for_partial_score(
                    status, self.task.intermediate_state_list[self.partial_score]
                ):
                    score += 1

            current_path = self.image_path
            destination = self.task.destination
            standing_direction = 0

            for step in range(score + 1, n_score + 1 + 1):

                text_prompt = ""
                save_path = f"{current_path}/image4reflection/{self.model}/Task{self.task_id}_step_{step}.png"
                image_path_prompt_list = []
                if step == 1:
                    correct_platform_name = (
                        self.task.item.on_platform.get_name_for_interaction()
                    )
                    self.reflection_prompt_helper.generate_reflection_prompts(
                        prompt_type="goto_platform",
                        platform_name=correct_platform_name,
                    )
                    pass
                elif step == 2:
                    platform = self.task.item.on_platform
                    platform_object_name = platform.name[: platform.name.rfind("_")]
                    platform_object = self.scene_graph.nodes[platform_object_name]
                    standing_direction = platform.get_first_standing_direction()

                    platform_img, platform_img_list = (
                        self.scene_graph.auto_take_platform_picture(
                            platform_name=platform.name,
                            view="human_full",
                            mark_object=True,
                            mark_freespace=len(platform.children) == 0,
                            standing_direction=standing_direction,
                            width=self.picture_width,
                            height=self.picture_height,
                            focus_ratio=0.6,
                            save_path=save_path,
                        )
                    )

                    correct_object_name = self.task.item.get_name_for_interaction()
                    correct_object_idx = self.task.item.get_object_id_on_platform()
                    self.scene_graph.remove_node(self.task.item.name)
                    self.reflection_prompt_helper.generate_reflection_prompts(
                        prompt_type="pick_up_object",
                        object_name=correct_object_name,
                        object_idx=correct_object_idx,
                    )
                    image_path_prompt_list.extend(platform_img_list)
                    pass
                elif step == 3:
                    platform = self.task.item.on_platform
                    standing_direction = platform.get_first_standing_direction()
                    platform_img, platform_img_list = (
                        self.scene_graph.auto_take_platform_picture(
                            platform_name=platform.name,
                            view="human_full",
                            mark_object=True,
                            mark_freespace=len(platform.children) == 0,
                            standing_direction=self.standing_direction,
                            width=self.picture_width,
                            height=self.picture_height,
                            focus_ratio=0.6,
                            save_path=save_path,
                        )
                    )
                    correct_platform_name = (
                        self.task.destination.get_name_for_interaction()
                    )
                    self.reflection_prompt_helper.generate_reflection_prompts(
                        prompt_type="goto_platform",
                        platform_name=correct_platform_name,
                    )
                    image_path_prompt_list.extend(platform_img_list)
                    pass
                elif step == 4:
                    platform = self.task.destination
                    standing_direction = platform.get_first_standing_direction()
                    platform_img, platform_img_list = (
                        self.scene_graph.auto_take_platform_picture(
                            platform_name=platform.name,
                            view="human_full",
                            mark_object=True,
                            mark_freespace=len(platform.children) == 0,
                            standing_direction=self.standing_direction,
                            width=self.picture_width,
                            height=self.picture_height,
                            focus_ratio=0.6,
                            save_path=save_path,
                        )
                    )
                    image_path_prompt_list.extend(platform_img_list)

                    if self.task.type == TaskType.MOVE_TO_EMPTY_PLATFORM:
                        self.reflection_prompt_helper.generate_reflection_prompts(
                            prompt_type="place_object",
                            place_type="on_platform",
                            direction=self.task.feature[0],
                            direction_idx=NINE_DIRECTIONS.index(self.task.feature[0]),
                            object_name=self.task.item.get_name_for_interaction(),
                        )
                        pass
                    elif self.task.type == TaskType.MOVE_TO_EMPTY_PLATFORM_9_GRID:
                        platform_name = platform.get_name_for_interaction()
                        direction_id = (
                            (
                                NINE_DIRECTIONS.index(self.feature[0])
                                + standing_direction
                            )
                            % 8
                            + 1
                            if self.feature[0] != "center"
                            else 8
                        )

                        place_destination_platform_action = (
                            f"place_at_freespace_[{direction_id}]"
                        )

                        center_extend_direction_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
                        cardinal_extend_direction_list = [direction_id, 9]
                        diagonal_extend_direction_list = [
                            direction_id,
                            (direction_id + 1) % 8,
                            (direction_id + 7) % 8,
                            9,
                        ]

                        cardinal_extend_more_direction_list = [
                            direction_id,
                            (direction_id + 1) % 8,
                            (direction_id + 7) % 8,
                            (direction_id + 2) % 8,
                            (direction_id + 6) % 8,
                            9,
                        ]
                        diagonal_extend_direction_list = [
                            8 if dir == 0 else dir
                            for dir in diagonal_extend_direction_list
                        ]
                        cardinal_extend_more_direction_list = [
                            8 if dir == 0 else dir
                            for dir in cardinal_extend_more_direction_list
                        ]

                        if self.feature[0] == "center" or "-" in self.feature[0]:
                            extend_direction_list = (
                                center_extend_direction_list
                                if self.feature[0] == "center"
                                else diagonal_extend_direction_list
                            )
                            self.reflection_prompt_helper.generate_reflection_prompts(
                                prompt_type="place_object",
                                place_type="on_platform_dir_diagonal",
                                object_name=self.task.item.get_name_for_interaction(),
                                platform_name=platform_name,
                                direction=self.feature[0],
                                direction_idx=direction_id,
                                extend_direction_list=extend_direction_list,
                                place_destination_platform_action=place_destination_platform_action,
                            )
                        else:
                            self.reflection_prompt_helper.generate_reflection_prompts(
                                prompt_type="place_object",
                                place_type="on_platform_dir_cardinal",
                                object_name=self.task.item.get_name_for_interaction(),
                                platform_name=platform_name,
                                direction=self.feature[0],
                                direction_idx=direction_id,
                                extend_direction_cardinal_list=cardinal_extend_direction_list,
                                more_extending_direction_list=cardinal_extend_more_direction_list,
                                place_destination_platform_action=place_destination_platform_action,
                            )

                    elif self.task.type == TaskType.MOVE_AROUND_OBJECT:
                        dest_item_node = self.scene_graph.nodes[self.feature[0]]
                        dest_item_name = dest_item_node.get_name_for_interaction()
                        freespace_num = dest_item_node.get_num_of_critical_space()
                        dest_item_id = [
                            id
                            for id, _ in enumerate(
                                dest_item_node.get_bel_ground_platform().children
                            )
                            if _.name == self.feature[0]
                        ][0] + 1
                        adjacent_object_node_list = [
                            child
                            for child in self.task.destination.children
                            if child.depth <= 2
                            and child.get_name_for_interaction() != correct_object_name
                        ]
                        adjacent_object_name_list = [
                            child.get_name_for_interaction()
                            for child in adjacent_object_node_list
                        ]
                        adjacent_object_idx_list = [
                            child.get_object_id_on_platform()
                            for child in adjacent_object_node_list
                        ]
                        freespace_list = [
                            (dest_item_id, i) for i in range(1, freespace_num + 1)
                        ]
                        self.reflection_prompt_helper.generate_reflection_prompts(
                            prompt_type="place_object",
                            place_type="around_object",
                            freespace_list=freespace_list,
                            object_name=dest_item_name,
                            object_idx=dest_item_id,
                            adjacent_object_name_list=adjacent_object_name_list,
                            adjacent_object_idx_list=adjacent_object_idx_list,
                        )
                        self.reflection_prompt_helper.generate_reflection_prompts(
                            prompt_type="place_object",
                            place_type="around_object",
                        )
                        pass
                    elif self.task.type == TaskType.MOVE_TO_OBJECT_FREESPACE_9_GRID:
                        # dest_item_node = scene_graph.nodes[self.feature[0]]
                        # dest_item_name = dest_item_node.get_name_for_interaction()
                        # dest_item_id = [id for id, _ in enumerate(dest_item_node.get_bel_ground_platform().children) if _.name == self.feature[0]][0] + 1
                        # direction_id = ( NINE_DIRECTIONS.index(self.feature[1]) + first_standing_direction) % 8
                        # direction_id = dest_item_node.get_on_picture_freespace_id(direction_id)

                        # for i in range(4):
                        #     if (direction_id != -1):
                        #         break
                        #     first_standing_direction_id = (first_standing_direction_id + 1) % len(available_directions)
                        #     first_standing_direction = available_directions[first_standing_direction_id]
                        #     direction_id = ( NINE_DIRECTIONS.index(self.feature[1]) + first_standing_direction) % 8
                        #     direction_id = dest_item_node.get_on_picture_freespace_id(direction_id)

                        #     goal_action_list.append(f'rotate_observation_view_of_current_platform')
                        #     goal_explanation_list.append(f"rotate your observation view angle to avoid a bad and could-be-good view angle. If the view angle is getting worse, just repeat this action for at most 4 times until you find a good view angle.")
                        # if direction_id == -1:
                        #     direction_id = 2

                        # self.reflection_prompt_helper.generate_reflection_prompts(
                        #     prompt_type="place_object",
                        #     place_type='on_direction_of_object',
                        #     freespace_list=freespace_list,
                        #     object_name=dest_item_name,
                        #     object_idx=dest_item_id,
                        #     adjacent_object_name_list=adjacent_object_name_list,
                        #     adjacent_object_idx_list=adjacent_object_idx_list,

                        # )
                        pass
                    elif self.task.type == TaskType.MOVE_TO_MIDDLE_OF_OBJECTS:
                        object_name_a = self.task.feature[0]
                        object_name_b = self.task.feature[1]
                        object_node_a = [
                            child
                            for child in self.task.destination.children
                            if child.get_name_for_interaction() == object_name_a
                        ][0]
                        object_node_b = [
                            child
                            for child in self.task.destination.children
                            if child.get_name_for_interaction() == object_name_b
                        ][0]

                        while object_node_a.depth > 2:
                            object_node_a = object_node_a.parent
                        while object_node_b.depth > 2:
                            object_node_b = object_node_b.parent

                        object_idx_a = object_node_a.get_object_id_on_platform()
                        object_idx_b = object_node_b.get_object_id_on_platform()
                        adjacent_object_node_list = [
                            child
                            for child in self.task.destination.children
                            if child.depth <= 2
                            and child.get_name_for_interaction() != object_name_a
                            and child.get_name_for_interaction() != object_name_b
                        ]
                        adjacent_object_name_list = [
                            child.get_name_for_interaction()
                            for child in adjacent_object_node_list
                        ]
                        adjacent_object_idx_list = [
                            child.get_object_id_on_platform()
                            for child in adjacent_object_node_list
                        ]

                        self.reflection_prompt_helper.generate_reflection_prompts(
                            prompt_type="place_object",
                            place_type="middle_of_2_objects",
                            object_name_a=object_name_a.get_name_for_interaction(),
                            object_name_b=object_name_b.get_name_for_interaction(),
                            object_idx_a=object_idx_a,
                            object_idx_b=object_idx_b,
                            adjacent_object_name_list=adjacent_object_name_list,
                            adjacent_object_idx_list=adjacent_object_idx_list,
                        )
                        pass
                    else:
                        pass
                    # self.reflection_prompt_helper.generate_reflection_prompts(
                    #     prompt_type="show_freespace_of_object",
                    # )
                    if (
                        self.task.type == TaskType.MOVE_AROUND_OBJECT
                        or self.task.type == TaskType.MOVE_TO_OBJECT_FREESPACE_9_GRID
                    ):
                        correct_object_name4interaction = self.task.feature[0]
                        correct_object_node = [
                            child
                            for child in self.task.destination.children
                            if child.get_name_for_interaction()
                            == correct_object_name4interaction
                        ][0]

                        correct_object_name = (
                            correct_object_node.get_name_for_interaction()
                        )
                        correct_object_idx = (
                            correct_object_node.get_object_id_on_platform()
                        )

                        self.reflection_prompt_helper.generate_reflection_prompts(
                            prompt_type="on_direction_of_object",
                            object_name=correct_object_name,
                            object_idx=correct_object_idx,
                            freespace_list=freespace_list,
                        )
                    elif self.task.type == TaskType.MOVE_TO_MIDDLE_OF_OBJECTS:
                        correct_object_name4interaction = self.task.feature[0]
                        correct_object_node = [
                            child
                            for child in self.task.destination.children
                            if child.get_name_for_interaction()
                            == correct_object_name4interaction
                        ][0]

                        correct_object_name = (
                            correct_object_node.get_name_for_interaction()
                        )
                        correct_object_idx = (
                            correct_object_node.get_object_id_on_platform()
                        )
                        self.reflection_prompt_helper.generate_reflection_prompts(
                            prompt_type="pick_up_object",
                            object_name=correct_object_name,
                            object_idx=correct_object_idx,
                        )

                        correct_object_name4interaction = self.task.feature[1]
                        correct_object_node = [
                            child
                            for child in self.task.destination.children
                            if child.get_name_for_interaction()
                            == correct_object_name4interaction
                        ][0]

                        correct_object_name = (
                            correct_object_node.get_name_for_interaction()
                        )
                        correct_object_idx = (
                            correct_object_node.get_object_id_on_platform()
                        )
                        self.reflection_prompt_helper.generate_reflection_prompts(
                            prompt_type="pick_up_object",
                            object_name=correct_object_name,
                            object_idx=correct_object_idx,
                        )
                    pass
                pass

                if len(image_path_prompt_list) > 0:
                    for image_path_prompt in image_path_prompt_list:
                        self.vlm_interactor.add_content(
                            content=image_path_prompt,
                            content_type="image",
                            role="user",
                        )
                if text_prompt != "":
                    self.vlm_interactor.add_content(
                        content=text_prompt,
                        content_type="text",
                        role="user",
                    )

        if not MistakeLogGenerator._rotated(self.action_history_list[3]):
            self.reflection_prompt_helper.generate_reflection_prompts(
                prompt_type="no_rotate_hint",
                context={
                    "task_id": self.task.task_id,
                    "task_type": self.task.type,
                },
            )

        if MistakeLogGenerator._place_repeatedly(
            correct_action_list[1] + correct_action_list[2]
        ):
            if score > 2:
                self.reflection_prompt_helper.generate_reflection_prompts(
                    prompt_type="attempted_place_repeatedly_at_beginning_hint",
                    context={},
                )
            else:
                self.reflection_prompt_helper.generate_reflection_prompts(
                    prompt_type="attempted_place_repeatedly_at_end_with_wrong_item_hint",
                    action_list=correct_action_list[1] + correct_action_list[2],
                )
        if MistakeLogGenerator._too_much_invalid_action(self.action_history_list):
            self.reflection_prompt_helper.generate_reflection_prompts(
                prompt_type="too_much_invalid_action_hint",
            )

        if MistakeLogGenerator.__attempted_place_before_looking(
            self.action_history_list
        ):
            if (
                self.task.type == TaskType.MOVE_TO_MIDDLE_OF_OBJECTS
                or self.task.type == TaskType.MOVE_TO_OBJECT_FREESPACE_9_GRID
            ):
                self.reflection_prompt_helper.generate_reflection_prompts(
                    prompt_type="attempted_place_before_look_hint",
                    action_list=self.action_history_list,
                )

        pass

    def calc_intermediate_score(self):
        def judge_dict_equal_for_partial_score(dict1, dict2):

            if len(dict1) != len(dict2):
                return False
            for key, value in dict1.items():
                if key not in dict2 or dict2[key] != value and dict2[key] != "any":
                    return False

            return True

        partial_score = 0

        for i, status in enumerate(self.status_history_list):
            if partial_score >= len(self.task.intermediate_state_list):
                break
            if judge_dict_equal_for_partial_score(
                status, self.task.intermediate_state_list[partial_score]
            ):
                partial_score += 1
        self.partial_score = partial_score
        return partial_score

        pass


class BenchmarkExecutor:

    def __init__(
        self,
        scene_graph=None,
        scene=None,
        platform_list=None,
        task=None,
        task_id=None,
        intermediate_task_id=None,
        intermediate_task=None,
        vlm_interactor=None,
        model_name=None,
        debug_mode=False,
        generate_mistake_note=False,
        use_mistake_note=0,
        reflection_file_path=None,
        no_task=False,
    ):
        self.config = get_benchmark_executor_config()
        self.global_config = get_config()
        self.model = model_name
        self.scene_graph = scene_graph
        tmp_scene = self.scene_graph.corresponding_scene
        self.scene_graph.corresponding_scene = None
        self.initial_scene_graph = copy.deepcopy(scene_graph)
        self.scene_graph.corresponding_scene = tmp_scene
        self.scene = scene
        self.platform_list = scene_graph.get_sensible_platform_list()
        self.platform_name_list = [
            platform.get_name_for_interaction() for platform in self.platform_list
        ]
        self.vlm_interactor = vlm_interactor
        self.picture_width = self.config.picture_width
        self.picture_height = self.config.picture_height
        self.image_path = self.global_config.image4interaction_path
        self.at_place = -1
        self.standing_direction = 0
        self.object_in_hand = None

        self.action_history_list = []
        self.status_history_list = []

        self.state_prompt_helper = StatePromptManager(
            prompt_templates=self.global_config.benchmark_prompt_template_path
        )
        self.hint_prompt_helper = HintPromptManager(
            prompt_templates=self.global_config.benchmark_prompt_template_path
        )
        self.reflection_prompt_helper = ReflectionPromptManager(
            prompt_templates=self.global_config.reflection_prompt_template_path
        )
        self.standing_direction_while_placing = {}

        if no_task:
            self.task = None
            self.task_id = None
            self.benchmarking_mode = False

            return

        self.task = task
        # Initialize chained task system
        self.chained_task_list = []
        self.out_of_order_partial_scores = (
            []
        )  # Store max partial score for each chained task
        self.current_task_index = 0
        self.in_order_partial_scores = []  # Store max partial score for each task
        self.prohibited_objects_list = []  # Objects that cannot be moved

        # Parse task chain or single task
        if hasattr(task, "subtask_list") and task.subtask_list:
            # Task is a TaskChain
            self.chained_task_list = task.subtask_list
            self.benchmarking_mode = True
            #   self.task = self.chained_task_list[0]  # Current task
            self._update_prohibited_objects()
        else:
            # Single task or dual task mode (backward compatibility)
            self.chained_task_list = [task]
            if intermediate_task is not None:
                self.chained_task_list.insert(0, intermediate_task)
            self.benchmarking_mode = len(self.chained_task_list) > 1
            #   self.task = self.chained_task_list[0]
            self._update_prohibited_objects()

        # Initialize partial scores for all tasks
        self.in_order_partial_scores = [0] * len(self.chained_task_list)
        self.out_of_order_partial_scores = [0] * len(self.chained_task_list)

        self.task_id = task_id
        self.intermediate_task_id = intermediate_task_id
        self.intermediate_task = intermediate_task

        # Legacy dual task support
        self.is_dual_task_mode = intermediate_task is not None

        if self.benchmarking_mode:
            task_descriptions = [
                f"Task {i+1}: {task.__repr__()} "
                for i, task in enumerate(self.chained_task_list)
            ]
            self.task_description = " Then ".join(task_descriptions)
            self.task_initial_information = " ".join(
                [task.initial_state_information() for task in self.chained_task_list]
            )
        else:
            self.task_description = task.__repr__()
            self.task_initial_information = task.initial_state_information()

        self.state = InteractStates.DEFAULT

        self.reflection_file_path = reflection_file_path

        self.status = (None,)

        self.partial_score = 0
        self.debug_mode = debug_mode
        self.generate_mistake_note = generate_mistake_note
        self.use_mistake_note = use_mistake_note

    def calc_partial_score(self):
        """Calculate partial score for the main task"""

        def judge_dict_equal_for_partial_score(dict1, dict2):
            if len(dict1) != len(dict2):
                return False
            for key, value in dict1.items():
                if key not in dict2 or dict2[key] != value and dict2[key] != "any":
                    return False
            return True

        partial_score = 0
        for i, status in enumerate(self.status_history_list):
            if partial_score >= len(self.task.intermediate_state_list):
                break
            if judge_dict_equal_for_partial_score(
                status, self.task.intermediate_state_list[partial_score]
            ):
                partial_score += 1
        self.partial_score = partial_score
        return partial_score

    def calc_intermediate_task_partial_score(self):
        """Calculate partial score for the intermediate task (dual task mode only)"""

        def judge_dict_equal_for_partial_score(dict1, dict2):
            if len(dict1) != len(dict2):
                return False
            for key, value in dict1.items():
                if key not in dict2 or dict2[key] != value and dict2[key] != "any":
                    return False
            return True

        partial_score = 0
        for i, status in enumerate(self.status_history_list):
            if partial_score >= len(self.intermediate_task.intermediate_state_list):
                break
            if judge_dict_equal_for_partial_score(
                status, self.intermediate_task.intermediate_state_list[partial_score]
            ):
                partial_score += 1
        return partial_score

    def if_intermediate_task_finished(self):
        """Check if the intermediate task is completed (dual task mode only)"""

        self.intermediate_partial_score = max(
            self.intermediate_partial_score, self.calc_intermediate_task_partial_score()
        )

        if self.object_in_hand is not None:
            glog.debug("Object in hand - intermediate task not finished")
            return False

        previous_nodes = self.initial_scene_graph.nodes
        current_nodes = self.scene_graph.nodes

        for node_name, node in current_nodes.items():
            if node.depth <= 1:
                continue
            if node_name not in previous_nodes:
                glog.debug(f"{node_name} not in previous nodes")
                return False

        node = self.scene_graph.nodes[self.intermediate_task.item.name]
        node_previous = previous_nodes.get(self.intermediate_task.item.name)
        parent_previous = previous_nodes.get(
            self.intermediate_task.destination.bel_object
        )
        parent_current = current_nodes.get(
            self.intermediate_task.destination.bel_object
        )

        if (
            node is None
            or node_previous is None
            or parent_previous is None
            or parent_current is None
        ):
            glog.debug("Task item or destination not in the scene graph tree")
            return False

        if parent_previous.on_platform.name != parent_current.on_platform.name:
            glog.debug("Destination Item is changed, which is not allowed")
            return False

        if node.on_platform.name != self.intermediate_task.destination.name:
            glog.debug(
                f"Item is not on the correct platform, expected: {self.intermediate_task.destination.name}, actual: {node.on_platform.name}"
            )
            return False

        # Check task completion based on intermediate task type
        return self._check_task_completion(self.intermediate_task, node)

    def update_task_status(self):
        """Check if the main task is completed"""

        if self.object_in_hand is not None:
            glog.debug("Object in hand - task not finished")
            return False

        for task_index, chained_task in enumerate(self.chained_task_list):
            self.out_of_order_partial_scores[task_index] = max(
                self.out_of_order_partial_scores[task_index],
                self._calculate_task_partial_score(task_index)
                + self._check_task_completion(self.chained_task_list[task_index]),
            )

        if self.current_task_index < len(self.chained_task_list) - 1:
            current_task_finished = self._check_task_completion(
                self.chained_task_list[self.current_task_index]
            )
            if current_task_finished:
                self.current_task_index += 1
                glog.debug(f"Current task {self.current_task_index} finished")

    def if_task_finished(self):

        return self.current_task_index == len(
            self.chained_task_list
        ) - 1 and self._check_task_completion(self.chained_task_list[-1])

    def _check_task_completion(self, task):
        """Check task completion status for specific task type"""

        previous_nodes = self.initial_scene_graph.nodes
        current_nodes = self.scene_graph.nodes

        for node_name, node in current_nodes.items():
            if node.depth <= 1:
                continue
            if node_name not in previous_nodes:
                glog.debug(f"{node_name} not in previous nodes")
                return False

        node = self.scene_graph.nodes[task.item.name]
        node_previous = previous_nodes.get(task.item.name)
        parent_previous = previous_nodes.get(task.destination.bel_object)
        parent_current = current_nodes.get(task.destination.bel_object)

        if (
            node is None
            or node_previous is None
            or parent_previous is None
            or parent_current is None
        ):
            glog.debug("Task item or destination not in the scene graph tree")
            return False

        if parent_previous.on_platform.name != parent_current.on_platform.name:
            glog.debug("Destination Item is changed, which is not allowed")
            return False

        if node.on_platform.name != task.destination.name:
            glog.debug("Item is not on the correct platform")
            return False

        if task.type == TaskType.MOVE_TO_EMPTY_PLATFORM:
            return True
        elif task.type == TaskType.MOVE_TO_EMPTY_PLATFORM_9_GRID:
            return self._check_9_grid_placement(task)
        elif task.type == TaskType.MOVE_AROUND_OBJECT:
            return True
        elif task.type == TaskType.MOVE_TO_OBJECT_FREESPACE_9_GRID:
            return self._check_object_freespace_9_grid(task)
        elif task.type == TaskType.MOVE_TO_MIDDLE_OF_OBJECTS:
            return self._check_middle_of_objects(task)
        return False

    def _check_9_grid_placement(self, task):
        """Check if 9-grid placement is correct"""
        if task.item.name not in self.standing_direction_while_placing:
            self.standing_direction_while_placing[task.item.name] = 0

        required_direction = (NINE_DIRECTIONS.index(task.feature[0])) % 8
        if task.feature[0] == "center":
            required_direction = 8
        part = task.item.at_which_part()

        correct_direction = (
            (required_direction + self.standing_direction_while_placing[task.item.name])
            % 8
            if required_direction != 8
            else 8
        )

        if NINE_DIRECTIONS[correct_direction] in part:
            glog.info("Target object placed in correct direction.")
            return True
        else:
            glog.info(
                f"Target object placed in wrong direction, expected: {NINE_DIRECTIONS[correct_direction]}, actual: {part}"
            )
            return False

    def _check_object_freespace_9_grid(self, task):
        """Check if object freespace 9-grid placement is correct"""
        if task.item.name not in self.standing_direction_while_placing:
            self.standing_direction_while_placing[task.item.name] = 0
        destination_node = self.scene_graph.nodes[task.feature[0]]
        required_direction = (NINE_DIRECTIONS.index(task.feature[1])) % 8
        in_dir = destination_node.judge_critical_direction(task.item.name)

        correct_direction = (
            required_direction + self.standing_direction_while_placing[task.item.name]
        ) % 8

        if correct_direction in in_dir:
            glog.info("Target object placed in correct direction.")
            return True
        else:
            glog.info(
                f"Target object placed in wrong direction, expected: {NINE_DIRECTIONS[correct_direction]}, actual: {NINE_DIRECTIONS[in_dir[0]] if len(in_dir) > 0 else None}"
            )
            return False

    def _check_middle_of_objects(self, task):
        """Check if object is correctly placed between two objects"""
        if task.item.name not in self.standing_direction_while_placing:
            self.standing_direction_while_placing[task.item.name] = 0
        destination_nodea = self.scene_graph.nodes[task.feature[0]]
        destination_nodeb = self.scene_graph.nodes[task.feature[1]]

        for dira in range(8):
            dira_freespace = destination_nodea.free_space[dira]["Available_space"]
            dira_freespace = ConvexHullProcessor_2d(vertices=dira_freespace)
            is_intersect = False
            oppositing_directions = [(dira + 4) % 8]

            for dirb in oppositing_directions:
                dirb_freespace = destination_nodeb.free_space[dirb]["Available_space"]
                dirb_freespace = ConvexHullProcessor_2d(vertices=dirb_freespace)
                if (
                    dira_freespace.intersect_with_another_convex(dirb_freespace)
                    is not None
                ):
                    is_intersect = True
                    break

            dir_objects = [
                obj.name for obj in destination_nodea.free_space[dira]["Objects"]
            ]
            if is_intersect:
                glog.debug(f"{dira} and {dirb} intersect")
                if task.item.name in dir_objects:
                    glog.info("Target object placed between two items.")
                    return True
        glog.info("Target object not placed between two items.")
        return False

    def __goto_platform(self, platform_name):
        """

        Goto platform with id = platform_id.

        Args:
            platform_id (_type_): _description_
        """
        platform_id = self.platform_name_list.index(platform_name)
        self.action_history_list.append(f"goto_{self.platform_name_list[platform_id]}")
        self.at_place = platform_id
        self.standing_direction = 0
        if self.state == InteractStates.NAVIGATION:
            self.state = InteractStates.IDLE
        elif (
            self.state == InteractStates.HOLDING_EMPTY_PLATFORM
            or self.state == InteractStates.HOLDING_OCCUPIED_PLATFORM
        ):
            self.state = (
                InteractStates.HOLDING_EMPTY_PLATFORM
                if len(self.platform_list[self.at_place].children) == 0
                else InteractStates.HOLDING_OCCUPIED_PLATFORM
            )
        pass

    def __handle_ambiguous_item(self, task, task_id=0, task_order=1):
        """Handle ambiguous objects (adapted for dual tasks)"""
        if not task.is_ambiguous(self.scene_graph):
            return

        ambiguous_hint = f"For the No. {task_order} atomic task: {task.__repr__()}"
        ambiguous_hint += self.hint_prompt_helper.generate_hint_prompts(
            hint_type="identical_object_involved"
        )
        self.vlm_interactor.add_content(
            content=ambiguous_hint, content_type="text", role="user"
        )

        task.item = self.scene_graph.nodes[task.item.name]

        # Original ambiguous handling logic...
        if task.item.is_ambiguous:
            #   glog.info(f"Handling ambiguous object...{task.item.name}")
            #
            object_to_show = self.scene_graph.nodes[task.item.name]
            save_path = f"{self.image_path}/{self.model}/Task_{task_id}_{task_order}th_AmbiguousObject.png"
            img = object_to_show.auto_take_non_ground_object_picture(
                scene=self.scene_graph.corresponding_scene,
                view="human_focus",
                mark_object=False,
                only_mark_itself=False,
                mark_freespace=False,
                standing_direction=self.standing_direction,
                width=self.picture_width,
                height=self.picture_height,
                focus_ratio=0.5,
                fovy_range=[np.deg2rad(40), np.deg2rad(60)],
                save_path=save_path,
            )

            identical_object_to_move_prompt = self.state_prompt_helper.generate_certain_type_prompts(
                prompt_type="image_description",
                context={
                    "image_type": "identical_object_to_move",
                    "image_name": save_path,
                    "n_image": 1,
                    "image_name_list": [save_path],
                    "image_info_list": [
                        {
                            "image_name": save_path,
                            "source_object_name": object_to_show.get_name_for_interaction(),
                            "source_platform_name": object_to_show.get_bel_ground_platform().get_name_for_interaction(),
                        }
                    ],
                },
            )

            self.vlm_interactor.add_content(
                content=save_path, content_type="image", role="user"
            )

            self.vlm_interactor.add_content(
                content=identical_object_to_move_prompt,
                content_type="text",
                role="user",
            )

        if (
            task.type == TaskType.MOVE_AROUND_OBJECT
            or task.type == TaskType.MOVE_TO_OBJECT_FREESPACE_9_GRID
        ):
            destination_object_name = task.feature[0]
            destination_object = self.scene_graph.nodes[destination_object_name]
            if destination_object.is_ambiguous:
                save_path = f"{self.image_path}/{self.model}/Task_{self.task_id}_{task_order}th_AmbiguousDestinationObject.png"
                object_to_show = destination_object
                img = object_to_show.auto_take_non_ground_object_picture(
                    scene=self.scene_graph.corresponding_scene,
                    view="human_focus",
                    mark_object=False,
                    only_mark_itself=False,
                    mark_freespace=False,
                    standing_direction=self.standing_direction,
                    width=self.picture_width,
                    height=self.picture_height,
                    focus_ratio=0.5,
                    fovy_range=[np.deg2rad(40), np.deg2rad(60)],
                    save_path=save_path,
                )

                identical_object_destination_prompt = self.state_prompt_helper.generate_certain_type_prompts(
                    prompt_type="image_description",
                    context={
                        "image_type": "identical_object_destination",
                        "image_name": save_path,
                        "n_image": 1,
                        "image_name_list": [save_path],
                        "image_info_list": [
                            {
                                "image_name": save_path,
                                "destination_object_name": object_to_show.get_name_for_interaction(),
                                "destination_platform_name": object_to_show.get_bel_ground_platform().get_name_for_interaction(),
                            }
                        ],
                    },
                )
                self.vlm_interactor.add_content(
                    content=save_path, content_type="image", role="user"
                )

                self.vlm_interactor.add_content(
                    content=identical_object_destination_prompt,
                    content_type="text",
                    role="user",
                )
        elif task.type == TaskType.MOVE_TO_MIDDLE_OF_OBJECTS:
            destination_object_a_name, destination_object_b_name = (
                task.feature[0],
                task.feature[1],
            )
            destination_object_a, destination_object_b = (
                self.scene_graph.nodes[destination_object_a_name],
                self.scene_graph.nodes[destination_object_b_name],
            )
            if destination_object_a.is_ambiguous:
                save_path = f"{self.image_path}/{self.model}/Task_{self.task_id}_{task_order}th_AmbiguousDestinationObjectA.png"
                object_to_show = destination_object_a
                img = object_to_show.auto_take_non_ground_object_picture(
                    scene=self.scene_graph.corresponding_scene,
                    view="human_focus",
                    mark_object=False,
                    only_mark_itself=False,
                    mark_freespace=False,
                    standing_direction=self.standing_direction,
                    width=self.picture_width,
                    height=self.picture_height,
                    focus_ratio=0.5,
                    fovy_range=[np.deg2rad(40), np.deg2rad(60)],
                    save_path=save_path,
                )

                identical_object_destination_prompt = self.state_prompt_helper.generate_certain_type_prompts(
                    prompt_type="image_description",
                    context={
                        "image_type": "identical_object_destination",
                        "image_name": save_path,
                        "n_image": 1,
                        "image_name_list": [save_path],
                        "image_info_list": [
                            {
                                "image_name": save_path,
                                "destination_object_name": object_to_show.get_name_for_interaction(),
                                "destination_platform_name": object_to_show.get_bel_ground_platform().get_name_for_interaction(),
                            }
                        ],
                    },
                )
                self.vlm_interactor.add_content(
                    content=save_path, content_type="image", role="user"
                )

                self.vlm_interactor.add_content(
                    content=identical_object_destination_prompt,
                    content_type="text",
                    role="user",
                )
            if destination_object_b.is_ambiguous:
                save_path = f"{self.image_path}/{self.model}/Task_{self.task_id}_{task_order}th_AmbiguousDestinationObjectB.png"
                object_to_show = destination_object_b
                img = object_to_show.auto_take_non_ground_object_picture(
                    scene=self.scene_graph.corresponding_scene,
                    view="human_focus",
                    mark_object=False,
                    only_mark_itself=False,
                    mark_freespace=False,
                    standing_direction=self.standing_direction,
                    width=self.picture_width,
                    height=self.picture_height,
                    focus_ratio=0.5,
                    fovy_range=[np.deg2rad(40), np.deg2rad(60)],
                    save_path=save_path,
                )

                identical_object_destination_prompt = self.state_prompt_helper.generate_certain_type_prompts(
                    prompt_type="image_description",
                    context={
                        "image_type": "identical_object_destination",
                        "image_name": save_path,
                        "n_image": 1,
                        "image_name_list": [save_path],
                        "image_info_list": [
                            {
                                "image_name": save_path,
                                "destination_object_name": object_to_show.get_name_for_interaction(),
                                "destination_platform_name": object_to_show.get_bel_ground_platform().get_name_for_interaction(),
                            }
                        ],
                    },
                )
                self.vlm_interactor.add_content(
                    content=save_path, content_type="image", role="user"
                )

                self.vlm_interactor.add_content(
                    content=identical_object_destination_prompt,
                    content_type="text",
                    role="user",
                )

        pass

    def __auto_rotate_to_standable(self):
        if self.platform_bel_object is None:
            return
        prev_standing_direction = self.standing_direction
        for i in range(5):
            if len(
                self.platform.standing_point_list[self.standing_direction // 2]
            ) and self.platform.freespace_is_visible(self.standing_direction):
                break
            self.standing_direction = (self.standing_direction + 2) % 8

        glog.info(f"Standing direction is {self.standing_direction}")

    def __pickup_object(self, object_id):
        """
        Pick up object with id = object_id.
        Args:
            object_id (_type_): _description_
        """
        platform = self.platform_list[self.at_place]
        platform_bel_object = self.scene_graph.nodes[platform.bel_object]

        # Use the comprehensive prohibited objects list for chained tasks
        prohibit = (
            [] if not self.benchmarking_mode else self.prohibited_objects_list.copy()
        )

        if platform.children[object_id - 1].name in prohibit:
            attempt_moving_destination_prompt = (
                self.hint_prompt_helper.generate_hint_prompts(
                    hint_type="attempt_moving_destination_hint",
                )
            )
            self.vlm_interactor.add_content(
                content=attempt_moving_destination_prompt,
                role="user",
                content_type="text",
            )
            self.state = InteractStates.IDLE
            return 0

        self.object_in_hand = platform.children[object_id - 1]
        self.action_history_list.append(f"pickup_object_{object_id}")

        self.scene_graph.remove_node(self.object_in_hand.name)
        for i, platform in enumerate(self.platform_list):
            self.platform_list[i] = self.scene_graph.platforms[platform.name]
        self.scene_graph.update_platform_children()

        self.state = (
            InteractStates.HOLDING_EMPTY_PLATFORM
            if len(self.platform.children) == 0
            else InteractStates.HOLDING_OCCUPIED_PLATFORM
        )

        return 0

    def __place_empty_platform(self, freespace_list):
        """
        place the object on empty platform

        Args:
        The number

        """
        platform = self.platform_list[self.at_place]
        platform_bbox = platform.convex_hull_2d.get_headed_bbox_instance()

        DIRECTION_MAPPING = [
            (0, 1),
            (0, 0),
            (1, 0),
            (2, 0),
            (2, 1),
            (2, 2),
            (1, 2),
            (0, 2),
            (1, 1),
        ]

        rectangle_list = []
        for c in freespace_list:
            i, j = DIRECTION_MAPPING[int(c) - 1]
            rect = [
                platform_bbox[0]
                + i * (platform_bbox[1] - platform_bbox[0]) / 3
                + j * (platform_bbox[3] - platform_bbox[0]) / 3,
                platform_bbox[0]
                + (i + 1) * (platform_bbox[1] - platform_bbox[0]) / 3
                + j * (platform_bbox[3] - platform_bbox[0]) / 3,
                platform_bbox[0]
                + (i + 1) * (platform_bbox[1] - platform_bbox[0]) / 3
                + (j + 1) * (platform_bbox[3] - platform_bbox[0]) / 3,
                platform_bbox[0]
                + i * (platform_bbox[1] - platform_bbox[0]) / 3
                + (j + 1) * (platform_bbox[3] - platform_bbox[0]) / 3,
            ]
            rectangle_list.append(rect)

        target_object_convex = self.object_in_hand.object.convex_hull_2d
        target_object_convex.heading = platform.heading
        target_rectangle = target_object_convex.get_headed_bbox_instance()

        translation_status, translation = PlacementHelper.place_rectangle(
            moving_rect=target_rectangle,
            fixed_rect_list=rectangle_list,
        )

        if translation_status == -1:
            placement_too_small_hint = self.hint_prompt_helper.generate_hint_prompts(
                hint_type="placement_failure_area_too_small",
            )
            self.vlm_interactor.add_content(
                content=placement_too_small_hint,
                role="user",
                content_type="text",
            )
            glog.info(f"{placement_too_small_hint}")
            self.state = (
                InteractStates.HOLDING_EMPTY_PLATFORM
                if len(self.platform.children) == 0
                else InteractStates.HOLDING_OCCUPIED_PLATFORM
            )

        elif translation_status == -2:

            placement_no_intersection_hint = (
                self.hint_prompt_helper.generate_hint_prompts(
                    hint_type="placement_failure_no_intersection",
                )
            )
            self.vlm_interactor.add_content(
                content=placement_no_intersection_hint,
                role="user",
                content_type="text",
            )
            glog.info(f"{placement_no_intersection_hint}")
            self.standing_direction_while_placing[self.object_in_hand.name] = (
                self.standing_direction
            )
            self.scene_graph.add_node(
                self.object_in_hand.name,
                platform.bel_object,
                platform.name,
                translation,
            )
            self.state = InteractStates.IDLE
            for i, platform in enumerate(self.platform_list):
                self.platform_list[i] = self.scene_graph.platforms[platform.name]
            self.object_in_hand = None

        elif translation_status == 0:
            placement_made_hint = self.hint_prompt_helper.generate_hint_prompts(
                hint_type="placement_made"
            )

            self.vlm_interactor.add_content(
                content=placement_made_hint,
                role="user",
                content_type="text",
            )

            glog.info(f"{placement_made_hint}")

            self.standing_direction_while_placing[self.object_in_hand.name] = (
                self.standing_direction
            )
            self.scene_graph.add_node(
                self.object_in_hand.name,
                platform.bel_object,
                platform.name,
                translation,
            )
            self.state = InteractStates.IDLE
            for i, platform in enumerate(self.platform_list):
                self.platform_list[i] = self.scene_graph.platforms[platform.name]
            self.object_in_hand = None

        place_type = "success" if translation_status != -1 else "failure"

        self.action_history_list.append(
            f"place_empty_platform_{freespace_list}_({place_type})"
        )

        pass

    def __place_occupied_platform(self, freespace_pair_list):

        platform = self.platform_list[self.at_place]
        rectangle_list = []
        target_object_convex = self.object_in_hand.object.convex_hull_2d
        target_object_convex.heading = platform.heading
        target_rectangle = target_object_convex.get_headed_bbox_instance()

        for i in range(len(freespace_pair_list)):

            # ipdb.set_trace()
            child_id = freespace_pair_list[i][0] - 1
            if child_id >= len(self.platform_list[self.at_place].children):
                glog.info("Error: Invalid child id detected.")
                return -1
            dir_id = (
                self.platform_list[self.at_place]
                .children[child_id]
                .get_freespace_id_on_picture(freespace_pair_list[i][1])
            )

            if dir_id == -1:
                glog.info("Error: Invalid freespace id detected.")
                return -1
            rect = (
                self.platform_list[self.at_place]
                .children[child_id]
                .free_space[dir_id]["Critical_space"]
            )
            rectangle_list.append(rect)

        translation_status, translation = PlacementHelper.place_rectangle(
            moving_rect=target_rectangle,
            fixed_rect_list=rectangle_list,
        )
        #  import ipdb; ipdb.set_trace()

        if translation_status == -1:
            placement_too_small_hint = self.hint_prompt_helper.generate_hint_prompts(
                hint_type="placement_failure_area_too_small",
            )
            self.vlm_interactor.add_content(
                content=placement_too_small_hint,
                role="user",
                content_type="text",
            )
            glog.info(f"{placement_too_small_hint}")
            self.state = (
                InteractStates.HOLDING_EMPTY_PLATFORM
                if len(self.platform.children) == 0
                else InteractStates.HOLDING_OCCUPIED_PLATFORM
            )

        elif translation_status == -2:

            placement_no_intersection_hint = (
                self.hint_prompt_helper.generate_hint_prompts(
                    hint_type="placement_failure_no_intersection",
                )
            )
            self.vlm_interactor.add_content(
                content=placement_no_intersection_hint,
                role="user",
                content_type="text",
            )
            glog.info(f"{placement_no_intersection_hint}")
            self.standing_direction_while_placing[self.object_in_hand.name] = (
                self.standing_direction
            )
            self.scene_graph.add_node(
                self.object_in_hand.name,
                platform.bel_object,
                platform.name,
                translation,
            )
            self.state = InteractStates.IDLE
            self.object_in_hand = None
            for i, platform in enumerate(self.platform_list):
                self.platform_list[i] = self.scene_graph.platforms[platform.name]

        elif translation_status == 0:
            placement_made_hint = self.hint_prompt_helper.generate_hint_prompts(
                hint_type="placement_made"
            )

            self.vlm_interactor.add_content(
                content=placement_made_hint,
                role="user",
                content_type="text",
            )

            glog.info(f"{placement_made_hint}")
            self.standing_direction_while_placing[self.object_in_hand.name] = (
                self.standing_direction
            )
            self.scene_graph.add_node(
                self.object_in_hand.name,
                platform.bel_object,
                platform.name,
                translation,
            )
            self.state = InteractStates.IDLE
            self.object_in_hand = None
            for i, platform in enumerate(self.platform_list):
                self.platform_list[i] = self.scene_graph.platforms[platform.name]

        place_type = "success" if translation_status != -1 else "failure"

        self.action_history_list.append(
            f"place_occupied_platform_{freespace_pair_list}_({place_type})"
        )

        pass

    def __place_anywhere(self):

        platform = self.platform
        platform_rect = self.platform.convex_hull_2d.get_headed_bbox_instance()
        fixed_rect_list = [
            child.object.convex_hull_2d.get_headed_bbox_instance()
            for child in self.platform.children
        ]
        target_object_convex = self.object_in_hand.object.convex_hull_2d
        target_object_convex.heading = self.platform.heading
        target_rectangle = target_object_convex.get_headed_bbox_instance()

        translation_status, translation = PlacementHelper.place_rectangle_anywhere(
            moving_rect=target_rectangle,
            fixed_rect_list=fixed_rect_list,
            bound_rect=platform_rect,
        )

        if translation_status == -1:
            placement_too_small_hint = self.hint_prompt_helper.generate_hint_prompts(
                hint_type="placement_failure_area_too_small",
            )
            self.vlm_interactor.add_content(
                content=placement_too_small_hint,
                role="user",
                content_type="text",
            )

            self.state = (
                InteractStates.HOLDING_EMPTY_PLATFORM
                if len(self.platform.children) == 0
                else InteractStates.HOLDING_OCCUPIED_PLATFORM
            )
            return 0

        self.action_history_list.append("place_anywhere")

        if translation_status == 0:
            placement_made_hint = self.hint_prompt_helper.generate_hint_prompts(
                hint_type="placement_made"
            )

            self.vlm_interactor.add_content(
                content=placement_made_hint,
                role="user",
                content_type="text",
            )

            glog.info(f"{placement_made_hint}")
            self.standing_direction_while_placing[self.object_in_hand.name] = (
                self.standing_direction
            )
            self.scene_graph.add_node(
                self.object_in_hand.name,
                platform.bel_object,
                platform.name,
                translation,
            )
            self.state = InteractStates.IDLE
            self.object_in_hand = None
            for i, platform in enumerate(self.platform_list):
                self.platform_list[i] = self.scene_graph.platforms[platform.name]
            return 0
        pass

    def __rotate(self):
        """
        rotate the standing direction

        Send rotation_failed_hint if unable to rotate to another direction.
        """
        previous_standing_direction = self.standing_direction
        for i in range(4):
            self.standing_direction = (self.standing_direction + 2) % 8
            if len(self.platform.standing_point_list[self.standing_direction // 2]):
                break

        if self.standing_direction == previous_standing_direction:

            rotation_failed_hint = self.hint_prompt_helper.generate_hint_prompts(
                hint_type="rotation_failed_hint",
            )
            self.vlm_interactor.add_content(
                content=rotation_failed_hint,
                role="user",
                content_type="text",
            )

        self.action_history_list.append("rotate_observation_view_of_current_platform")

        pass

    def __show_object(self, object_id, save_path):
        """
        Show the object with id = object_id.

        Args:
            object_id (_type_): _description_
        """
        platform = self.platform_list[self.at_place]
        # import ipdb
        # ipdb.set_trace()
        if object_id > 0 and object_id <= len(platform.children):
            object_to_show = platform.children[object_id - 1]
            img = object_to_show.auto_take_non_ground_object_picture(
                scene=self.scene_graph.corresponding_scene,
                view="human_focus",
                mark_object=False,
                only_mark_itself=False,
                mark_freespace=True,
                standing_direction=self.standing_direction,
                width=self.picture_width,
                height=self.picture_height,
                focus_ratio=0.5,
                fovy_range=[np.deg2rad(40), np.deg2rad(60)],
                save_path=save_path,
            )
            if img is not None:
                show_freespace_of_object_freespace_prompt = self.state_prompt_helper.generate_certain_type_prompts(
                    prompt_type="image_description",
                    context={
                        "image_type": "show_freespace_of_object",
                        "image_name": save_path,
                        "n_image": 1,
                        "image_name_list": [save_path],
                        "image_info_list": [
                            {
                                "image_name": save_path,
                                "object_idx": object_id,
                                "freespace_num": object_to_show.get_num_of_critical_space(),
                            }
                        ],
                    },
                )

                self.vlm_interactor.add_content(
                    content=show_freespace_of_object_freespace_prompt,
                    role="user",
                    content_type="text",
                )

                self.vlm_interactor.add_content(
                    content=save_path,
                    role="user",
                    content_type="image",
                )
                self.action_history_list.append(f"show_freespace_of_object_{object_id}")
            else:
                return -1
        else:
            glog.info("Invalid object id")
            return -1

        return 0
        pass

    def apply_action(self, state=None):
        """Unified action application method"""
        if state is not None:
            self.state = state

        scene_graph = self.scene_graph
        scene = self.scene_graph.corresponding_scene
        # import ipdb; ipdb.set_trace()
        # task = self.task
        task = self.task
        platform_list = self.platform_list
        platform_name_list = self.platform_name_list = [
            platform.get_name_for_interaction() for platform in platform_list
        ]
        id = self.task_id
        current_path = self.image_path
        width, height = self.picture_width, self.picture_height

        def get_task_description():
            if self.benchmarking_mode:
                if self.state == InteractStates.NAVIGATION:
                    return (
                        self.task.__repr_rough__()
                        + self.task.initial_state_information()
                    )
                else:
                    return self.task.__repr_rough__()
            else:
                return "No task assigned."
            # if self.benchmarking_mode:
            #     return [task.__repr__() for task in self.chained_task_list]
            # elif self.is_dual_task_mode:
            #     return [self.intermediate_task.__repr__(), self.task.__repr__()]
            # else:
            #     return [self.task.__repr__()]

        while True:
            platform = self.platform = platform_list[self.at_place]
            platform_bel_object = self.platform_bel_object = (
                scene_graph.nodes[platform.bel_object] if self.at_place != -1 else None
            )

            # Enhanced task completion checking for chained tasks
            if self.benchmarking_mode:
                # Check if current task is completed
                self.update_task_status()
                if self._check_current_task_completion():
                    # Update partial score for completed task
                    current_partial_score = self.calc_current_task_partial_score()
                    self.in_order_partial_scores[self.current_task_index] = max(
                        self.in_order_partial_scores[self.current_task_index],
                        current_partial_score + 1,  # +1 for completion
                    )

                    # Try to advance to next task
                    if not self._advance_to_next_task():
                        # All tasks completed
                        glog.info("All chained tasks completed!")

                # Record status history
                self.status_history_list.append(
                    {
                        "holding": (
                            self.object_in_hand.name
                            if self.object_in_hand is not None
                            else "nothing"
                        ),
                        "at_platform": (
                            platform.get_name_for_interaction()
                            if platform is not None
                            else "none"
                        ),
                    }
                )

                # Update partial scores for all tasks during execution
                for i in range(len(self.chained_task_list)):
                    if i <= self.current_task_index:
                        # Calculate partial score for this task
                        task_partial_score = self._calculate_task_partial_score(i)
                        self.in_order_partial_scores[i] = max(
                            self.in_order_partial_scores[i], task_partial_score
                        )

            self.__auto_rotate_to_standable()

            # Check maximum interaction count
            if (
                self.vlm_interactor.interaction_count
                > self.vlm_interactor.MAX_INTERACTION_COUNT
            ):
                glog.info("Maximum interaction count reached.")
                break
            if self.state == InteractStates.NAVIGATION:

                navigation_state_prompt = NavigationState.generate_prompt(
                    scene_description="",
                    platform_list=platform_name_list,
                    task_description=get_task_description(),
                    steps_used=self.vlm_interactor.interaction_count,
                    total_steps=self.vlm_interactor.MAX_INTERACTION_COUNT,
                    location_action_list=[
                        f"goto_{platform_list[i].get_name_for_interaction()}"
                        for i in range(len(platform_list))
                    ],
                )

                navigation_state_prompt_system = navigation_state_prompt[
                    : navigation_state_prompt.find("Current task:")
                ]
                navigation_state_prompt_user = navigation_state_prompt[
                    navigation_state_prompt.find("Current task:") :
                ]
                self.vlm_interactor.add_content(
                    content=navigation_state_prompt_system,
                    role="system",
                    content_type="text",
                )

                if self.benchmarking_mode:
                    for chained_subtask in self.chained_task_list:
                        self.__handle_ambiguous_item(
                            task=chained_subtask,
                            task_id=self.task_id,
                            task_order=self.chained_task_list.index(chained_subtask)
                            + 1,
                        )

                if self.benchmarking_mode and self.use_mistake_note:
                    self._add_mistake_notes()

                self.vlm_interactor.add_content(
                    content=navigation_state_prompt_user,
                    role="user",
                    content_type="text",
                )
                status_code, choice = self.vlm_interactor.send_content_n_request()
                action_type, action_param = NavigationState.validate_action_details(
                    choice, platform_name_list
                )

                # import ipdb
                # ipdb.set_trace()
            elif self.state == InteractStates.IDLE:
                # import ipdb
                # ipdb.set_trace()  # Debugging line to inspect state
                platform_img, platform_img_list = (
                    self.scene_graph.auto_take_platform_picture(
                        platform_name=platform.name,
                        view="human_full",
                        mark_object=True,
                        mark_freespace=len(platform.children) == 0,
                        standing_direction=self.standing_direction,
                        width=width,
                        height=height,
                        focus_ratio=0.6,
                        save_path=f"{current_path}/{self.model}/Task{id}_Idle_{self.vlm_interactor.interaction_count}.png",
                    )
                )
                n_platform_img_list = len(platform_img_list)
                image_info_list = [
                    {
                        "image_name": f"{current_path}/{self.model}/Task{id}_Idle_{self.vlm_interactor.interaction_count}_{(i+1)}_out_of_{ n_platform_img_list}.png",
                        "image_type": "show_platform",
                        "platform_name": platform.get_name_for_interaction(),
                    }
                    for i in range(len(platform_img_list))
                ]
                idle_state_prompt = IdleState.generate_prompt(
                    scene_description="",
                    platform_list=platform_name_list,
                    task_description=get_task_description(),
                    steps_used=self.vlm_interactor.interaction_count,
                    total_steps=self.vlm_interactor.MAX_INTERACTION_COUNT,
                    platform_name=platform.get_name_for_interaction(),
                    holding_object=(
                        self.object_in_hand.get_name_for_interaction()
                        if self.object_in_hand is not None
                        else "nothing" if self.object_in_hand is not None else "nothing"
                    ),
                    image_type="show_platform",
                    image_info_list=image_info_list,
                    n_image=n_platform_img_list,
                    image_name_list=[
                        image_info["image_name"] for image_info in image_info_list
                    ],
                    location_action_list=[
                        f"goto_{platform_list[i].get_name_for_interaction()}"
                        for i in range(len(platform_list))
                    ],
                    object_action_list=(
                        [
                            f"pick_up_object_{i+1}_of_current_platform"
                            for i in range(len(platform.children))
                        ]
                        if len(platform.children) > 0
                        else []
                    ),
                    show_freespace_of_object_action_list=(
                        [
                            f"show_freespace_of_object_{i+1}_of_current_platform"
                            for i in range(len(platform.children))
                        ]
                        if len(platform.children) > 0
                        else []
                    ),
                )
                self.vlm_interactor.add_content(
                    content=idle_state_prompt,
                    role="user",
                    content_type="text",
                )

                for i in range(len(platform_img_list)):
                    self.vlm_interactor.add_content(
                        content=image_info_list[i]["image_name"],
                        role="user",
                        content_type="image",
                    )
                status_code, choice = self.vlm_interactor.send_content_n_request()
                self.vlm_interactor.clear_history_pictures()
                action_type, action_param = IdleState.validate_action_details(
                    action_str=choice,
                    platform_name_list=platform_name_list,
                    object_num=len(platform.children),
                )
                # import ipdb
                # ipdb.set_trace()

            elif self.state == InteractStates.HOLDING_EMPTY_PLATFORM:
                platform_img, platform_img_list = (
                    self.scene_graph.auto_take_platform_picture(
                        platform_name=platform.name,
                        view="human_full",
                        mark_object=True,
                        mark_freespace=len(platform.children) == 0,
                        standing_direction=self.standing_direction,
                        width=width,
                        height=height,
                        focus_ratio=0.6,
                        save_path=f"{current_path}/{self.model}/Task{id}_HoldingAtEmptyPlatform_{self.vlm_interactor.interaction_count}.png",
                    )
                )
                n_platform_img_list = len(platform_img_list)
                image_info_list = [
                    {
                        "image_name": f"{current_path}/{self.model}/Task{id}_HoldingAtEmptyPlatform_{self.vlm_interactor.interaction_count}_{(i+1)}_out_of_{ n_platform_img_list}.png",
                        "image_type": "show_platform",
                        "platform_name": platform.get_name_for_interaction(),
                    }
                    for i in range(len(platform_img_list))
                ]
                holding_state_prompt = HoldingEmptyPlatformState.generate_prompt(
                    scene_description="",
                    platform_list=platform_name_list,
                    task_description=get_task_description(),
                    steps_used=self.vlm_interactor.interaction_count,
                    total_steps=self.vlm_interactor.MAX_INTERACTION_COUNT,
                    platform_name=platform.get_name_for_interaction(),
                    holding_object=(
                        self.object_in_hand.get_name_for_interaction()
                        if self.object_in_hand is not None
                        else "nothing"
                    ),
                    image_type="show_platform",
                    image_info_list=image_info_list,
                    n_image=n_platform_img_list,
                    image_name_list=[
                        image_info["image_name"] for image_info in image_info_list
                    ],
                    location_action_list=[
                        f"goto_{platform_list[i].get_name_for_interaction()}"
                        for i in range(len(platform_list))
                    ],
                    show_freespace_of_object_action_list=(
                        [
                            f"show_freespace_of_object_{i+1}_of_current_platform"
                            for i in range(len(platform.children))
                        ]
                        if len(platform.children) > 0
                        else []
                    ),
                )

                self.vlm_interactor.add_content(
                    content=holding_state_prompt,
                    role="user",
                    content_type="text",
                )

                for i in range(len(platform_img_list)):
                    self.vlm_interactor.add_content(
                        content=image_info_list[i]["image_name"],
                        role="user",
                        content_type="image",
                    )
                status_code, choice = self.vlm_interactor.send_content_n_request()
                self.vlm_interactor.clear_history_pictures()
                action_type, action_param = (
                    HoldingEmptyPlatformState.validate_action_details(
                        action_str=choice,
                        platform_name_list=platform_name_list,
                        object_num=len(platform.children),
                    )
                )
                # import ipdb
                # ipdb.set_trace()
            elif self.state == InteractStates.HOLDING_OCCUPIED_PLATFORM:
                platform_img, platform_img_list = (
                    self.scene_graph.auto_take_platform_picture(
                        platform_name=platform.name,
                        view="human_full",
                        mark_object=True,
                        mark_freespace=False,
                        standing_direction=self.standing_direction,
                        width=width,
                        height=height,
                        focus_ratio=0.6,
                        save_path=f"{current_path}/{self.model}/Task{id}_HoldingOccupiedPlatformState_{self.vlm_interactor.interaction_count}.png",
                    )
                )

                n_platform_img_list = len(platform_img_list)

                image_info_list = [
                    {
                        "image_name": f"{current_path}/{self.model}/Task{id}_HoldingOccupiedPlatformState_{self.vlm_interactor.interaction_count}_{(i+1)}_out_of_{ n_platform_img_list}.png",
                        "image_type": "show_platform",
                        "platform_name": platform.get_name_for_interaction(),
                    }
                    for i in range(len(platform_img_list))
                ]

                available_freespace_pair_list = []
                for i, child in enumerate(platform.children):
                    cnt = child.get_num_of_critical_space()
                    for j in range(cnt):
                        available_freespace_pair_list.append((i + 1, j + 1))

                placement_empty_state_prompt = (
                    HoldingOccupiedPlatformState.generate_prompt(
                        scene_description="",
                        platform_list=platform_name_list,
                        task_description=get_task_description(),
                        steps_used=self.vlm_interactor.interaction_count,
                        total_steps=self.vlm_interactor.MAX_INTERACTION_COUNT,
                        platform_name=platform.get_name_for_interaction(),
                        holding_object=(
                            self.object_in_hand.get_name_for_interaction()
                            if self.object_in_hand is not None
                            else "nothing"
                        ),
                        image_type="show_platform",
                        image_info_list=image_info_list,
                        n_image=n_platform_img_list,
                        image_name_list=[
                            image_info["image_name"] for image_info in image_info_list
                        ],
                        available_freespace_pair_list=available_freespace_pair_list,
                        n_object=len(platform.children),
                        location_action_list=[
                            f"goto_{platform_list[i].get_name_for_interaction()}"
                            for i in range(len(platform_list))
                        ],
                        show_freespace_of_object_action_list=(
                            [
                                f"show_freespace_of_object_{i+1}_of_current_platform"
                                for i in range(len(platform.children))
                            ]
                            if len(platform.children) > 0
                            else []
                        ),
                    )
                )

                self.vlm_interactor.add_content(
                    content=placement_empty_state_prompt,
                    role="user",
                    content_type="text",
                )

                for i in range(len(platform_img_list)):
                    self.vlm_interactor.add_content(
                        content=image_info_list[i]["image_name"],
                        role="user",
                        content_type="image",
                    )
                status_code, choice = self.vlm_interactor.send_content_n_request()
                self.vlm_interactor.clear_history_pictures()
                action_type, action_param = (
                    HoldingOccupiedPlatformState.validate_action_details(
                        action_str=choice,
                        platform_name_list=platform_name_list,
                        object_num=len(platform.children),
                        freespace_pair_list=available_freespace_pair_list,
                    )
                )

            else:
                glog.info("Invalid state")
                break

            # import ipdb
            # ipdb.set_trace()

            if action_type == ActionType.CALL_END:
                break
            elif action_type == ActionType.NOT_AVAILABLE:
                not_available_action_hint = (
                    self.hint_prompt_helper.generate_hint_prompts(
                        hint_type="not_available_action_hint",
                    )
                )
                self.vlm_interactor.add_content(
                    content=not_available_action_hint, role="user", content_type="text"
                )
            elif action_type == ActionType.PLACE_IDLE:
                placement_failure_idle_hint = (
                    self.hint_prompt_helper.generate_hint_prompts(
                        hint_type="placement_failure_idle",
                    )
                )
                self.vlm_interactor.add_content(
                    content=placement_failure_idle_hint,
                    role="user",
                    content_type="text",
                )

            elif action_type == ActionType.GOTO_PLATFORM:
                self.__goto_platform(action_param)
            elif action_type == ActionType.PICKUP_OBJECT:
                self.__pickup_object(action_param)
            elif action_type == ActionType.PLACE_EMPTY:
                self.__place_empty_platform(action_param)
            elif action_type == ActionType.PLACE_OCCUPIED:
                self.__place_occupied_platform(action_param)
            elif action_type == ActionType.PLACE_ANYWHERE:
                self.__place_anywhere()
            elif action_type == ActionType.ROTATE:
                self.__rotate()
            elif action_type == ActionType.SHOW_OBJECT:
                self.__show_object(
                    action_param,
                    save_path=f"{current_path}/{self.model}/Task{id}_ShowObject_object_{self.vlm_interactor.interaction_count}.png",
                    # f"{current_path}/image4interact/{self.model}/Task{id}_ShowObject_object_{self.vlm_interactor.interaction_count}.png",
                )

            else:
                self.action_history_list.append(f"**invalid_action**")
                invalid_action_hint = self.hint_prompt_helper.generate_hint_prompts(
                    hint_type="invalid_action_hint",
                )
                self.vlm_interactor.add_content(
                    content=invalid_action_hint, role="user", content_type="text"
                )
                glog.info("Invalid action type")

        if not self.benchmarking_mode:
            return True, None

        self.update_task_status()
        self.status = self.if_task_finished()

        reflection_conversation_list = []

        if not self.status and self.generate_mistake_note:
            self.scene_graph = self.initial_scene_graph
            self.scene_graph.corresponding_scene = self.scene

            def judge_dict_equal_for_partial_score(dict1, dict2):

                if len(dict1) != len(dict2):
                    return False
                for key, value in dict1.items():
                    if key not in dict2 or dict2[key] != value and dict2[key] != "any":
                        return False

                return True

            for task in self.task.subtask_list:
                intermediate_state_list = task.intermediate_state_list
                state_history_list = self.status_history_list
                n_score = len(intermediate_state_list)
                correct_action_list = [[] for i in range(4)]
                self.status_history_list = self.status_history_list[1:]
                score = 0
                for i, status in enumerate(self.status_history_list):
                    if score >= n_score or i >= len(self.action_history_list):
                        break
                    correct_action_list[score].append(self.action_history_list[i])
                    if judge_dict_equal_for_partial_score(
                        status, task.intermediate_state_list[score]
                    ):
                        score += 1

                goal_action_list, goal_explanation_list, goal_picture_list = (
                    task.generate_goal_information(
                        scene_graph=self.scene_graph,
                        current_path=self.image_path,
                        id=self.task_id,
                    )
                )

                def judge_dict_equal_for_partial_score(dict1, dict2):

                    if len(dict1) != len(dict2):
                        return False
                    for key, value in dict1.items():
                        if (
                            key not in dict2
                            or dict2[key] != value
                            and dict2[key] != "any"
                        ):
                            return False

                    return True

                intermediate_state_list = task.intermediate_state_list
                n_score = len(intermediate_state_list)

                correct_action_list = [[] for i in range(4)]
                score = 0
                for i, status in enumerate(self.status_history_list):
                    if score >= n_score or i >= len(self.action_history_list):
                        break
                    correct_action_list[score].append(self.action_history_list[i])
                    if judge_dict_equal_for_partial_score(
                        status, task.intermediate_state_list[score]
                    ):
                        score += 1

                correct_action_list[score] = []

                action_list = []
                for i, actions in enumerate(correct_action_list):
                    if len(actions) > 0:
                        action_list.extend(actions)

                task.generate_default_intermediate_state()

                mistake_note_prompt = f"We also provide a subtask you had failed in another scene, including the steps you've made and a correct way to finish the task. Each action step includes the images you will see when making that decision. You can learn from it to better finish the coming task. The task is: {self.task.__repr_rough__()}, and your action history list is: {self.action_history_list}"

                partial_score_prompt = (
                    self.reflection_prompt_helper.generate_reflection_prompt(
                        prompt_type="partial_score",
                        action_list=action_list,
                        correct_state_list=task.intermediate_state_repr_list[:score],
                        failed_state_list=task.intermediate_state_repr_list[score:],
                    )
                )

                one_possible_correct_answer_prompt = (
                    self.reflection_prompt_helper.generate_reflection_prompt(
                        prompt_type="one_possible_correct_answer",
                        solution_list="",
                        failed_state_list=task.intermediate_state_repr_list[score:],
                    )
                )

                reflection_conversation_list.append(
                    {
                        "role": "system",
                        "content": mistake_note_prompt,
                        "content_type": "text",
                    }
                )

                reflection_conversation_list.append(
                    {
                        "role": "system",
                        "content": partial_score_prompt,
                        "content_type": "text",
                    }
                )

                reflection_conversation_list.append(
                    {
                        "role": "system",
                        "content": one_possible_correct_answer_prompt,
                        "content_type": "text",
                    }
                )

                n = len(goal_action_list)
                for i in range(score, n):

                    for goal_picture in goal_picture_list[i]:
                        reflection_conversation_list.append(
                            {
                                "role": "system",
                                "content": goal_picture,
                                "content_type": "image",
                            }
                        )

                    reflection_conversation_list.append(
                        {
                            "role": "system",
                            "content": goal_explanation_list[i],
                            "content_type": "text",
                        }
                    )
                    reflection_conversation_list.append(
                        {
                            "role": "system",
                            "content": f"choose action: {goal_action_list[i]}",
                            "content_type": "text",
                        }
                    )
                    pass

            def write_reflection_to_file(
                reflection_conversation_list,
                filename=self.global_config.reflection_txt_save_path,
            ):

                try:
                    os.makedirs(os.path.dirname(filename), exist_ok=True)
                    with open(filename, "a", encoding="utf-8") as f:
                        # Use json.dumps to convert the entire list to a single-line JSON string
                        json_str = json.dumps(
                            reflection_conversation_list, ensure_ascii=False
                        )
                        f.write(
                            json_str + "\n"
                        )  # Add newline to separate different records
                except Exception as e:
                    print(f"Error writing to file: {e}")

            write_reflection_to_file(reflection_conversation_list)
            # import ipdb
            # ipdb.set_trace()
            pass

        self.partial_score = sum(self.out_of_order_partial_scores)
        print(
            self.status,
            f"{self.partial_score}/{len(self.task.subtask_list)*(len(self.task.subtask_list[0].intermediate_state_list) + 1)}",
        )
        return self.status, self.partial_score

    def _add_mistake_notes(self):
        """Add mistake notes"""

        def read_reflections_from_file(
            filename=self.global_config.reflection_txt_load_path,
        ):
            reflections = []
            try:
                with open(filename, "r", encoding="utf-8") as f:
                    for line in f:
                        if line.strip():
                            reflections.append(json.loads(line))
                return reflections
            except Exception as e:
                glog.error(
                    f"Error reading file: {e}. Using empty reflections in this run."
                )
                return []

        if self.use_mistake_note:
            reflections = read_reflections_from_file()
            note_num = 0
            for reflection_list in reflections:
                for reflection in reflection_list:
                    if isinstance(reflection["content"], list):
                        for content in reflection["content"]:
                            self.vlm_interactor.add_content(
                                content=content,
                                role="user",
                                content_type=reflection["content_type"],
                            )
                    elif isinstance(reflection["content"], str):
                        self.vlm_interactor.add_content(
                            content=reflection["content"],
                            role="user",
                            content_type=reflection["content_type"],
                        )
                note_num += 1
                if note_num >= self.use_mistake_note:
                    break

    def _update_prohibited_objects(self):
        """Update the list of objects that cannot be moved based on all tasks in the chain"""
        self.prohibited_objects_list = []

        for task in self.chained_task_list:
            if (
                task.type == TaskType.MOVE_AROUND_OBJECT
                or task.type == TaskType.MOVE_TO_OBJECT_FREESPACE_9_GRID
            ):
                if hasattr(task, "feature") and len(task.feature) > 0:
                    self.prohibited_objects_list.append(task.feature[0])
            elif task.type == TaskType.MOVE_TO_MIDDLE_OF_OBJECTS:
                if hasattr(task, "feature") and len(task.feature) >= 2:
                    self.prohibited_objects_list.extend(task.feature[:2])

    def _check_current_task_completion(self):
        """Check if the current task in the chain is completed"""
        if self.current_task_index >= len(self.chained_task_list):
            return False

        current_task = self.chained_task_list[self.current_task_index]

        # Use existing task completion logic
        if self.object_in_hand is not None:
            return False

        previous_nodes = self.initial_scene_graph.nodes
        current_nodes = self.scene_graph.nodes

        for node_name, node in current_nodes.items():
            if node.depth <= 1:
                continue
            if node_name not in previous_nodes:
                return False

        node = self.scene_graph.nodes.get(current_task.item.name)
        if node is None:
            return False

        if node.on_platform.name != current_task.destination.name:
            return False

        return self._check_task_completion(current_task)

    def _advance_to_next_task(self):
        """Advance to the next task in the chain"""
        if self.current_task_index < len(self.chained_task_list) - 1:
            # Update partial score for current task (take maximum)
            current_partial_score = self.calc_current_task_partial_score()
            self.in_order_partial_scores[self.current_task_index] = max(
                self.in_order_partial_scores[self.current_task_index],
                current_partial_score,
            )

            self.current_task_index += 1
            return True
        return False

    def calc_current_task_partial_score(self):
        """Calculate partial score for the current task in the chain"""

        def judge_dict_equal_for_partial_score(dict1, dict2):
            if len(dict1) != len(dict2):
                return False
            for key, value in dict1.items():
                if key not in dict2 or dict2[key] != value and dict2[key] != "any":
                    return False
            return True

        current_task = self.chained_task_list[self.current_task_index]
        partial_score = 0

        for i, status in enumerate(self.status_history_list):
            if partial_score >= len(current_task.intermediate_state_list):
                break
            if judge_dict_equal_for_partial_score(
                status, current_task.intermediate_state_list[partial_score]
            ):
                partial_score += 1

        return partial_score

    def _calculate_task_partial_score(self, task_index):
        """Calculate partial score for a specific task in the chain"""
        if task_index >= len(self.chained_task_list):
            return 0

        def judge_dict_equal_for_partial_score(dict1, dict2):
            if len(dict1) != len(dict2):
                return False
            for key, value in dict1.items():
                if key not in dict2 or dict2[key] != value and dict2[key] != "any":
                    return False
            return True

        task = self.chained_task_list[task_index]
        partial_score = 0

        for i, status in enumerate(self.status_history_list):
            if partial_score >= len(task.intermediate_state_list):
                break
            if judge_dict_equal_for_partial_score(
                status, task.intermediate_state_list[partial_score]
            ):
                partial_score += 1

        return partial_score

    def get_final_scores(self):
        """Get final scores for all tasks in the chain"""
        if self.benchmarking_mode:
            # For chained tasks, return the maximum partial score achieved for each task
            final_scores = []
            for i, task in enumerate(self.chained_task_list):
                max_score = max(
                    self.in_order_partial_scores[i],
                    self._calculate_task_partial_score(i),
                )
                # Add completion bonus if task was completed
                if i < self.current_task_index or (
                    i == self.current_task_index
                    and self._check_current_task_completion()
                ):
                    max_score = min(
                        max_score + 1, len(task.intermediate_state_list) + 1
                    )
                final_scores.append(max_score)
            return final_scores
        else:
            # For single task or dual task mode, use existing logic
            if self.is_dual_task_mode:
                return [
                    getattr(self, "intermediate_partial_score", 0),
                    self.partial_score,
                ]
            else:
                return [self.partial_score]


def main():
    pass
    benchmark_executor = BenchmarkExecutor()