const { query } = require('../db');
const BillingAgent = require('./BillingAgent');
const TriageAgent = require('./TriageAgent');
const FollowUpAgent = require('./FollowUpAgent');
const InventoryAgent = require('./InventoryAgent');
const CDSSAgent = require('./CDSSAgent');
const RxVisionAgent = require('./RxVisionAgent');
const DocumentIntelligenceAgent = require('./DocumentIntelligenceAgent');

class AgentManager {
    constructor() {
        this.agents = {};
        this.registerAgent('BILLING', BillingAgent);
        this.registerAgent('TRIAGE', TriageAgent);
        this.registerAgent('FOLLOWUP', FollowUpAgent);
        this.registerAgent('INVENTORY', InventoryAgent);
        this.registerAgent('CDSS', CDSSAgent);
        this.registerAgent('RX_VISION', RxVisionAgent);
        this.registerAgent('DOC_INTELLIGENCE', DocumentIntelligenceAgent);
    }

    /**
     * Register an agent instance mapped to its type enum.
     */
    registerAgent(agentType, agentInstance) {
        this.agents[agentType] = agentInstance;
        console.log(`[AgentManager] Registered: ${agentType}`);
    }

    /**
     * The core event dispatcher. 
     * E.g. dispatch('sharma-clinic', 'BILLING', { clinicalNotes: '...' })
     */
    async dispatch(tenantId, agentType, payload) {
        if (!this.agents[agentType]) {
            console.error(`[AgentManager] Agent type ${agentType} is not registered in the system.`);
            return null;
        }

        try {
            // Check if clinic has this agent enabled
            const dbCheck = await query(
                'SELECT is_active, config FROM agent_configs WHERE tenant_id = $1 AND agent_type = $2',
                [tenantId, agentType]
            );

            if (dbCheck.rows.length === 0 || !dbCheck.rows[0].is_active) {
                console.log(`[AgentManager] Skipped ${agentType} for tenant ${tenantId} (Not enabled)`);
                return null;
            }

            const config = dbCheck.rows[0].config;
            console.log(`[AgentManager] Dispatched ${agentType} for tenant ${tenantId}`);
            
            // Execute the agent asynchronously so it doesn't block the main thread
            return this.agents[agentType].execute(config, payload).catch(err => {
                console.error(`[AgentManager] ${agentType} execution error:`, err);
            });

        } catch (err) {
            console.error(`[AgentManager] Dispatch error for ${agentType}:`, err);
        }
    }
}

// Singleton instance
module.exports = new AgentManager();
