import { describe, it, expect } from 'vitest';
import { ComponentRegistry } from './registry.js';

describe('ComponentRegistry', () => {
  it('matches exact rules deterministically', () => {
    const registry = new ComponentRegistry({ matchThreshold: 0.5 });
    registry.loadRules([
      {
        name: 'status-help',
        patterns: ['status'],
        target: { type: 'agent', name: 'assistant' },
        priority: 1,
        enabled: true,
      },
    ]);

    const match = registry.match('status');
    expect(match?.rule.name).toBe('status-help');
    expect(match?.matchedPattern).toBe('status');
    expect(match?.score).toBe(1);
  });

  it('matches wildcard patterns', () => {
    const registry = new ComponentRegistry({ matchThreshold: 0.5 });
    registry.register({
      name: 'deploy-route',
      patterns: ['deploy *'],
      target: { type: 'agent', name: 'coder' },
      priority: 1,
      enabled: true,
    });

    const match = registry.match('deploy api service');
    expect(match?.rule.name).toBe('deploy-route');
    expect(match?.score).toBeGreaterThan(0.5);
    expect(match?.score).toBeLessThanOrEqual(1);
  });

  it('resolves ties by priority then specificity', () => {
    const registry = new ComponentRegistry({ matchThreshold: 0.5 });
    registry.loadRules([
      {
        name: 'low-priority',
        patterns: ['deploy *'],
        target: { type: 'agent', name: 'assistant' },
        priority: 1,
        enabled: true,
      },
      {
        name: 'high-priority',
        patterns: ['deploy *'],
        target: { type: 'agent', name: 'coder' },
        priority: 10,
        enabled: true,
      },
    ]);

    const match = registry.match('deploy dashboard');
    expect(match?.rule.name).toBe('high-priority');
  });

  it('returns null when no rule meets threshold', () => {
    const registry = new ComponentRegistry({ matchThreshold: 0.95 });
    registry.register({
      name: 'weak',
      patterns: ['deploy *'],
      target: { type: 'agent', name: 'coder' },
      priority: 1,
      enabled: true,
    });

    expect(registry.match('deploy dashboard')).toBeNull();
  });
});
