import type { AgentCard } from '@a2a-js/sdk';
import type { A2aPrincipal } from './token-auth.js';
import { resolveEffectiveSpaces, resolveEffectiveSkills } from './delegation.js';

const PROTOCOL_VERSION = '0.3.0';

interface BaseDeps { baseUrl: string; issuer: string; version: string; }

export function buildBaseCard(deps: BaseDeps): AgentCard {
  return {
    name: 'MAESTRO',
    description: 'MAESTRO agent orchestration — A2A inbound interface',
    url: `${deps.baseUrl}/a2a`,
    version: deps.version,
    protocolVersion: PROTOCOL_VERSION,
    capabilities: { streaming: true, pushNotifications: false },
    defaultInputModes: ['text/plain'],
    defaultOutputModes: ['text/plain'],
    skills: [],
    supportsAuthenticatedExtendedCard: true,
    securitySchemes: {
      maestro_oauth: {
        type: 'oauth2',
        flows: {
          authorizationCode: {
            authorizationUrl: `${deps.issuer}/auth`,
            tokenUrl: `${deps.issuer}/token`,
            scopes: { 'a2a.read': 'Read-oriented A2A skills within the consented scope' },
          },
        },
      },
    },
    security: [{ maestro_oauth: ['a2a.read'] }],
  } as AgentCard;
}

interface ExtendedDeps extends BaseDeps {
  userVisibleSpaceIds: string[];
  allowlistsBySpace: Record<string, string[]>;
}

export function buildExtendedCard(principal: A2aPrincipal, deps: ExtendedDeps): AgentCard {
  const effectiveSpaces = resolveEffectiveSpaces(principal.delegation.grantedSpaceIds, deps.userVisibleSpaceIds);
  const effectiveSkills = resolveEffectiveSkills(principal.delegation.grantedSkills, deps.allowlistsBySpace, effectiveSpaces);
  const base = buildBaseCard(deps);
  return {
    ...base,
    skills: effectiveSkills.map(id => ({
      id,
      name: id,
      description: `MAESTRO piece "${id}" exposed as an A2A skill`,
      tags: ['maestro'],
    })),
  } as AgentCard;
}
