'use strict';

function diagnoseHooks({ discoveryResult = {}, runtime = null } = {}) {
  const diagnostics = [...(discoveryResult.diagnostics || [])];
  if (runtime && typeof runtime.getDiagnostics === 'function') {
    diagnostics.push(...runtime.getDiagnostics());
  }
  const packages = discoveryResult.packages || [];
  const registered = runtime && typeof runtime.listHooks === 'function' ? runtime.listHooks() : [];
  const findings = [];

  for (const diagnostic of diagnostics) {
    const text = diagnostic.reason || diagnostic.message || '';
    const level = diagnostic.level || 'warn';
    findings.push({
      severity: level === 'error' ? 'high' : 'low',
      code: level === 'error' ? 'hook-diagnostic-error' : 'hook-diagnostic',
      message: text || 'Hook diagnostic',
      details: diagnostic,
    });
  }

  for (const hook of registered) {
    const permissions = hook.permissions || {};
    if (permissions.network || permissions.shell || permissions.writeWorkspace) {
      findings.push({
        severity: permissions.shell ? 'high' : 'medium',
        code: 'hook-risky-permission',
        message: `Hook ${hook.id} requests risky permissions`,
        details: { id: hook.id, permissions },
      });
    }
  }

  const summary = findings.reduce((acc, finding) => {
    acc.total += 1;
    acc[finding.severity] = (acc[finding.severity] || 0) + 1;
    return acc;
  }, { total: 0, high: 0, medium: 0, low: 0 });

  return {
    ok: summary.high === 0,
    packageCount: packages.length,
    registeredCount: registered.length,
    summary,
    findings,
  };
}

module.exports = {
  diagnoseHooks,
};
