/**
 * Agent Reasoning Engine — Zero-Cost Intelligence
 * 
 * Provides deterministic, RAG-grounded reasoning for domain agents
 * WITHOUT calling any external LLM. This is the default reasoning path.
 * 
 * Flow:
 * 1. Load Standing Orders (always first)
 * 2. Query RAG namespace for domain-specific business context
 * 3. Apply deterministic rules based on agent domain + message intent
 * 4. Compose a structured response
 * 5. If confidence < threshold AND external LLM is allowed → fallback to cloud
 * 
 * Standing Order: "All agent interactions must attempt zero-cost reasoning first."
 */

import { retrieveContext } from '@/lib/gfs/rag/retriever';
import { prisma } from '@/lib/db';
import { BRAND } from '@/lib/white-label/constants';

export interface AgentReasoningInput {
  agentId: string;
  agentName: string;
  agentDomain: string;
  agentTitle: string;
  systemPrompt: string;
  personality: string;
  userMessage: string;
  memories: { category: string; key: string; content: unknown }[];
  escalationContext?: string;
}

export interface AgentReasoningResult {
  reply: string;
  confidence: number; // 0-1, how confident the deterministic response is
  source: 'rag' | 'rules' | 'rag+rules' | 'fallback';
  ragCitations: { source: string; title: string; category: string }[];
  requiresLLM: boolean; // true if confidence is too low for deterministic
  intent: string;
  tokensUsed: 0; // always 0 for deterministic path
  costUsd: 0;
}

// ============================================
// INTENT CLASSIFICATION (Rule-based, no LLM)
// ============================================

type Intent = 
  | 'status_query'      // "How are things?" "What's the status?"
  | 'data_query'        // "Show me X" "How many Y?"
  | 'action_request'    // "Create X" "Update Y" "Delete Z"
  | 'analysis_request'  // "Analyze X" "What's the trend?"
  | 'escalation'        // "This is urgent" "I need help"
  | 'greeting'          // "Hello" "Hi"
  | 'general'           // Catch-all
  | 'complex';          // Needs LLM

const INTENT_PATTERNS: { pattern: RegExp; intent: Intent }[] = [
  // Greetings
  { pattern: /^(hi|hello|hey|good\s*(morning|afternoon|evening)|greetings)/i, intent: 'greeting' },
  // Status queries
  { pattern: /(status|how\s*(are|is)|what'?s\s*(happening|going|the\s*state)|overview|summary|brief|report|dashboard)/i, intent: 'status_query' },
  // Data queries
  { pattern: /(show|list|find|get|how\s*many|count|total|display|retrieve|lookup|search)/i, intent: 'data_query' },
  // Action requests
  { pattern: /(create|add|make|generate|build|set\s*up|configure|update|change|modify|delete|remove|cancel|approve|reject)/i, intent: 'action_request' },
  // Analysis
  { pattern: /(analyze|trend|forecast|predict|compare|assess|evaluate|risk|anomal|pattern|insight)/i, intent: 'analysis_request' },
  // Escalation
  { pattern: /(urgent|escalat|critical|emergency|help|override|breach|violation|alert)/i, intent: 'escalation' },
];

function classifyIntent(message: string): Intent {
  const lower = message.toLowerCase().trim();
  for (const { pattern, intent } of INTENT_PATTERNS) {
    if (pattern.test(lower)) return intent;
  }
  // If message is long or contains questions that need reasoning, mark as complex
  if (lower.length > 300 || (lower.includes('?') && lower.split(' ').length > 20)) {
    return 'complex';
  }
  return 'general';
}

// ============================================
// DOMAIN-SPECIFIC RULE ENGINES
// ============================================

interface DomainRules {
  ragNamespace: string[]; // RAG categories to search
  statusTemplate: (data: Record<string, unknown>) => string;
  greetingTemplate: (agentName: string, agentTitle: string) => string;
  capabilities: string[];
}

const DOMAIN_RULES: Record<string, DomainRules> = {
  ceo: {
    ragNamespace: ['standing_order', 'sop', 'business_model', 'architecture', 'agent_guide'],
    statusTemplate: (data) => `**Executive Overview**\n\nThe ${BRAND.companyName} system is operational.\n\n` +
      `• **Active Agents**: ${data.activeAgents || 'checking...'}\n` +
      `• **Pending Escalations**: ${data.pendingEscalations || 0}\n` +
      `• **System Health**: ${data.systemHealth || 'nominal'}\n\n` +
      `I'm coordinating all domain agents. Key priorities remain aligned with our Standing Orders.`,
    greetingTemplate: (name, title) => `I'm ${name}, ${title} of ${BRAND.companyName}'s AI agent hierarchy. ` +
      `I coordinate all domain agents — Finance (Ledger), HR (Harmony), Sales (Pipeline), ` +
      `Inventory (Stockwatch), Compliance (Sentinel), Projects (Milestone), and Operations (Conductor). ` +
      `What do you need from the Familiars today?`,
    capabilities: ['cross_domain_reasoning', 'strategic_planning', 'escalation_handling', 'intelligence_briefs'],
  },
  finance: {
    ragNamespace: ['standing_order', 'sop', 'policy', 'business_model'],
    statusTemplate: (data) => `**Finance Status Report**\n\n` +
      `• **Accounts**: ${data.accountCount || 'checking...'} active\n` +
      `• **Open Invoices**: ${data.openInvoices || 'checking...'}\n` +
      `• **Pending Transactions**: ${data.pendingTx || 0}\n` +
      `• **Budget Alerts**: ${data.budgetAlerts || 'none'}\n\n` +
      `All financial operations comply with Standing Orders §1 (Data Sovereignty), §7 (Audit Requirements), ` +
      `and §13 (GAAP/SOX Accounting Guardrails).\n\n` +
      `**Active Guardrails**: Referential integrity enforced • Soft-delete only for entities with history • ` +
      `Posted transactions immutable • Full audit trail on all operations.`,
    greetingTemplate: (name, title) => `I'm ${name}, the ${title}. Numbers are my native language. ` +
      `I track every dollar, flag anomalies, and forecast with precision. ` +
      `GAAP guardrails are enforced on all operations — no record with transaction history can be deleted, ` +
      `and posted entries are immutable. How can I help with finances?`,
    capabilities: ['transaction_analysis', 'budget_monitoring', 'invoice_tracking', 'cash_flow_forecasting',
      'guardrail_enforcement', 'void_transaction', 'soft_delete', 'audit_trail'],
  },
  hr: {
    ragNamespace: ['standing_order', 'sop', 'policy'],
    statusTemplate: (data) => `**HR & People Status**\n\n` +
      `• **Employees**: ${data.employeeCount || 'checking...'}\n` +
      `• **Open Leave Requests**: ${data.leaveRequests || 0}\n` +
      `• **Departments**: ${data.departmentCount || 'checking...'}\n` +
      `• **Payroll Status**: ${data.payrollStatus || 'current'}\n\n` +
      `People-first, data-informed. All HR operations respect privacy per Standing Orders §1.`,
    greetingTemplate: (name, title) => `I'm ${name}, the ${title}. People are the most complex system of all. ` +
      `I understand workforce dynamics and ensure every team member is supported. What's on your mind?`,
    capabilities: ['employee_monitoring', 'payroll_analysis', 'leave_management', 'workforce_planning'],
  },
  sales: {
    ragNamespace: ['standing_order', 'sop', 'business_model', 'product_spec'],
    statusTemplate: (data) => `**Revenue Pipeline Status**\n\n` +
      `• **Active Opportunities**: ${data.opportunities || 'checking...'}\n` +
      `• **Open Sales Orders**: ${data.salesOrders || 'checking...'}\n` +
      `• **Pipeline Value**: ${data.pipelineValue || 'calculating...'}\n` +
      `• **Conversion Rate**: ${data.conversionRate || 'tracking...'}\n\n` +
      `Revenue is the lifeblood. Every deal tracked, every conversion optimized.`,
    greetingTemplate: (name, title) => `I'm ${name}, the ${title}. I know every deal in the pipeline, ` +
      `every quote outstanding, and every conversion pattern. Let's talk revenue.`,
    capabilities: ['pipeline_analysis', 'revenue_forecasting', 'lead_scoring', 'deal_risk_assessment'],
  },
  inventory: {
    ragNamespace: ['standing_order', 'sop', 'product_spec'],
    statusTemplate: (data) => `**Supply Chain Status**\n\n` +
      `• **Products**: ${data.productCount || 'checking...'}\n` +
      `• **In-Stock Items**: ${data.inStockCount || 'checking...'}\n` +
      `• **Low Stock Alerts**: ${data.lowStockAlerts || 0}\n` +
      `• **Pending Orders**: ${data.pendingOrders || 0}\n\n` +
      `Supply chain flowing. Every SKU monitored in real-time.`,
    greetingTemplate: (name, title) => `I'm ${name}, the ${title}. Supply chain is a puzzle and I solve it in real-time. ` +
      `I predict shortages, optimize reorder points, and keep everything flowing. What needs attention?`,
    capabilities: ['stock_monitoring', 'demand_forecasting', 'supplier_analysis', 'shortage_prediction'],
  },
  compliance: {
    ragNamespace: ['standing_order', 'sop', 'policy', 'risk_register'],
    statusTemplate: (data) => `**Compliance & Security Status**\n\n` +
      `• **Active Alerts**: ${data.activeAlerts || 0}\n` +
      `• **Rules Enforced**: ${data.rulesCount || 'all'}\n` +
      `• **Audit Trail Entries**: ${data.auditEntries || 'continuous'}\n` +
      `• **Standing Orders**: Loaded and enforced\n\n` +
      `I never sleep. All operations are auditable and compliant.`,
    greetingTemplate: (name, title) => `I'm ${name}, the ${title}. I never sleep, and I see everything. ` +
      `Security isn't a feature — it's the foundation. What needs my attention?`,
    capabilities: ['anomaly_detection', 'compliance_monitoring', 'audit_trail', 'threat_assessment'],
  },
  projects: {
    ragNamespace: ['standing_order', 'sop'],
    statusTemplate: (data) => `**Projects Status**\n\n` +
      `• **Active Projects**: ${data.projectCount || 'checking...'}\n` +
      `• **Tasks in Progress**: ${data.tasksInProgress || 0}\n` +
      `• **Milestones Due This Week**: ${data.milestonesDue || 0}\n` +
      `• **Resource Utilization**: ${data.utilization || 'monitoring'}\n\n` +
      `Timelines tracked. Deliverables on schedule. Green/Yellow/Red — no ambiguity.`,
    greetingTemplate: (name, title) => `I'm ${name}, the ${title}. Timelines and deliverables are my obsession. ` +
      `I track every task and predict delays before they cascade. What project needs attention?`,
    capabilities: ['project_tracking', 'milestone_monitoring', 'resource_allocation', 'dependency_analysis'],
  },
  operations: {
    ragNamespace: ['standing_order', 'sop', 'architecture'],
    statusTemplate: (data) => `**Operations Status**\n\n` +
      `• **System Uptime**: ${data.uptime || '99.9%'}\n` +
      `• **Active Workflows**: ${data.activeWorkflows || 0}\n` +
      `• **Queue Depth**: ${data.queueDepth || 'nominal'}\n` +
      `• **Last Health Check**: ${data.lastHealthCheck || 'recent'}\n\n` +
      `All systems coordinated. Workflows executing within Standing Order parameters.`,
    greetingTemplate: (name, title) => `I'm ${name}, the ${title}. I keep all systems running in harmony. ` +
      `Cross-domain coordination is my specialty. What operational matter needs attention?`,
    capabilities: ['workflow_coordination', 'system_monitoring', 'process_optimization', 'cross_domain_ops'],
  },
};

// ============================================
// LIVE DATA FETCHERS (zero-cost, DB only)
// ============================================

async function fetchDomainData(domain: string): Promise<Record<string, unknown>> {
  try {
    switch (domain) {
      case 'finance': {
        const [accounts, invoices, transactions] = await Promise.all([
          prisma.account.count().catch(() => 0),
          prisma.invoice.count({ where: { status: { in: ['draft', 'sent'] } } }).catch(() => 0),
          prisma.transaction.count({ where: { status: 'pending' } }).catch(() => 0),
        ]);
        return { accountCount: accounts, openInvoices: invoices, pendingTx: transactions };
      }
      case 'hr': {
        const [employees, departments] = await Promise.all([
          prisma.employee.count().catch(() => 0),
          prisma.department.count().catch(() => 0),
        ]);
        return { employeeCount: employees, departmentCount: departments };
      }
      case 'sales': {
        const [orders, opportunities] = await Promise.all([
          prisma.salesOrder.count({ where: { status: { not: 'cancelled' } } }).catch(() => 0),
          prisma.opportunity.count({ where: { stage: { not: 'closed-lost' } } }).catch(() => 0),
        ]);
        return { salesOrders: orders, opportunities: opportunities };
      }
      case 'inventory': {
        const [products, inStock, lowStock] = await Promise.all([
          prisma.product.count().catch(() => 0),
          prisma.inventoryItem.count({ where: { status: 'in-stock' } }).catch(() => 0),
          prisma.inventoryItem.count({ where: { quantity: { lte: 10 } } }).catch(() => 0),
        ]);
        return { productCount: products, inStockCount: inStock, lowStockAlerts: lowStock };
      }
      case 'compliance': {
        const [alerts, audits] = await Promise.all([
          prisma.sentinelAlert.count({ where: { status: 'active' } }).catch(() => 0),
          prisma.auditLog.count().catch(() => 0),
        ]);
        return { activeAlerts: alerts, auditEntries: audits };
      }
      case 'ceo': {
        const [agents, escalations] = await Promise.all([
          prisma.domainAgent.count({ where: { status: 'active' } }).catch(() => 0),
          prisma.domainAgentMessage.count({ where: { type: 'escalation', status: 'pending' } }).catch(() => 0),
        ]);
        return { activeAgents: agents, pendingEscalations: escalations, systemHealth: 'nominal' };
      }
      default:
        return {};
    }
  } catch {
    return {};
  }
}

// ============================================
// MAIN REASONING FUNCTION
// ============================================

export async function agentReason(input: AgentReasoningInput): Promise<AgentReasoningResult> {
  const intent = classifyIntent(input.userMessage);
  const domain = input.agentDomain;
  const rules = DOMAIN_RULES[domain] || DOMAIN_RULES['operations'];

  // Always retrieve RAG context (Standing Orders loaded first due to boost)
  const ragContext = retrieveContext(
    `${domain} ${input.userMessage}`,
    {
      boostCategories: ['standing_order', 'sop'],
      maxChunks: 4,
    }
  );

  const ragCitations = ragContext.citations;
  let reply = '';
  let confidence = 0;
  let source: AgentReasoningResult['source'] = 'rules';

  switch (intent) {
    case 'greeting': {
      reply = rules.greetingTemplate(input.agentName, input.agentTitle);
      confidence = 1.0;
      source = 'rules';
      break;
    }

    case 'status_query': {
      const liveData = await fetchDomainData(domain);
      reply = rules.statusTemplate(liveData);
      if (ragContext.chunkCount > 0) {
        reply += `\n\n**Relevant Business Context:**\n${ragContext.contextText.substring(0, 500)}`;
        source = 'rag+rules';
      }
      confidence = 0.9;
      break;
    }

    case 'data_query': {
      const liveData = await fetchDomainData(domain);
      reply = `**${input.agentName} — Data Query Response**\n\n`;
      // Provide what we can from live DB data
      const entries = Object.entries(liveData);
      if (entries.length > 0) {
        reply += entries.map(([k, v]) => `• **${k.replace(/([A-Z])/g, ' $1').trim()}**: ${v}`).join('\n');
        confidence = 0.7;
      } else {
        reply += `I can provide status for my domain (${domain}). For specific queries, ` +
          `please check the ${domain} module in Ghost Control → Operations.`;
        confidence = 0.5;
      }
      if (ragContext.chunkCount > 0) {
        reply += `\n\n**Policy Context:**\n${ragContext.contextText.substring(0, 400)}`;
        source = 'rag+rules';
      } else {
        source = 'rules';
      }
      break;
    }

    case 'action_request': {
      const msgLower = input.userMessage.toLowerCase();
      const isDeleteRequest = /\b(delete|remove|destroy|erase|drop|purge)\b/.test(msgLower);
      const isVoidRequest = /\b(void|reverse|cancel|annul)\b/.test(msgLower);
      const isFinancialEntity = /\b(customer|vendor|invoice|order|transaction|payment|account|product)\b/.test(msgLower);

      if (isDeleteRequest && isFinancialEntity) {
        // GAAP Guardrail — block delete, suggest alternatives
        reply = `**🛡️ ${input.agentName} — GAAP Guardrail Activated**\n\n` +
          `Your request involves deleting a financial entity. Per **Standing Orders §13** (Accounting Guardrails):\n\n` +
          `• **Referential Integrity**: Hard delete is blocked if linked transactions exist.\n` +
          `• **Soft Delete Only**: Entities with history can only be **Marked Inactive** (hidden from lists, preserved for audits/tax).\n` +
          `• **Posted Transactions**: Invoices, sales orders, and credits that are posted can NEVER be deleted — only **Voided** with a Reason Code.\n\n` +
          `**What you can do instead:**\n` +
          `1. **Mark Inactive** — Go to CRM → Customers and use the ⊘ button\n` +
          `2. **Void** — For posted invoices/orders, use the Void action with a mandatory reason\n` +
          `3. **Credit Memo** — Create a reversing entry instead of deleting\n\n` +
          `All actions are logged in the immutable audit trail. Need help with one of these alternatives?`;
        confidence = 0.95;
        source = 'rules';
      } else if (isVoidRequest && isFinancialEntity) {
        reply = `**${input.agentName} — Void/Reversal Request**\n\n` +
          `Per **Standing Orders §13.3**, void operations on posted transactions require:\n\n` +
          `• **Reason Code** (mandatory) — e.g., Duplicate Entry, Customer Request, Data Error\n` +
          `• **Approval** required for amounts ≥ $1,000\n` +
          `• Original record preserved with full audit trail\n\n` +
          `Please specify the entity ID and reason code. The void will zero the amount while keeping the complete record for compliance.`;
        confidence = 0.9;
        source = 'rules';
      } else {
        reply = `**${input.agentName} — Action Request Received**\n\n` +
          `I've noted your request: "${input.userMessage.substring(0, 200)}"\n\n` +
          `Per Standing Orders §3 (Blast Radius), all write operations require:\n` +
          `• Save-point creation before execution\n` +
          `• Audit trail entry\n` +
          `• Maximum 10 entities per operation\n\n` +
          `Please use the relevant module in Ghost Control → Operations to execute this action with full safety controls.`;
      }
      confidence = confidence || 0.8;
      source = source || (ragContext.chunkCount > 0 ? 'rag+rules' : 'rules');
      break;
    }

    case 'escalation': {
      reply = `**⚠️ Escalation Acknowledged**\n\n` +
        `${input.agentName} has flagged this for priority handling.\n\n` +
        `• **Message**: ${input.userMessage.substring(0, 300)}\n` +
        `• **Agent Domain**: ${domain}\n` +
        `• **Standing Order §6**: Escalation sent to CEO (Tes) for cross-domain resolution.\n\n` +
        `This escalation has been recorded in the audit trail.`;
      confidence = 0.85;
      source = 'rules';
      break;
    }

    case 'analysis_request': {
      // Analysis benefits from RAG context but often needs LLM for deep reasoning
      const liveData = await fetchDomainData(domain);
      reply = `**${input.agentName} — Analysis**\n\n`;
      
      if (ragContext.chunkCount > 0) {
        reply += `Based on ${BRAND.companyName} business rules and current data:\n\n`;
        const entries = Object.entries(liveData);
        if (entries.length > 0) {
          reply += `**Current Metrics:**\n` +
            entries.map(([k, v]) => `• ${k.replace(/([A-Z])/g, ' $1').trim()}: ${v}`).join('\n');
        }
        reply += `\n\n**Business Context:**\n${ragContext.contextText.substring(0, 600)}`;
        reply += `\n\nFor deeper analytical reasoning, an operator can enable external LLM in Configuration → AI & LLM.`;
        confidence = 0.55;
        source = 'rag+rules';
      } else {
        reply += `I can provide basic metrics for ${domain}. For deep trend analysis and forecasting, ` +
          `enable external LLM in Configuration → AI & LLM.`;
        confidence = 0.3;
        source = 'rules';
      }
      break;
    }

    case 'complex': {
      // Complex queries are honest about needing LLM
      reply = `**${input.agentName} — Complex Query**\n\n` +
        `This request requires reasoning capabilities beyond my deterministic rules.\n\n` +
        `**What I can tell you from RAG + rules:**\n`;
      if (ragContext.chunkCount > 0) {
        reply += ragContext.contextText.substring(0, 500);
      } else {
        reply += `No specific business context found for this query.`;
      }
      reply += `\n\n**To get a full AI-powered response:**\n` +
        `Enable external LLM for agents in Configuration → AI & LLM.\n` +
        `This uses cloud LLM credits but provides deeper reasoning.`;
      confidence = 0.2;
      source = ragContext.chunkCount > 0 ? 'rag' : 'rules';
      break;
    }

    default: {
      // General — provide what context we have
      reply = `**${input.agentName}** (${input.agentTitle})\n\n`;
      if (ragContext.chunkCount > 0) {
        reply += `Here's what I know that may be relevant:\n\n${ragContext.contextText.substring(0, 600)}`;
        confidence = 0.5;
        source = 'rag';
      } else {
        reply += `I'm ${input.agentName}, responsible for ${domain} operations. ` +
          `My capabilities include: ${rules.capabilities.join(', ')}.\n\n` +
          `Try asking me about the current status of ${domain}, or use Ghost Control → Operations for actions.`;
        confidence = 0.6;
        source = 'rules';
      }
      break;
    }
  }

  // Append memory context if relevant
  if (input.memories.length > 0 && intent !== 'greeting') {
    const recentMemories = input.memories.slice(0, 3);
    reply += `\n\n**From my memory:**\n` +
      recentMemories.map(m => `• [${m.category}] ${typeof m.content === 'string' ? m.content.substring(0, 100) : JSON.stringify(m.content).substring(0, 100)}`).join('\n');
  }

  return {
    reply,
    confidence,
    source,
    ragCitations,
    requiresLLM: confidence < 0.5,
    intent,
    tokensUsed: 0,
    costUsd: 0,
  };
}
