/**
 * Alice — sender. Uploads a local file to Bob using 4 parallel lanes,
 * 1 MiB chunks, and the default HTTP transport. Prints sender-side
 * progress + the verified sha256 on completion.
 *
 * Usage:
 *   bun run examples/07-streams-upload/alice-sender.ts <path/to/file>
 */
import { readFile } from 'node:fs/promises';
import { basename } from 'node:path';
import { createShade } from '@shade/sdk';

const PREKEY_URL = 'http://localhost:9991';
const BOB_BASE_URL = 'http://localhost:9992';

const filePath = process.argv[2];
if (filePath === undefined || filePath === '') {
  console.error('usage: alice-sender.ts <path/to/file>');
  process.exit(2);
}

const bytes = await readFile(filePath);
const name = basename(filePath);

const alice = await createShade({ prekeyServer: PREKEY_URL, address: 'alice' });

alice.configureTransfers({
  resolveBaseUrl: async (peer) => {
    if (peer === 'bob') return BOB_BASE_URL;
    throw new Error(`unknown peer ${peer}`);
  },
});

console.log(`[alice] uploading ${name} (${bytes.length} bytes) → bob`);

const handle = await alice.upload({
  to: 'bob',
  input: new Uint8Array(bytes),
  lanes: 4,
  chunkSize: 1024 * 1024,
  metadata: { name },
  onProgress: (p) => {
    const pct = p.percent !== undefined ? `${(p.percent * 100).toFixed(1)}%` : '—';
    const mbps = (p.bytesPerSecond / (1024 * 1024)).toFixed(2);
    process.stdout.write(`\r[alice] ${pct}   ${mbps} MB/s   ${p.bytesSent}/${p.bytesTotal ?? '?'} B`);
  },
});

const result = await handle.done();
process.stdout.write('\n');
console.log(`[alice] done — ${result.bytesSent} B in ${result.durationMs.toFixed(0)} ms`);
console.log(`[alice] sha256 = ${result.sha256}`);

await alice.shutdown();
