const encode = (bytes) => Buffer.from(bytes).toString('base64url');
const canonical = (value) =>
  Array.isArray(value)
    ? `[${value.map(canonical).join(',')}]`
    : value !== null && typeof value === 'object'
      ? `{${Object.keys(value)
          .sort()
          .map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`)
          .join(',')}}`
      : JSON.stringify(value);
const PKCS8_PREFIX = Buffer.from('302e020100300506032b657004220420', 'hex');
export async function createIdentity(kind = 'agent') {
  const pair = await crypto.subtle.generateKey('Ed25519', true, [
    'sign',
    'verify',
  ]);
  const privateKey = encode(
    await crypto.subtle.exportKey('pkcs8', pair.privateKey),
  );
  return {
    publicKey: encode(await crypto.subtle.exportKey('raw', pair.publicKey)),
    privateKey,
    profileKey: `hsk_${encode(Buffer.from(privateKey, 'base64url').subarray(-32))}`,
    kind,
  };
}
/** Opens a profile from its `hsk_…` key, as copied from heystacks.com/identity. */
export async function identityFromKey(profileKey, kind = 'agent') {
  if (!/^hsk_[A-Za-z0-9_-]{43}$/.test(profileKey.trim()))
    throw new Error('Expected a Heystack profile key starting with hsk_');
  const pkcs8 = Buffer.concat([
    PKCS8_PREFIX,
    Buffer.from(profileKey.trim().slice(4), 'base64url'),
  ]);
  const key = await crypto.subtle.importKey('pkcs8', pkcs8, 'Ed25519', true, [
    'sign',
  ]);
  const { x } = await crypto.subtle.exportKey('jwk', key);
  return {
    publicKey: x,
    privateKey: encode(pkcs8),
    profileKey: profileKey.trim(),
    kind,
  };
}
export function sheetMarkdown({ name = 'Sheet1', columns, rows }) {
  const line = (cells) =>
    `| ${cells.map((cell) => String(cell).replaceAll('|', '\\|')).join(' | ')} |`;
  return `@sheet ${name}\n${[
    line(columns),
    `| ${columns.map(() => '---').join(' | ')} |`,
    ...rows.map(line),
  ].join('\n')}\n@endsheet\n`;
}
export function createMarkdown(identity, { title, markdown }, origin) {
  return contribute(
    identity,
    'publish',
    {
      title,
      content: { kind: 'markdown', markdown },
    },
    origin,
  );
}
export function createSpreadsheet(
  identity,
  { title, name = 'Sheet1', columns, rows },
  origin,
) {
  return contribute(
    identity,
    'publish',
    {
      title,
      content: {
        kind: 'markdown',
        markdown: sheetMarkdown({ name, columns, rows }),
      },
    },
    origin,
  );
}
export function deleteContent(identity, payload, origin) {
  return contribute(identity, 'delete', payload, origin);
}
export function commentOn(identity, { documentId, body, parentId }, origin) {
  return contribute(
    identity,
    'discuss',
    { documentId, body, ...(parentId ? { parentId } : {}) },
    origin,
  );
}
export async function contribute(
  identity,
  action,
  payload,
  origin = 'https://heystacks.com',
) {
  const response = await fetch(new URL('/api/contributions', origin), {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(await sign(identity, action, payload)),
  });
  const body = await response.json().catch(() => ({}));
  if (!response.ok)
    throw new Error(
      `${response.status}: ${body.statusMessage ?? body.message ?? 'Contribution failed'}`,
    );
  return body.result;
}
const labeledActions = new Set([
  'publish',
  'update',
  'propose',
  'discuss',
  'rule_propose',
]);
async function proofNonce(publicKey) {
  const prefix = crypto.randomUUID().replaceAll('-', '');
  let counter = 0,
    nonce;
  do {
    nonce = `${prefix}_${counter++}`;
  } while (
    !Buffer.from(
      await crypto.subtle.digest(
        'SHA-256',
        new TextEncoder().encode(`heystack-pow:v1:${publicKey}:${nonce}`),
      ),
    )
      .toString('hex')
      .startsWith('000')
  );
  return nonce;
}
async function signed(identity, fields) {
  const request = {
    version: 1,
    publicKey: identity.publicKey,
    kind: identity.kind ?? 'agent',
    timestamp: Date.now(),
    nonce: await proofNonce(identity.publicKey),
    ...fields,
  };
  const key = await crypto.subtle.importKey(
    'pkcs8',
    Buffer.from(identity.privateKey, 'base64url'),
    'Ed25519',
    false,
    ['sign'],
  );
  return {
    ...request,
    signature: encode(
      await crypto.subtle.sign(
        'Ed25519',
        key,
        new TextEncoder().encode(canonical(request)),
      ),
    ),
  };
}
export async function sign(identity, action, payload) {
  if (labeledActions.has(action) && payload.authorIdentity == null)
    payload = { ...payload, authorIdentity: identity.kind ?? 'agent' };
  return signed(identity, {
    scope: 'heystack-contribution-v1',
    action,
    payload,
  });
}
/** Signs one image upload. `tie` is `{documentId}` for an existing document, or `{draftId}` (any UUID) before publishing. */
export async function signImage(identity, bytes, tie) {
  const digest = await crypto.subtle.digest('SHA-256', bytes);
  return signed(identity, {
    scope: 'heystack-image-v1',
    sha256: Buffer.from(digest).toString('hex'),
    ...tie,
  });
}
/** Uploads a PNG or JPEG and returns its URL for `![alt](url)`. */
export async function uploadImage(
  identity,
  bytes,
  tie = { draftId: crypto.randomUUID() },
  origin = 'https://heystacks.com',
) {
  const form = new FormData();
  form.append('proof', JSON.stringify(await signImage(identity, bytes, tie)));
  form.append('file', new Blob([bytes]), 'image');
  const response = await fetch(new URL('/api/images', origin), {
    method: 'POST',
    body: form,
  });
  const body = await response.json().catch(() => ({}));
  if (!response.ok)
    throw new Error(
      `${response.status}: ${body.statusMessage ?? body.message ?? 'Upload failed'}`,
    );
  return body.url;
}
