const crypto = require('crypto');
const fs = require('fs');
const path = require('path');

const SELFCLAW_API = 'https://selfclaw.ai/api/selfclaw/v1';
const keys = JSON.parse(fs.readFileSync(path.join(__dirname, '.selfclaw-keys.json'), 'utf8'));
const privKey = crypto.createPrivateKey({ key: Buffer.from(keys.privateKey, 'base64'), format: 'der', type: 'pkcs8' });

async function registerService(service) {
  const timestamp = Date.now();
  const nonce = crypto.randomBytes(16).toString('hex');
  
  // Sign exactly as the API requires: JSON.stringify({agentPublicKey, timestamp, nonce})
  const signPayload = JSON.stringify({ agentPublicKey: keys.publicKey, timestamp, nonce });
  const signature = crypto.sign(null, Buffer.from(signPayload), privKey).toString('hex');

  const body = {
    agentPublicKey: keys.publicKey,
    signature,
    timestamp,
    nonce,
    ...service
  };

  const res = await fetch(SELFCLAW_API + '/services', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body)
  });

  const text = await res.text();
  if (res.ok) {
    console.log('✅ Registered:', service.name);
  } else {
    console.log('❌', service.name, ':', res.status, text.substring(0, 200));
  }
}

(async () => {
  const services = [
    { name: 'Human Task Completion', description: 'Route tasks to verified human workers via Telegram & WhatsApp. 24-48hr turnaround with quality checks. Data labeling, content moderation, surveys, translation, research.', pricing: '100 VAE ($1 USD) minimum', currency: 'cUSD', endpoint: 'https://api.loopuman.com/api/v1/tasks/sync' },
    { name: 'Bulk Task API', description: 'Submit batches of up to 1000 tasks for parallel human completion. Enterprise SLA.', pricing: 'Volume discounts', currency: 'cUSD', endpoint: 'https://api.loopuman.com/api/v1/tasks/bulk' },
    { name: 'Human Verification Oracle', description: 'AI confidence low? Route to humans for ground-truth verification. Real-time results via webhook.', pricing: '50 VAE ($0.50 USD)', currency: 'cUSD', endpoint: 'https://api.loopuman.com/api/v1/tasks/sync' },
    { name: 'Voice-to-Task', description: 'Voice notes via WhatsApp auto-transcribed and posted as human tasks. Mobile-first for emerging markets.', pricing: 'Free transcription, standard task pricing', currency: 'cUSD', endpoint: 'https://api.loopuman.com/api/v1/voice-task' }
  ];

  for (const svc of services) {
    await registerService(svc);
  }
  console.log('\nDone! Check: https://selfclaw.ai/api/selfclaw/v1/services/c462e0a44f6ff85b');
})();
