'use strict';

const { validateManifest } = require('./manifest-validator');

const ACTIVATION_TRIGGERS = new Set([
  'startup',
  'provider',
  'agentHarness',
  'command',
  'channel',
  'route',
  'configPath',
  'capability',
]);

function normalizePluginManifest(manifest = {}, opts = {}) {
  const base = validateManifest(manifest, opts);
  const diagnostics = [...base.diagnostics];
  const pluginId = typeof manifest.id === 'string' ? manifest.id : undefined;
  const source = opts.source || 'unknown';

  if (manifest.activation !== undefined) {
    const activation = Array.isArray(manifest.activation) ? manifest.activation : [];
    if (!Array.isArray(manifest.activation)) {
      diagnostics.push({ level: 'error', message: 'activation must be an array', fieldPath: 'activation', pluginId, source });
    }
    for (const item of activation) {
      if (!item || typeof item !== 'object' || !ACTIVATION_TRIGGERS.has(item.type)) {
        diagnostics.push({ level: 'error', message: `unsupported activation trigger: ${item?.type}`, fieldPath: 'activation', pluginId, source });
      }
    }
  }

  if (manifest.modelSupport !== undefined) {
    const support = manifest.modelSupport;
    const valid = support && typeof support === 'object' && (
      Array.isArray(support.prefixes) || Array.isArray(support.patterns) || Array.isArray(support.models)
    );
    if (!valid) diagnostics.push({ level: 'error', message: 'modelSupport must declare prefixes, patterns, or models', fieldPath: 'modelSupport', pluginId, source });
  }

  if (manifest.modelCatalog !== undefined && !Array.isArray(manifest.modelCatalog)) {
    diagnostics.push({ level: 'error', message: 'modelCatalog must be an array', fieldPath: 'modelCatalog', pluginId, source });
  }

  if (manifest.configSchema !== undefined && (!manifest.configSchema || typeof manifest.configSchema !== 'object')) {
    diagnostics.push({ level: 'error', message: 'configSchema must be an object', fieldPath: 'configSchema', pluginId, source });
  }

  if (manifest.permissions !== undefined) {
    for (const [key, value] of Object.entries(manifest.permissions || {})) {
      if (typeof value !== 'boolean') {
        diagnostics.push({ level: 'error', message: `permission ${key} must be boolean`, fieldPath: `permissions.${key}`, pluginId, source });
      }
    }
  }

  const errorCount = diagnostics.filter(d => d.level === 'error').length;
  return {
    valid: errorCount === 0,
    manifest: errorCount === 0 ? manifest : undefined,
    diagnostics,
  };
}

module.exports = {
  ACTIVATION_TRIGGERS,
  normalizePluginManifest,
};
