// Quick smoke test of parseAgentURI against real on-chain data.
// Run: node scripts/test-agent-uri.mjs

// Inline copy of parseAgentURI (can't import TS directly in node without build).
const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;

function fallbackName(address) { return `agent-${address.slice(2, 8).toLowerCase()}`; }
function cleanSlug(s) { return String(s || '').replace(/\.vns$/i, '').toLowerCase().trim(); }
function toStringArray(v) {
  if (Array.isArray(v)) return v.filter(x => typeof x === 'string' && x.trim()).map(x => String(x).trim());
  if (typeof v === 'string' && v.trim()) return v.split(/[,;\s]+/).filter(Boolean);
  return [];
}

function parseAgentURI(uri, address) {
  const raw = String(uri || '');
  if (raw.startsWith('{')) {
    try {
      const p = JSON.parse(raw);
      const rawName = cleanSlug(p.name || '');
      const name = rawName && SLUG_RE.test(rawName) ? rawName : fallbackName(address);
      return { name, description: p.description || p.desc || '', identityType: p.type, capabilities: toStringArray(p.capabilities ?? p.skills), version: p.version, protocol: p.protocol, raw };
    } catch {}
  }
  if (raw.startsWith('http://') || raw.startsWith('https://')) {
    try {
      const url = new URL(raw);
      const parts = url.pathname.split('/').filter(Boolean);
      const last = parts[parts.length - 1] || '';
      const cleaned = cleanSlug(last.replace(/\.json$/i, ''));
      return { name: cleaned && SLUG_RE.test(cleaned) ? cleaned : fallbackName(address), description: '', capabilities: [], raw };
    } catch {}
  }
  const cleaned = cleanSlug(raw);
  return { name: cleaned && SLUG_RE.test(cleaned) ? cleaned : fallbackName(address), description: '', capabilities: [], raw };
}

// Test cases — real representative data
const cases = [
  { label: 'sentinel JSON blob', uri: '{"name":"vaultfire-sentinel","description":"Core protocol monitoring agent","capabilities":["monitoring","metrics-reporting","bond-health","alerting"],"protocol":"vaultfire","version":"v3","type":"autonomous-sentinel"}', addr: '0xA054f831B562e729F8D268291EBde1B2EDcFb84F' },
  { label: 'JSON with .vns suffix in name', uri: '{"name":"foo-agent.vns","description":"test","capabilities":["solidity","auditing"]}', addr: '0x1234567890123456789012345678901234567890' },
  { label: 'plain vns name', uri: 'my-agent.vns', addr: '0x1111111111111111111111111111111111111111' },
  { label: 'plain slug', uri: 'simple-agent', addr: '0x2222222222222222222222222222222222222222' },
  { label: 'URL', uri: 'https://example.com/agents/cool-agent.json', addr: '0x3333333333333333333333333333333333333333' },
  { label: 'empty', uri: '', addr: '0x4444444444444444444444444444444444444444' },
  { label: 'bad JSON', uri: '{broken', addr: '0x5555555555555555555555555555555555555555' },
  { label: 'evil name injection', uri: '{"name":"foo\'; DROP TABLE--","capabilities":[]}', addr: '0x6666666666666666666666666666666666666666' },
  { label: 'skills instead of capabilities', uri: '{"name":"skilled","skills":["defi","bridging"]}', addr: '0x7777777777777777777777777777777777777777' },
  { label: 'comma-separated caps string', uri: '{"name":"commasep","capabilities":"a, b, c"}', addr: '0x8888888888888888888888888888888888888888' },
];

let pass = 0, fail = 0;
for (const c of cases) {
  const r = parseAgentURI(c.uri, c.addr);
  const nameIsSafe = SLUG_RE.test(r.name);
  console.log(`[${nameIsSafe ? 'PASS' : 'FAIL'}] ${c.label}: name="${r.name}"  caps=${JSON.stringify(r.capabilities)}  type=${r.identityType}`);
  if (nameIsSafe) pass++; else fail++;
}
console.log(`\n${pass}/${pass+fail} passed`);
process.exit(fail > 0 ? 1 : 0);
