goaprs 0.2.1

Goal Oriented Action Planning implementation in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
//! Automaton module implements the core GOAP (Goal-Oriented Action Planning) finite state machine.
//!
//! This module provides the Automaton and AutomatonController classes which handle:
//! - Sensing the environment using sensors
//! - Planning actions to achieve goals
//! - Executing actions based on the plan
//! - Maintaining world state and working memory
//!
//! The automaton follows a continuous cycle of sensing, planning, and acting to achieve its goals.

//! Automaton module implements the core GOAP (Goal-Oriented Action Planning) finite state machine.
//!
//! This module provides the Automaton and AutomatonController classes which handle:
//! - Sensing the environment using sensors
//! - Planning actions to achieve goals
//! - Executing actions based on the plan
//! - Maintaining world state and working memory
//!
//! The automaton follows a continuous cycle of sensing, planning, and acting to achieve its goals.

use async_trait::async_trait;
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use tokio::sync::Mutex;

use crate::action::ActionResponse;
use crate::error::Result;
use crate::planner::Planner;
use crate::world_state::WorldState;
use crate::Action;
use crate::Sensor;

/// Represents a fact gathered from the environment.
///
/// Facts are produced by sensors and stored in the working memory of the automaton.
/// Each fact has a binding key, data value, timestamp, and reference to the parent sensor.
///
/// # Examples
///
/// ```
/// use goaprs::utils::automaton::Fact;
///
/// let fact = Fact::new("temperature", "72.5", "temperature_sensor");
/// assert_eq!(fact.binding(), "temperature");
/// assert_eq!(fact.data(), "72.5");
/// assert_eq!(fact.parent_sensor(), "temperature_sensor");
/// ```
///
/// Facts are produced by sensors and stored in the working memory of the automaton.
/// Each fact has a binding key, data value, timestamp, and reference to the parent sensor.
///
/// # Examples
///
/// ```
/// use goaprs::utils::automaton::Fact;
///
/// let fact = Fact::new("temperature", "72.5", "temperature_sensor");
/// assert_eq!(fact.binding(), "temperature");
/// assert_eq!(fact.data(), "72.5");
/// assert_eq!(fact.parent_sensor(), "temperature_sensor");
/// ```
#[derive(Debug, Clone)]
pub struct Fact {
    /// The binding key for the fact
    binding: String,
    /// The data of the fact
    data: String,
    /// When this fact was observed
    timestamp: SystemTime,
    /// The parent sensor that produced this fact
    parent_sensor: String,
}

impl Fact {
    /// Creates a new fact with the given binding, data, and parent sensor.
    ///
    /// The fact is automatically timestamped with the current system time.
    ///
    /// # Arguments
    ///
    /// * `binding` - The key that identifies what the fact represents
    /// * `data` - The actual value or information of the fact
    /// * `parent_sensor` - The name of the sensor that produced this fact
    ///
    /// # Returns
    ///
    /// A new `Fact` instance
    pub fn new(
        binding: impl Into<String>,
        data: impl Into<String>,
        parent_sensor: impl Into<String>,
    ) -> Self {
        Self {
            binding: binding.into(),
            data: data.into(),
            timestamp: SystemTime::now(),
            parent_sensor: parent_sensor.into(),
        }
    }

    /// Gets the binding key of this fact.
    ///
    /// The binding key identifies what the fact represents in the world state.
    ///
    /// # Returns
    ///
    /// A string slice containing the binding key
    pub fn binding(&self) -> &str {
        &self.binding
    }

    /// Gets the data value of this fact.
    ///
    /// # Returns
    ///
    /// A string slice containing the fact's data
    pub fn data(&self) -> &str {
        &self.data
    }

    /// Gets the timestamp when this fact was created.
    ///
    /// # Returns
    ///
    /// The `SystemTime` when this fact was created
    pub fn timestamp(&self) -> SystemTime {
        self.timestamp
    }

    /// Gets the name of the parent sensor that produced this fact.
    ///
    /// # Returns
    ///
    /// A string slice containing the parent sensor's name
    pub fn parent_sensor(&self) -> &str {
        &self.parent_sensor
    }
}

impl fmt::Display for Fact {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.binding, self.data)
    }
}

/// States of the automaton's finite state machine.
///
/// The automaton cycles through these states as it operates:
/// 1. `WaitingOrders`: Idle state, waiting for a goal to be set
/// 2. `Sensing`: Gathering information from the environment
/// 3. `Planning`: Generating an action plan to achieve the goal
/// 4. `Acting`: Executing the planned actions
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
    /// Waiting for orders - idle state before receiving goals
    WaitingOrders,
    /// Sensing the environment - gathering data from sensors
    Sensing,
    /// Planning actions - determining sequence of actions to reach goal
    Planning,
    /// Acting on the plan - executing planned actions
    Acting,
}

/// Trait for action functionality

#[async_trait]
pub trait ActionFn: Send + Sync {
    /// Executes the action and returns success or failure
    async fn exec(&self, world_state: &HashMap<String, Fact>) -> bool;
}

/// A finite state machine automaton that manages the GOAP (Goal-Oriented Action Planning) process.
///
/// The automaton is the core component of the GOAP system. It:
/// - Maintains the current world state and goal state
/// - Collects facts from sensors into working memory
/// - Plans actions to transition from the current state to the goal state
/// - Executes actions according to the plan
///
/// The automaton follows a cycle of sensing, planning, and acting to achieve its goals.
///
/// # Thread Safety
///
/// The automaton is designed to be thread-safe with internal state protected by `Arc<Mutex<>>`.
pub struct Automaton {
    /// Gets the name of the automaton.
    ///
    /// # Returns
    ///
    /// A string slice containing the automaton's name
    name: String,
    /// The current state of the automaton's finite state machine
    state: Arc<Mutex<State>>,
    /// The current world state (key-value pairs representing the environment)
    world_state: Arc<Mutex<WorldState>>,
    /// The goal state the automaton is trying to achieve
    goal: Arc<Mutex<WorldState>>,
    /// The working memory containing facts gathered from sensors
    working_memory: Arc<Mutex<Vec<Fact>>>,
    /// Collection of sensors used to gather information from the environment
    sensors: Vec<Sensor>,
    /// Collection of available actions the automaton can perform
    #[allow(dead_code)]
    actions: Vec<Action>,
    /// The planner used to generate action sequences
    planner: Planner,
    /// The current action plan being executed
    action_plan: Arc<Mutex<Vec<crate::action::Action>>>,
}

impl Automaton {
    /// Creates a new automaton with the given name, sensors, actions, and initial world state.
    ///
    /// # Arguments
    ///
    /// * `name` - A name for the automaton
    /// * `sensors` - The collection of sensors the automaton will use to gather information
    /// * `actions` - The collection of actions the automaton can perform
    /// * `world_state_facts` - Initial key-value pairs representing the starting world state
    ///
    /// # Returns
    ///
    /// A new `Automaton` instance initialized with the provided components and in the `WaitingOrders` state
    ///
    /// # Examples
    ///
    /// ```
    /// use std::collections::HashMap;
    /// use goaprs::utils::automaton::{Automaton};
    /// use goaprs::sensor::Sensor;
    /// use goaprs::action::Action;
    ///
    /// let sensors = Vec::<Sensor>::new();
    /// let actions = Vec::<Action>::new();
    /// let mut initial_state = HashMap::new();
    /// initial_state.insert("location".to_string(), "home".to_string());
    ///
    /// let automaton = Automaton::new("home_assistant", sensors, actions, initial_state);
    /// ```
    pub fn new(
        name: impl Into<String>,
        sensors: Vec<Sensor>,
        actions: Vec<Action>,
        world_state_facts: HashMap<String, String>,
    ) -> Self {
        Self {
            name: name.into(),
            state: Arc::new(Mutex::new(State::WaitingOrders)),
            world_state: Arc::new(Mutex::new(WorldState::from_hashmap(world_state_facts))),
            goal: Arc::new(Mutex::new(WorldState::new())),
            working_memory: Arc::new(Mutex::new(Vec::new())),
            sensors: sensors,
            actions: actions.clone(),
            planner: Planner::new(actions),
            action_plan: Arc::new(Mutex::new(Vec::new())),
        }
    }

    /// Gets the name of the automaton.
    ///
    /// # Returns
    ///
    /// A string slice containing the automaton's name
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Gets the current state of the automaton's finite state machine.
    ///
    /// # Returns
    ///
    /// A `Result` containing the current `State` of the automaton
    ///
    /// # Errors
    ///
    /// Returns an error if the state mutex is poisoned
    pub async fn state(&self) -> Result<State> {
        let state_lock = self.state.lock().await;
        Ok(*state_lock)
    }

    /// Sets the goal state for the automaton.
    ///
    /// When a new goal is set, the automaton transitions to the `WaitingOrders` state,
    /// preparing for a new sense-plan-act cycle.
    ///
    /// # Arguments
    ///
    /// * `goal` - A HashMap of key-value pairs representing the desired goal state
    ///
    /// # Returns
    ///
    /// A `Result` indicating success or failure
    ///
    /// # Errors
    ///
    /// Returns an error if either the goal or state mutex is poisoned
    pub async fn set_goal(&self, goal: HashMap<String, String>) -> Result<()> {
        // Update goal
        {
            let mut goal_lock = self.goal.lock().await;
            *goal_lock = WorldState::from_hashmap(goal);
        }

        // When setting a goal, transition to waiting orders
        {
            let mut state_lock = self.state.lock().await;
            *state_lock = State::WaitingOrders;
        }

        Ok(())
    }

    /// Gets the current goal state from the managed automaton.
    ///
    /// # Returns
    ///
    /// A `Result` containing the current goal `WorldState`
    ///
    /// # Errors
    ///
    /// Returns an error if retrieving the goal state fails
    ///
    /// # Returns
    ///
    /// A `Result` containing a clone of the current `WorldState`
    ///
    /// # Errors
    ///
    /// Returns an error if the world state mutex is poisoned
    ///
    /// # Returns
    ///
    /// A `Result` containing a clone of the current goal `WorldState`
    ///
    /// # Errors
    ///
    /// Returns an error if the goal mutex is poisoned
    ///
    /// # Returns
    ///
    /// A `Result` containing a clone of the current goal `WorldState`
    ///
    /// # Errors
    ///
    /// Returns an error if the goal mutex is poisoned
    pub async fn goal(&self) -> Result<WorldState> {
        let goal_lock = self.goal.lock().await;
        Ok(goal_lock.clone())
    }

    /// Gets the current world state from the managed automaton.
    ///
    /// # Returns
    ///
    /// A `Result` containing the current `WorldState`
    ///
    /// # Errors
    ///
    /// Returns an error if retrieving the world state fails
    ///
    /// # Returns
    ///
    /// A `Result` containing a clone of the current `WorldState`
    ///
    /// # Errors
    ///
    /// Returns an error if the world state mutex is poisoned
    pub async fn world_state(&self) -> Result<WorldState> {
        let world_state_lock = self.world_state.lock().await;
        Ok(world_state_lock.clone())
    }

    /// Transitions to the sensing state and gathers data from all sensors.
    ///
    /// This method:
    /// 1. Changes the automaton state to `Sensing`
    /// 2. Clears the current working memory
    /// 3. Executes each sensor and stores results as facts in working memory
    /// 4. Updates the world state with the gathered facts
    ///
    /// # Returns
    ///
    /// A `Result` indicating success or failure
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Any mutex is poisoned
    /// - Any sensor execution fails
    ///
    /// # Examples
    ///
    /// ```
    /// # async fn example(automaton: &goaprs::utils::automaton::Automaton) -> Result<(), Box<dyn std::error::Error>> {
    /// // Gather information from all sensors
    /// automaton.sense().await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// This method:
    /// 1. Changes the automaton state to `Sensing`
    /// 2. Clears the current working memory
    /// 3. Executes each sensor and stores results as facts in working memory
    /// 4. Updates the world state with the gathered facts
    ///
    /// # Returns
    ///
    /// A `Result` indicating success or failure
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Any mutex is poisoned
    /// - Any sensor execution fails
    ///
    /// # Examples
    ///
    /// ```
    /// # async fn example(automaton: &goaprs::utils::automaton::Automaton) -> Result<(), Box<dyn std::error::Error>> {
    /// // Gather information from all sensors
    /// automaton.sense().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn sense(&self) -> Result<()> {
        // Change state to sensing
        {
            let mut state_lock = self.state.lock().await;
            *state_lock = State::Sensing;
        }

        // Clear the working memory
        {
            let mut working_memory = self.working_memory.lock().await;
            working_memory.clear();
        }

        // Run each sensor and update the working memory
        for sensor in self.sensors.iter() {
            let response = sensor.exec().await?;

            // Add the fact to working memory
            {
                let mut working_memory = self.working_memory.lock().await;
                working_memory.push(Fact::new(
                    sensor.binding(),
                    response.response(),
                    sensor.name(),
                ));
            }
        }

        // Update the world state with the facts
        {
            // Get facts from working memory first
            let facts: Vec<Fact> = {
                let working_memory = self.working_memory.lock().await;
                working_memory.clone()
            };

            // Then update world state with collected facts
            let mut world_state = self.world_state.lock().await;
            for fact in facts.iter() {
                world_state.insert(fact.binding().to_string(), fact.data().to_string());
            }
        }

        Ok(())
    }

    /// Transitions to the planning state and generates an action plan to reach the goal.
    ///
    /// This method:
    /// 1. Changes the automaton state to `Planning`
    /// 2. Uses the planner to find a sequence of actions that will transition from
    ///    the current world state to the goal state
    /// 3. Stores the generated plan for later execution
    ///
    /// # Returns
    ///
    /// A `Result` containing the generated action plan as a vector of `Action`s
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Any mutex is poisoned
    /// - The planner fails to generate a valid plan
    ///
    /// # Examples
    ///
    /// ```
    /// # async fn example(automaton: &goaprs::utils::automaton::Automaton) -> Result<(), Box<dyn std::error::Error>> {
    /// // Create a plan to achieve a goal
    /// let plan = automaton.plan().await?;
    /// println!("Generated plan with {} actions", plan.len());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn plan(&self) -> Result<Vec<crate::action::Action>> {
        // Set state to Planning
        {
            let mut state_lock = self.state.lock().await;
            *state_lock = State::Planning;
        }

        // Get world state and goal state
        let world_hash: HashMap<String, String>;
        let goal_hash: HashMap<String, String>;

        {
            let world_state = self.world_state.lock().await;
            world_hash = world_state
                .iter()
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect();
        }

        {
            let goal = self.goal.lock().await;
            goal_hash = goal.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
        }

        // Convert HashMaps to State objects
        let mut current_state = crate::state::State::new();
        for (k, v) in world_hash.iter() {
            current_state.set(k, v == "true");
        }

        let mut goal_state = crate::state::State::new();
        for (k, v) in goal_hash.iter() {
            goal_state.set(k, v == "true");
        }

        // Generate plan
        let planner = self.planner.clone();
        let plan = planner.plan(&current_state, &goal_state)?;

        // Store the action plan
        {
            let mut action_plan = self.action_plan.lock().await;
            *action_plan = plan.clone();
        }

        Ok(plan)
    }

    /// Transitions to the acting state and executes the current action plan.
    ///
    /// This method:
    /// 1. Changes the automaton state to `Acting`
    /// 2. Executes each action in the previously generated plan in sequence
    /// 3. Collects and returns the responses from each action
    ///
    /// # Returns
    ///
    /// A `Result` containing a vector of `ActionResponse`s from executed actions
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Any mutex is poisoned
    /// - Any action execution fails
    ///
    /// # Examples
    ///
    /// ```
    /// # async fn example(automaton: &goaprs::utils::automaton::Automaton) -> Result<(), Box<dyn std::error::Error>> {
    /// // Execute the current action plan
    /// let responses = automaton.act().await?;
    /// for (i, response) in responses.iter().enumerate() {
    ///     println!("Action {}: {}", i, response);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// This method:
    /// 1. Changes the automaton state to `Acting`
    /// 2. Executes each action in the previously generated plan in sequence
    /// 3. Collects and returns the responses from each action
    ///
    /// # Returns
    ///
    /// A `Result` containing a vector of `ActionResponse`s from executed actions
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Any mutex is poisoned
    /// - Any action execution fails
    ///
    /// # Examples
    ///
    /// ```
    /// # async fn example(automaton: &goaprs::utils::automaton::Automaton) -> Result<(), Box<dyn std::error::Error>> {
    /// // Execute the current action plan
    /// let responses = automaton.act().await?;
    /// for (i, response) in responses.iter().enumerate() {
    ///     println!("Action {}: {}", i, response);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn act(&self) -> Result<Vec<ActionResponse>> {
        // Set state to Acting
        {
            let mut state_lock = self.state.lock().await;
            *state_lock = State::Acting;
        }

        // Get action plan
        let actions_to_execute = {
            let action_plan = self.action_plan.lock().await;
            action_plan.clone()
        };

        let mut responses = Vec::new();

        // Execute each action in the plan
        for action in actions_to_execute.iter() {
            let response = action.exec().await?;
            responses.push(response.clone());
        }

        Ok(responses)
    }

    /// Transitions to the waiting orders state.
    ///
    /// This method:
    /// 1. Changes the automaton state to `WaitingOrders`
    /// 2. Clears the working memory
    ///
    /// This state indicates the automaton has either completed its goal or
    /// is waiting for a new goal to be set.
    ///
    /// # Returns
    ///
    /// A `Result` indicating success or failure
    ///
    /// # Errors
    ///
    /// Returns an error if any mutex is poisoned
    ///
    /// This method:
    /// 1. Changes the automaton state to `WaitingOrders`
    /// 2. Clears the working memory
    ///
    /// This state indicates the automaton has either completed its goal or
    /// is waiting for a new goal to be set.
    ///
    /// # Returns
    ///
    /// A `Result` indicating success or failure
    ///
    /// # Errors
    ///
    /// Returns an error if any mutex is poisoned
    pub async fn wait(&self) -> Result<()> {
        // Set state to WaitingOrders
        {
            let mut state_lock = self.state.lock().await;
            *state_lock = State::WaitingOrders;
        }

        // Clear the working memory
        {
            let mut working_memory = self.working_memory.lock().await;
            working_memory.clear();
        }

        Ok(())
    }
}

/// A controller that runs the automaton in a continuous loop.
///
/// The AutomatonController manages an Automaton instance, running its sense-plan-act
/// cycle in a separate thread. It provides methods to start and stop the automaton's
/// execution, as well as to set goals and access state information.
///
/// # Examples
///
/// ```
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use std::collections::HashMap;
/// use goaprs::utils::automaton::AutomatonController;
/// use goaprs::sensor::Sensor;
/// use goaprs::action::Action;
///
/// let sensors = Vec::<Sensor>::new();
/// let actions = Vec::<Action>::new();
/// let mut world_state = HashMap::new();
/// world_state.insert("location".to_string(), "home".to_string());
///
/// let controller = AutomatonController::new(actions, sensors, "home_assistant", world_state);
///
/// // Set a goal
/// let mut goal = HashMap::new();
/// goal.insert("lights".to_string(), "on".to_string());
/// controller.set_goal(goal).await?;
///
/// // Start the automaton
/// controller.start().await?;
///
/// // Later, stop the automaton
/// controller.stop().await?;
/// # Ok(())
/// # }
/// ```
///
/// The AutomatonController manages an Automaton instance, running its sense-plan-act
/// cycle in a separate thread. It provides methods to start and stop the automaton's
/// execution, as well as to set goals and access state information.
///
/// # Examples
///
/// ```
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use std::collections::HashMap;
/// use goaprs::utils::automaton::AutomatonController;
/// use goaprs::sensor::Sensor;
/// use goaprs::action::Action;
///
/// let sensors = Vec::<Sensor>::new();
/// let actions = Vec::<Action>::new();
/// let mut world_state = HashMap::new();
/// world_state.insert("location".to_string(), "home".to_string());
///
/// let controller = AutomatonController::new(actions, sensors, "home_assistant", world_state);
///
/// // Set a goal
/// let mut goal = HashMap::new();
/// goal.insert("lights".to_string(), "on".to_string());
/// controller.set_goal(goal).await?;
///
/// // Start the automaton
/// controller.start().await?;
///
/// // Later, stop the automaton
/// controller.stop().await?;
/// # Ok(())
/// # }
/// ```
pub struct AutomatonController {
    /// The automaton to control
    automaton: Arc<Automaton>,
    /// Whether the controller is running
    running: Arc<Mutex<bool>>,
}

impl AutomatonController {
    /// Creates a new automaton controller with the given components.
    ///
    /// # Arguments
    ///
    /// * `actions` - Collection of actions the automaton can perform
    /// * `sensors` - Collection of sensors the automaton will use
    /// * `name` - Name for the automaton
    /// * `world_state` - Initial world state as key-value pairs
    ///
    /// # Returns
    ///
    /// A new `AutomatonController` instance that manages an Automaton with the provided components
    pub fn new(
        actions: Vec<crate::action::Action>,
        sensors: Vec<crate::sensor::Sensor>,
        name: impl Into<String>,
        world_state: HashMap<String, String>,
    ) -> Self {
        Self {
            automaton: Arc::new(Automaton::new(name, sensors, actions, world_state)),
            running: Arc::new(Mutex::new(false)),
        }
    }

    /// Gets a reference to the managed automaton.
    ///
    /// # Returns
    ///
    /// A reference to the `Automaton` instance
    pub fn automaton(&self) -> &Automaton {
        &self.automaton
    }

    /// Sets the goal state for the automaton.
    ///
    /// # Arguments
    ///
    /// * `goal` - A HashMap of key-value pairs representing the desired goal state
    ///
    /// # Returns
    ///
    /// A `Result` indicating success or failure
    ///
    /// # Errors
    ///
    /// Returns an error if setting the goal fails
    pub async fn set_goal(&self, goal: HashMap<String, String>) -> Result<()> {
        self.automaton.set_goal(goal).await
    }

    /// Gets the current world state from the managed automaton.
    ///
    /// # Returns
    ///
    /// A `Result` containing the current `WorldState`
    ///
    /// # Errors
    ///
    /// Returns an error if retrieving the world state fails
    pub async fn world_state(&self) -> Result<WorldState> {
        self.automaton.world_state().await
    }

    /// Gets the current goal state from the managed automaton.
    ///
    /// # Returns
    ///
    /// A `Result` containing the current goal `WorldState`
    ///
    /// # Errors
    ///
    /// Returns an error if retrieving the goal state fails
    pub async fn goal(&self) -> Result<WorldState> {
        self.automaton.goal().await
    }

    /// Starts the automaton controller in a new thread.
    ///
    /// This method:
    /// 1. Sets the running flag to true
    /// 2. Spawns a new thread that runs the automaton's sense-plan-act cycle
    /// 3. The thread will continue until the controller is stopped
    ///
    /// # Returns
    ///
    /// A `Result` indicating success or failure
    ///
    /// # Notes
    ///
    /// This method must be called from within a tokio::task::LocalSet
    /// since it uses tokio::task::spawn_local internally.
    ///
    /// # Errors
    ///
    /// Returns an error if the running mutex is poisoned
    ///
    /// This method:
    /// 1. Sets the running flag to true
    /// 2. Spawns a new local task that runs the automaton's sense-plan-act cycle
    /// 3. The task will continue until the controller is stopped
    ///
    /// # Returns
    ///
    /// A `Result` indicating success or failure
    ///
    /// # Errors
    ///
    /// Returns an error if the running mutex is poisoned
    pub async fn start(&self) -> Result<()> {
        {
            let mut running = self.running.lock().await;
            *running = true;
        }

        let automaton = self.automaton.clone();
        let running = self.running.clone();

        // Spawn a task on the local task set that runs the automaton loop
        tokio::task::spawn_local(async move {
            loop {
                let is_running = {
                    let running_guard = running.lock().await;
                    *running_guard
                };

                if !is_running {
                    break;
                }

                // Check if we've reached the goal
                let world_state = automaton.world_state().await.unwrap();
                let goal = automaton.goal().await.unwrap();

                if world_state.satisfies(&goal) {
                    println!("World state satisfies goal: {:?}", goal);
                    automaton.wait().await.unwrap();
                } else {
                    println!(
                        "World state differs from goal: \nState: {:?}\nGoal: {:?}",
                        world_state, goal
                    );
                    println!("Need to find an action plan");

                    // Generate a plan
                    let plan = automaton.plan().await.unwrap();
                    println!("Plan found. Will execute the action plan: {:?}", plan);

                    // Execute the plan
                    automaton.act().await.unwrap();
                }

                // Sense the environment
                automaton.sense().await.unwrap();

                // Wait before next cycle
                tokio::time::sleep(Duration::from_secs(5)).await;
            }
        });

        Ok(())
    }

    /// Stops the automaton controller.
    ///
    /// This method sets the running flag to false, which will cause the
    /// controller's thread to exit after its current cycle completes.
    ///
    /// # Returns
    ///
    /// A `Result` indicating success or failure
    ///
    /// # Errors
    ///
    /// Returns an error if the running mutex is poisoned
    ///
    /// This method sets the running flag to false, which will cause the
    /// controller's thread to exit after its current cycle completes.
    ///
    /// # Returns
    ///
    /// A `Result` indicating success or failure
    ///
    /// # Errors
    ///
    /// Returns an error if the running mutex is poisoned
    pub async fn stop(&self) -> Result<()> {
        let mut running = self.running.lock().await;
        *running = false;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::Result;
    use crate::sensor::{self, SensorResponse};
    use crate::utils::actor::{self, SensorFn};
    use async_trait::async_trait;
    use std::sync::Arc;

    struct TestSensor;

    #[async_trait]
    impl SensorFn for TestSensor {
        async fn exec(&self, _world_state: &HashMap<String, actor::Fact>) -> Vec<actor::Fact> {
            vec![actor::Fact::new("test_key", "test value", "test_sensor")]
        }
    }

    // Adapter to convert from actor::SensorFn to sensor::SensorFn
    struct SensorAdapter {
        sensor: Arc<dyn SensorFn>,
    }

    impl SensorAdapter {
        fn new(sensor: Arc<dyn SensorFn>) -> Self {
            Self { sensor }
        }
    }

    #[async_trait]
    impl sensor::SensorFn for SensorAdapter {
        async fn exec(&self) -> Result<SensorResponse> {
            let facts = self.sensor.exec(&HashMap::new()).await;
            let value = if !facts.is_empty() {
                facts[0].data().to_string()
            } else {
                "".to_string()
            };
            Ok(SensorResponse::new(value, "".to_string(), 0))
        }
    }

    // We don't need TestAction as we're using Action directly in the test

    #[tokio::test]
    async fn test_automaton_basic_cycle() {
        // Create sensors and actions
        let test_sensor = Arc::new(TestSensor);
        let sensor_adapter = SensorAdapter::new(test_sensor);
        let sensors = vec![Sensor::new("test_sensor", "test_key", sensor_adapter)];

        let mut actions = vec![];

        let mut conditions = HashMap::new();
        conditions.insert("test_key".to_string(), "test value".to_string());

        let mut effects = HashMap::new();
        effects.insert("goal_key".to_string(), "goal value".to_string());

        // Create a test action with the conditions and effects
        let mut test_action = Action::new("test_action", 1.0).unwrap();
        for (key, value) in conditions {
            test_action.preconditions.set(&key, value == "true");
        }
        for (key, value) in effects {
            test_action.effects.set(&key, value == "true");
        }
        actions.push(test_action);

        // Creates a new automaton with the given name, sensors, actions, and initial world state.
        //
        // # Arguments
        //
        // * `name` - A name for the automaton
        // * `sensors` - The collection of sensors the automaton will use to gather information
        // * `actions` - The collection of actions the automaton can perform
        // * `world_state_facts` - Initial key-value pairs representing the starting world state
        //
        // # Returns
        //
        // A new `Automaton` instance initialized with the provided components and in the `WaitingOrders` state
        //
        // # Examples
        //
        // ```
        // use std::collections::HashMap;
        // use goaprs::{Automaton, Sensors, Actions};
        //
        // let sensors = Sensors::new();
        // let actions = Actions::new();
        // let mut initial_state = HashMap::new();
        // initial_state.insert("location".to_string(), "home".to_string());
        //
        // let automaton = Automaton::new("home_assistant", sensors, actions, initial_state);
        // ```
        let mut world_state = HashMap::new();
        world_state.insert("initial_key".to_string(), "initial value".to_string());

        let automaton = Automaton::new("test", sensors, actions, world_state);

        // Set a goal
        let mut goal = HashMap::new();
        goal.insert("goal_key".to_string(), "goal value".to_string());
        automaton.set_goal(goal).await.unwrap();

        // Run through the cycle
        assert_eq!(automaton.state().await.unwrap(), State::WaitingOrders);

        // Sense
        automaton.sense().await.unwrap();
        assert_eq!(automaton.state().await.unwrap(), State::Sensing);

        // Check that the world state was updated
        let ws = automaton.world_state().await.unwrap();
        assert_eq!(ws.get("test_key"), Some(&"test value".to_string()));

        // Plan
        let plan = automaton.plan().await.unwrap();
        assert_eq!(automaton.state().await.unwrap(), State::Planning);
        assert_eq!(plan.len(), 1);
        assert_eq!(plan[0].name, "test_action");

        // Act
        let responses = automaton.act().await.unwrap();
        assert_eq!(automaton.state().await.unwrap(), State::Acting);
        assert_eq!(responses.len(), 1);
        assert_eq!(responses[0].stdout(), "Executed action: test_action");
    }
}