import { BRAND, VOCAB } from '@/lib/white-label/constants';

/**
 * ERP Module Registry
 * 
 * Master registry of all available modules in the ${BRAND.primaryName} ERP system.
 * Each module is a self-contained functional domain that can be enabled/disabled.
 * Core modules cannot be disabled. Modules declare dependencies on other modules.
 * 
 * The Configuration Module acts as the "org chart editor" for the agent hierarchy —
 * when a module is enabled, its corresponding Domain Agent activates.
 * When disabled, the agent goes dormant.
 */

export interface ModuleDefinition {
  moduleId: string;
  name: string;
  description: string;
  category: 'core' | 'operations' | 'intelligence' | 'addon';
  icon: string; // lucide icon name
  isCore: boolean;
  defaultEnabled: boolean;
  sortOrder: number;
  dependencies: string[]; // moduleIds this module requires
  agentId?: string; // corresponding domain agent
  features: string[]; // key capabilities
  prismaModels: string[]; // DB models this module owns
  apiRoutes: string[]; // API route prefixes
  uiRoutes: string[]; // UI page paths
  tier: 'starter' | 'professional' | 'enterprise'; // minimum tier required
}

export const MODULE_REGISTRY: ModuleDefinition[] = [
  // ===== CORE MODULES (always on) =====
  {
    moduleId: 'configuration',
    name: 'Configuration & Settings',
    description: 'Module management, feature flags, organization settings, and system preferences. The backbone of the entire platform.',
    category: 'core',
    icon: 'Settings',
    isCore: true,
    defaultEnabled: true,
    sortOrder: 0,
    dependencies: [],
    features: ['Module toggle', 'Feature flags', 'Org settings', 'Theme customization', 'Agent deployment manifest'],
    prismaModels: ['ModuleConfig', 'Organization'],
    apiRoutes: ['/api/modules'],
    uiRoutes: ['/ghost-control/configuration'],
    tier: 'starter',
  },
  {
    moduleId: 'identity',
    name: 'Identity & Access',
    description: 'Authentication, role-based access control, permissions, audit logging, and behavioral fingerprinting.',
    category: 'core',
    icon: 'Shield',
    isCore: true,
    defaultEnabled: true,
    sortOrder: 1,
    dependencies: [],
    features: ['SSO', 'RBAC', 'Audit trails', 'Session management', 'Behavioral fingerprinting'],
    prismaModels: ['GfsUser', 'Role', 'Permission', 'UserRole', 'RolePermission', 'AuditLog', 'BehavioralFingerprint', 'UserSession'],
    apiRoutes: ['/api/gfs/identity', '/api/auth'],
    uiRoutes: [],
    tier: 'starter',
  },
  {
    moduleId: 'agent-core',
    name: 'Agent Orchestration',
    description: 'The Foundry agent hierarchy system. Agent CEO (Tes) coordinates domain-specific sub-agents, each with persistent memory and autonomous reasoning.',
    category: 'core',
    icon: 'Brain',
    isCore: true,
    defaultEnabled: true,
    sortOrder: 2,
    dependencies: ['identity'],
    agentId: 'agent-ceo',
    features: ['Agent hierarchy', 'Persistent memory', 'Cross-agent messaging', 'Escalation protocols', 'Self-evolution'],
    prismaModels: ['DomainAgent', 'DomainAgentMemory', 'DomainAgentMessage', 'Agent', 'AgentTemplate'],
    apiRoutes: ['/api/agents'],
    uiRoutes: ['/ghost-control/agents'],
    tier: 'starter',
  },

  // ===== OPERATIONS MODULES =====
  {
    moduleId: 'finance',
    name: 'Finance & Accounting',
    description: 'Chart of accounts, general ledger, transactions, invoicing, budgeting, and financial reporting. Agent Finance monitors cash flow and flags anomalies.',
    category: 'operations',
    icon: 'Wallet',
    isCore: false,
    defaultEnabled: true,
    sortOrder: 10,
    dependencies: ['identity'],
    agentId: 'agent-finance',
    features: ['Chart of accounts', 'General ledger', 'Invoicing', 'Budget tracking', 'Multi-currency', 'Financial reports'],
    prismaModels: ['Account', 'Transaction', 'Invoice', 'Budget'],
    apiRoutes: ['/api/erp/finance'],
    uiRoutes: ['/ghost-control/operations/finance'],
    tier: 'starter',
  },
  {
    moduleId: 'hr',
    name: 'Human Resources',
    description: 'Employee management, payroll processing, time tracking, leave management, and department organization. Agent HR knows your people.',
    category: 'operations',
    icon: 'Users',
    isCore: false,
    defaultEnabled: true,
    sortOrder: 11,
    dependencies: ['identity'],
    agentId: 'agent-hr',
    features: ['Employee directory', 'Payroll processing', 'Time tracking', 'Leave management', 'Department hierarchy'],
    prismaModels: ['Employee', 'Department', 'PayrollRecord', 'TimeEntry', 'LeaveRequest'],
    apiRoutes: ['/api/erp/hr'],
    uiRoutes: ['/ghost-control/operations/hr'],
    tier: 'starter',
  },
  {
    moduleId: 'inventory',
    name: 'Inventory & Supply Chain',
    description: 'Product catalog, stock levels, supplier management, purchase orders, and stock movement tracking. Agent Inventory predicts shortages before they happen.',
    category: 'operations',
    icon: 'Package',
    isCore: false,
    defaultEnabled: true,
    sortOrder: 12,
    dependencies: ['identity'],
    agentId: 'agent-inventory',
    features: ['Product catalog', 'Stock tracking', 'Supplier management', 'Purchase orders', 'Reorder alerts', 'Stock movements'],
    prismaModels: ['Product', 'InventoryItem', 'StockMovement', 'Supplier', 'PurchaseOrder', 'PurchaseOrderItem'],
    apiRoutes: ['/api/erp/inventory'],
    uiRoutes: ['/ghost-control/operations/inventory'],
    tier: 'starter',
  },
  {
    moduleId: 'crm',
    name: 'CRM & Sales',
    description: 'Customer management, sales pipeline, leads, opportunities, quotes, and sales orders. Agent Sales optimizes your pipeline and forecasts revenue.',
    category: 'operations',
    icon: 'TrendingUp',
    isCore: false,
    defaultEnabled: true,
    sortOrder: 13,
    dependencies: ['identity'],
    agentId: 'agent-crm',
    features: ['Customer database', 'Lead management', 'Opportunity pipeline', 'Quote generation', 'Sales orders', 'Revenue forecasting'],
    prismaModels: ['Customer', 'Contact', 'Lead', 'Opportunity', 'Quote', 'QuoteItem', 'SalesOrder', 'SalesOrderItem'],
    apiRoutes: ['/api/erp/crm'],
    uiRoutes: ['/ghost-control/operations/crm'],
    tier: 'starter',
  },
  {
    moduleId: 'documents',
    name: 'Document Management',
    description: 'Document storage, version control, contract lifecycle management, and compliance documentation.',
    category: 'operations',
    icon: 'FileText',
    isCore: false,
    defaultEnabled: true,
    sortOrder: 14,
    dependencies: ['identity'],
    agentId: 'agent-operations',
    features: ['Document storage', 'Version history', 'Contract management', 'Full-text search', 'Compliance docs'],
    prismaModels: ['Document', 'Contract'],
    apiRoutes: ['/api/erp/documents'],
    uiRoutes: ['/ghost-control/operations/documents'],
    tier: 'starter',
  },
  {
    moduleId: 'approvals',
    name: 'Approval Workflows',
    description: 'Multi-step approval chains for purchases, expenses, contracts, and any configurable business process.',
    category: 'operations',
    icon: 'CheckSquare',
    isCore: false,
    defaultEnabled: true,
    sortOrder: 15,
    dependencies: ['identity'],
    features: ['Configurable workflows', 'Multi-step approvals', 'Auto-escalation', 'Audit trail', 'Delegation rules'],
    prismaModels: ['ApprovalWorkflow', 'ApprovalRequest', 'ApprovalStep'],
    apiRoutes: ['/api/erp/approvals'],
    uiRoutes: ['/ghost-control/operations/approvals'],
    tier: 'professional',
  },

  // ===== NEW MODULES (to be built) =====
  {
    moduleId: 'projects',
    name: 'Project Management',
    description: 'Projects, tasks, milestones, resource allocation, time budgets, and Gantt-style tracking. Agent Projects keeps everything on schedule.',
    category: 'operations',
    icon: 'FolderKanban',
    isCore: false,
    defaultEnabled: false,
    sortOrder: 16,
    dependencies: ['identity', 'hr'],
    agentId: 'agent-projects',
    features: ['Project planning', 'Task boards', 'Milestones', 'Resource allocation', 'Time budgets', 'Gantt charts'],
    prismaModels: [],
    apiRoutes: ['/api/erp/projects'],
    uiRoutes: ['/ghost-control/operations/projects'],
    tier: 'professional',
  },
  {
    moduleId: 'expenses',
    name: 'Expense Management',
    description: 'Expense reports, receipt capture, policy enforcement, mileage tracking, and reimbursement workflows.',
    category: 'operations',
    icon: 'Receipt',
    isCore: false,
    defaultEnabled: false,
    sortOrder: 17,
    dependencies: ['finance', 'hr'],
    agentId: 'agent-finance',
    features: ['Expense reports', 'Receipt capture', 'Policy enforcement', 'Mileage tracking', 'Auto-categorization'],
    prismaModels: [],
    apiRoutes: ['/api/erp/expenses'],
    uiRoutes: ['/ghost-control/operations/expenses'],
    tier: 'professional',
  },
  {
    moduleId: 'payables-receivables',
    name: 'AP/AR Management',
    description: 'Accounts payable, accounts receivable, aging reports, payment scheduling, dunning, and bank reconciliation.',
    category: 'operations',
    icon: 'ArrowLeftRight',
    isCore: false,
    defaultEnabled: false,
    sortOrder: 18,
    dependencies: ['finance'],
    agentId: 'agent-finance',
    features: ['AP aging', 'AR aging', 'Payment scheduling', 'Dunning automation', 'Bank reconciliation'],
    prismaModels: [],
    apiRoutes: ['/api/erp/ap-ar'],
    uiRoutes: ['/ghost-control/operations/ap-ar'],
    tier: 'professional',
  },
  {
    moduleId: 'manufacturing',
    name: 'Manufacturing & BOM',
    description: 'Bill of materials, work orders, production runs, routing, quality checks, and shop floor management.',
    category: 'operations',
    icon: 'Factory',
    isCore: false,
    defaultEnabled: false,
    sortOrder: 19,
    dependencies: ['inventory'],
    agentId: 'agent-inventory',
    features: ['Bill of Materials', 'Work orders', 'Production runs', 'Quality checks', 'Shop floor tracking'],
    prismaModels: [],
    apiRoutes: ['/api/erp/manufacturing'],
    uiRoutes: ['/ghost-control/operations/manufacturing'],
    tier: 'enterprise',
  },
  {
    moduleId: 'assets',
    name: 'Asset Management',
    description: 'Fixed asset tracking, depreciation schedules, maintenance planning, asset lifecycle, and disposal management.',
    category: 'operations',
    icon: 'Building2',
    isCore: false,
    defaultEnabled: false,
    sortOrder: 20,
    dependencies: ['finance'],
    agentId: 'agent-finance',
    features: ['Asset register', 'Depreciation calc', 'Maintenance scheduling', 'Lifecycle tracking', 'Disposal workflows'],
    prismaModels: [],
    apiRoutes: ['/api/erp/assets'],
    uiRoutes: ['/ghost-control/operations/assets'],
    tier: 'professional',
  },
  {
    moduleId: 'quality',
    name: 'Quality Management',
    description: 'QC inspections, non-conformance reports, corrective/preventive actions (CAPA), and quality metrics dashboards.',
    category: 'operations',
    icon: 'BadgeCheck',
    isCore: false,
    defaultEnabled: false,
    sortOrder: 21,
    dependencies: ['inventory'],
    features: ['QC inspections', 'NCR tracking', 'CAPA management', 'Quality metrics', 'Supplier quality'],
    prismaModels: [],
    apiRoutes: ['/api/erp/quality'],
    uiRoutes: ['/ghost-control/operations/quality'],
    tier: 'enterprise',
  },
  {
    moduleId: 'helpdesk',
    name: 'Ticketing & Help Desk',
    description: 'Support tickets, SLA tracking, knowledge base, customer portal, and satisfaction surveys.',
    category: 'operations',
    icon: 'LifeBuoy',
    isCore: false,
    defaultEnabled: false,
    sortOrder: 22,
    dependencies: ['crm'],
    agentId: 'agent-sales',
    features: ['Ticket management', 'SLA tracking', 'Knowledge base', 'Customer portal', 'CSAT surveys'],
    prismaModels: [],
    apiRoutes: ['/api/erp/helpdesk'],
    uiRoutes: ['/ghost-control/operations/helpdesk'],
    tier: 'professional',
  },
  {
    moduleId: 'ecommerce',
    name: 'E-Commerce & Storefront',
    description: 'Online catalog, shopping cart, checkout, order fulfillment, and shipping integration.',
    category: 'addon',
    icon: 'ShoppingCart',
    isCore: false,
    defaultEnabled: false,
    sortOrder: 30,
    dependencies: ['inventory', 'crm'],
    agentId: 'agent-sales',
    features: ['Product catalog', 'Shopping cart', 'Checkout', 'Order fulfillment', 'Shipping integration'],
    prismaModels: [],
    apiRoutes: ['/api/erp/ecommerce'],
    uiRoutes: ['/ghost-control/operations/ecommerce'],
    tier: 'enterprise',
  },
  {
    moduleId: 'fleet',
    name: 'Fleet & Logistics',
    description: 'Vehicle tracking, route optimization, delivery management, driver assignments, and fuel tracking.',
    category: 'addon',
    icon: 'Truck',
    isCore: false,
    defaultEnabled: false,
    sortOrder: 31,
    dependencies: ['inventory'],
    features: ['Vehicle tracking', 'Route optimization', 'Delivery management', 'Driver assignments', 'Fuel tracking'],
    prismaModels: [],
    apiRoutes: ['/api/erp/fleet'],
    uiRoutes: ['/ghost-control/operations/fleet'],
    tier: 'enterprise',
  },
  {
    moduleId: 'tax',
    name: 'Tax & Compliance',
    description: 'Tax calculation, filing preparation, regulatory reporting, multi-jurisdiction support, and compliance tracking.',
    category: 'addon',
    icon: 'Scale',
    isCore: false,
    defaultEnabled: false,
    sortOrder: 32,
    dependencies: ['finance'],
    agentId: 'agent-compliance',
    features: ['Tax calculation', 'Filing prep', 'Multi-jurisdiction', 'Regulatory reports', 'Compliance calendar'],
    prismaModels: [],
    apiRoutes: ['/api/erp/tax'],
    uiRoutes: ['/ghost-control/operations/tax'],
    tier: 'enterprise',
  },

  // ===== INTELLIGENCE MODULES =====
  {
    moduleId: 'sentinel',
    name: `${VOCAB.observer} (Security & Compliance)`,
    description: 'Continuous monitoring, anomaly detection, threat analysis, compliance enforcement, and security events. Agent Compliance never sleeps.',
    category: 'intelligence',
    icon: 'Eye',
    isCore: false,
    defaultEnabled: true,
    sortOrder: 40,
    dependencies: ['identity'],
    agentId: 'agent-compliance',
    features: ['Anomaly detection', 'Threat analysis', 'Compliance rules', 'Security alerts', 'Behavioral analysis'],
    prismaModels: [`${VOCAB.observer}Alert`, `${VOCAB.observer}Rule`, 'SecurityEvent'],
    apiRoutes: ['/api/gfs/sentinel'],
    uiRoutes: ['/ghost-control/heartbeat'],
    tier: 'starter',
  },
  {
    moduleId: 'intelligence-briefs',
    name: 'Intelligence Briefs',
    description: 'Weekly executive summaries, market intelligence, operational insights, and proactive recommendations powered by Agent CEO.',
    category: 'intelligence',
    icon: 'Newspaper',
    isCore: false,
    defaultEnabled: true,
    sortOrder: 41,
    dependencies: ['agent-core'],
    agentId: 'agent-ceo',
    features: ['Weekly summaries', 'Market intelligence', 'Ops insights', 'Proactive recommendations', 'Trend analysis'],
    prismaModels: ['IntelligenceBrief'],
    apiRoutes: ['/api/intelligence-brief'],
    uiRoutes: [],
    tier: 'professional',
  },
  {
    moduleId: 'reporting',
    name: 'Reporting & BI',
    description: 'Custom report builder, KPI dashboards, scheduled reports, data export, and cross-module analytics.',
    category: 'intelligence',
    icon: 'BarChart3',
    isCore: false,
    defaultEnabled: false,
    sortOrder: 42,
    dependencies: ['agent-core'],
    agentId: 'agent-ceo',
    features: ['Report builder', 'KPI dashboards', 'Scheduled reports', 'Data export', 'Cross-module analytics'],
    prismaModels: [],
    apiRoutes: ['/api/erp/reporting'],
    uiRoutes: ['/ghost-control/operations/reporting'],
    tier: 'professional',
  },
  {
    moduleId: 'dark-factory',
    name: `${VOCAB.factory} (Code Gen)`,
    description: 'AI-powered code generation system. Describe what you need, and the Weft engine builds it with multi-LLM selection and deployment targets.',
    category: 'intelligence',
    icon: 'Wand2',
    isCore: false,
    defaultEnabled: true,
    sortOrder: 43,
    dependencies: ['agent-core'],
    features: ['Weft engine', 'Template library', 'Multi-LLM selection', 'Version history', 'Multi-platform deploy'],
    prismaModels: ['DarkFactoryProject', 'GenerationRequest', 'GenerationTask', 'GeneratedArtifact'],
    apiRoutes: ['/api/dark-factory'],
    uiRoutes: ['/ghost-control/dark-factory'],
    tier: 'professional',
  },

  // ===== POS MODULE =====
  {
    moduleId: 'pos',
    name: 'Point of Sale',
    description: 'Commercial POS terminal for retail and restaurant. Touchscreen-optimized register with menu management, split payments, tips, voids/refunds, order transfers, and multi-printer ticketing.',
    category: 'operations',
    icon: 'Monitor',
    isCore: false,
    defaultEnabled: false,
    sortOrder: 15,
    dependencies: ['finance', 'inventory'],
    agentId: 'agent-ledger',
    features: ['Touchscreen register', 'Menu management', 'Split payments', 'Tip handling', 'Void/refund workflow', 'Order transfers', 'Multi-printer tickets', 'Station management', 'Barcode scanning'],
    prismaModels: ['POSCategory', 'POSMenuItem', 'POSStation', 'POSOrder', 'POSOrderItem', 'POSPayment'],
    apiRoutes: ['/api/pos'],
    uiRoutes: ['/ghost-control/operations/pos'],
    tier: 'professional',
  },

];

/**
 * Get a module definition by its ID
 */
export function getModule(moduleId: string): ModuleDefinition | undefined {
  return MODULE_REGISTRY.find(m => m.moduleId === moduleId);
}

/**
 * Get all modules in a category
 */
export function getModulesByCategory(category: ModuleDefinition['category']): ModuleDefinition[] {
  return MODULE_REGISTRY.filter(m => m.category === category).sort((a, b) => a.sortOrder - b.sortOrder);
}

/**
 * Resolve all dependencies for a module (recursive)
 */
export function resolveDependencies(moduleId: string, resolved: Set<string> = new Set()): string[] {
  const mod = getModule(moduleId);
  if (!mod) return [];
  
  const deps: string[] = [];
  for (const depId of mod.dependencies) {
    if (!resolved.has(depId)) {
      resolved.add(depId);
      deps.push(...resolveDependencies(depId, resolved));
      deps.push(depId);
    }
  }
  return deps;
}

/**
 * Check if enabling a module would create any unmet dependencies
 */
export function checkDependencies(moduleId: string, enabledModules: Set<string>): { satisfied: boolean; missing: string[] } {
  const mod = getModule(moduleId);
  if (!mod) return { satisfied: false, missing: [`Module '${moduleId}' not found`] };
  
  const missing = mod.dependencies.filter(depId => !enabledModules.has(depId));
  return { satisfied: missing.length === 0, missing };
}

/**
 * Check if disabling a module would break any dependents
 */
export function checkDependents(moduleId: string, enabledModules: Set<string>): { safe: boolean; dependents: string[] } {
  const dependents = MODULE_REGISTRY
    .filter(m => m.dependencies.includes(moduleId) && enabledModules.has(m.moduleId))
    .map(m => m.moduleId);
  return { safe: dependents.length === 0, dependents };
}

/**
 * Get the full module count by status
 */
export function getModuleStats(enabledModules: Set<string>) {
  const total = MODULE_REGISTRY.length;
  const enabled = MODULE_REGISTRY.filter(m => enabledModules.has(m.moduleId)).length;
  const core = MODULE_REGISTRY.filter(m => m.isCore).length;
  const available = total - enabled;
  
  return { total, enabled, core, available };
}
