console.log('[EA] entrepriseAgents.js file loaded');

llmApp.directive('entrepriseAgents',['PLUGIN_PATHS','PythonService','ParamsHelperService','$stateParams', 'SharedPromiseService', function (PLUGIN_PATHS, PythonService,ParamsHelperService,$stateParams,SharedPromiseService) {

    return {
        restrict: 'E',
        templateUrl: PLUGIN_PATHS.WEBAPP + 'sections/entreprise-agents.html',
        scope: { config: '=', configForm: '=' },
        controller: ['$scope', '$timeout', function ($scope, $timeout) {
            $scope.config = $scope.config || {};

            function eaDbg() {
                try { console.debug.apply(console, ['[EA]'].concat([].slice.call(arguments))); } catch(e) {}
                try { console.log.apply(console,   ['[EA]'].concat([].slice.call(arguments))); } catch(e) {}
            }

            // Initialize config arrays
            $scope.config.projects_keys = $scope.config.projects_keys || [];
            $scope.config.agents_ids = $scope.config.agents_ids || [];
            $scope.config.augmented_llms_ids = $scope.config.augmented_llms_ids || [];
            $scope.config.tool_agent_configurations = $scope.config.tool_agent_configurations || [];
            $scope.config.augmented_llms_configurations = $scope.config.augmented_llms_configurations || [];

            function projectOf(id) { 
                if (!id || typeof id !== 'string') return null; 
                var i = id.indexOf(':'); 
                return i>0 ? id.slice(0,i) : null; 
            }

            function makeAgentConfig(agentId) {
                return { 
                    agent_id: agentId, 
                    agent_system_instructions: '', 
                    tool_agent_description: '', 
                    enable_stories: false, 
                    stories_workspace: null 
                };
            }

            function makeAugLLMConfig(llmId) {
                return { 
                    augmented_llm_id: llmId, 
                    augmented_llm_description: '', 
                    augmented_llm_system_instructions: '' 
                };
            }

            function syncListFromIds(ids, listProp, idField, factoryFn) {
                if (!Array.isArray(ids)) return;
                var list = $scope.config[listProp] || [];
                ids.forEach(function (id) { 
                    if (!list.some(function (it) { return it[idField] === id; })) {
                        list.push(factoryFn(id)); 
                    }
                });
                for (var i = list.length - 1; i >= 0; i--) { 
                    if (!ids.includes(list[i][idField])) {
                        list.splice(i, 1); 
                    }
                }
                $scope.config[listProp] = list;
            }

            function updateProjectsFromAgents() {
                var projects = new Set();
                
                // From agents (extract from ID)
                ($scope.config.agents_ids || []).forEach(function(id) {
                    var proj = projectOf(id);
                    if (proj) projects.add(proj);
                });
                
                // From augmented LLMs (extract from label via service)
                var augLlmIds = $scope.config.augmented_llms_ids || [];
                if (augLlmIds.length > 0) {
                    var payload = {
                        rootModel: {
                            augmented_llms_ids: augLlmIds,
                            projects_keys: $scope.config.projects_keys
                        }
                    };
                    
                    ParamsHelperService.listSelectedAugmentedLlms(payload)
                        .then(function(result) {
                            (result.choices || []).forEach(function(choice) {
                                var match = choice.label.match(/^\[([^\]]+)\]/);
                                if (match && match[1]) {
                                    projects.add(match[1]);
                                }
                            });
                            $scope.config.projects_keys = Array.from(projects);
                        });
                } else {
                    $scope.config.projects_keys = Array.from(projects);
                }
            }
            
            // Add modal
            $scope.addModal = {
                isVisible: false,
                projects_keys: null,
                isOpen: false,
                filter: '',
                catalog: [],
                available: [],
                selectedItems: [],
                selectedCount: 0,
                
                show: function() {
                    this.isVisible = true;
                    this.projects_keys = null;
                    this.filter = '';
                    this.selectedItems = [];
                    this.selectedCount = 0;
                    this.catalog = [];
                    this.available = [];
                },
                
                cancel: function() {
                    this.isVisible = false;
                    this.projects_keys = null;
                    this.filter = '';
                    this.selectedItems = [];
                    this.catalog = [];
                    this.available = [];
                },
                
                itemMatchesFilter: function(item) {
                    if (!$scope.addModal.filter) return true;
                    var f = $scope.addModal.filter.toLowerCase();
                    return (item.label && item.label.toLowerCase().indexOf(f) !== -1)
                        || (item.type && item.type.toLowerCase().indexOf(f) !== -1);
                },
                
                selectItem: function(item) {
                    var idx = this.selectedItems.indexOf(item.value);
                    if (idx === -1) {
                        this.selectedItems.push(item.value);
                        item.selected = true;
                    } else {
                        this.selectedItems.splice(idx, 1);
                        item.selected = false;
                    }
                    this.selectedCount = this.selectedItems.length;
                },
                
                submit: function() {
                    var self = this;
                    var selectedProject = this.projects_keys;
                    
                    this.selectedItems.forEach(function(itemValue) {
                        var item = self.catalog.find(function(x) { return x.value === itemValue; });
                        if (!item) return;
                        
                        if (item.type === 'AGENT') {
                            if ($scope.config.agents_ids.indexOf(item.value) === -1) {
                                $scope.config.agents_ids.push(item.value);
                            }
                        } else {
                            if ($scope.config.augmented_llms_ids.indexOf(item.value) === -1) {
                                $scope.config.augmented_llms_ids.push(item.value);
                            }
                        }
                    });
                    
                    // Add project to projects_keys if not already there
                    if (selectedProject && $scope.config.projects_keys.indexOf(selectedProject) === -1) {
                        $scope.config.projects_keys.push(selectedProject);
                    }
                    
                    this.cancel();
                }
                };

            function loadCatalogForModal() {
                if (!$scope.addModal.projects_keys) {
                    $scope.addModal.catalog = [];
                    $scope.addModal.available = [];
                    return;
                }

                // Create temp config with selected project
                var tempConfig = { projects_keys: [$scope.addModal.projects_keys] };
                
                var pAgents = ParamsHelperService.do({ parameterName: 'agents_ids', rootModel: tempConfig });
                var pRag = ParamsHelperService.do({ parameterName: 'augmented_llms_ids', rootModel: tempConfig });

                Promise.all([pAgents, pRag]).then(function (res) {
                    var cat = [];
                    var agentsChoices = (res[0] && res[0].choices) ? res[0].choices : [];
                    var ragChoices    = (res[1] && res[1].choices) ? res[1].choices : [];
                    
                    agentsChoices.forEach(function (c) {
                        if (c && c.value) cat.push({ 
                            value: c.value, 
                            label: c.label || c.value, 
                            type: 'AGENT', 
                            selected: false 
                        });
                    });
                    ragChoices.forEach(function (c) {
                        if (c && c.value) cat.push({ 
                            value: c.value, 
                            label: c.label || c.value, 
                            type: 'RAG', 
                            selected: false 
                        });
                    });
                    
                    $scope.$applyAsync(function () {
                        $scope.addModal.catalog = cat;
                        
                        // Filter out already selected items
                        var taken = new Set(($scope.config.agents_ids || []).concat($scope.config.augmented_llms_ids || []));
                        $scope.addModal.available = cat.filter(function (x) { return !taken.has(x.value); });
                    });
                }).catch(function (err) {
                    eaDbg('Error loading catalog:', err);
                    $scope.$applyAsync(function () {
                        $scope.addModal.catalog = [];
                        $scope.addModal.available = [];
                    });
                });
            }

            // Row delete -> keep ids arrays in sync and update projects
            $scope.onRowRemoved = function(type, item) {
                if (!item) return;
                var id = (type === 'AGENT') ? item.agent_id : item.augmented_llm_id;
                if (!id) return;
                
                if (type === 'AGENT') {
                    $scope.config.agents_ids = ($scope.config.agents_ids || []).filter(function(x){ return x !== id; });
                } else {
                    $scope.config.augmented_llms_ids = ($scope.config.augmented_llms_ids || []).filter(function(x){ return x !== id; });
                }
                
                // Clean up projects_keys
                updateProjectsFromAgents();
            };
            
            // Watchers
            $scope.$watchCollection('config.agents_ids', function (ids) {
                syncListFromIds(ids || [], 'tool_agent_configurations', 'agent_id', makeAgentConfig);

                    // Update modal available items if modal is open
                    if ($scope.addModal.isVisible && $scope.addModal.catalog.length > 0) {
                        var taken = new Set((ids || []).concat($scope.config.augmented_llms_ids || []));
                        $scope.addModal.available = $scope.addModal.catalog.filter(function (x) { return !taken.has(x.value); });
                    }

            });
            
            $scope.$watchCollection('config.augmented_llms_ids', function (ids) {
                syncListFromIds(ids || [], 'augmented_llms_configurations', 'augmented_llm_id', makeAugLLMConfig);
                    // Update modal available items if modal is open
                    if ($scope.addModal.isVisible && $scope.addModal.catalog.length > 0) {
                        var taken = new Set(($scope.config.agents_ids || []).concat(ids || []));
                        $scope.addModal.available = $scope.addModal.catalog.filter(function (x) { return !taken.has(x.value); });
                    }

            });
            
            // Watch for project selection in modal
            $scope.$watch('addModal.projects_keys', function(newVal) {
                if (newVal) {
                    loadCatalogForModal();
                }
            });

            // Initialize projects_keys from existing agents/LLMs
            updateProjectsFromAgents();
        }]
    };
}]);
