const fs = require('fs');
const {
  BASE1_DATA_PATH,
  getBase1NetworkStatus,
  recordBase1NetworkMessage,
  registerBase1Peer,
  removeBase1Peer,
  resetBase1State,
  verifyBase1Chain,
} = require('../src/lib/base1_state');

function main() {
  const hadState = fs.existsSync(BASE1_DATA_PATH);
  const backup = hadState ? fs.readFileSync(BASE1_DATA_PATH, 'utf8') : null;

  try {
    resetBase1State();
    const add = registerBase1Peer({ url: 'http://localhost:3001', name: 'sample-peer' });
    if (!add.ok || add.peers.length !== 1) throw new Error('Expected peer to be registered');
    const message = recordBase1NetworkMessage({
      direction: 'outbound',
      peer: add.peer.url,
      type: 'P2P_HEAD',
      status: 'queued',
      detail: { sample: true },
    });
    const network = getBase1NetworkStatus();
    if (network.peers.length !== 1 || network.messages[0].id !== message.id) {
      throw new Error('Expected network status to include peer and message');
    }
    const remove = removeBase1Peer({ url: 'http://localhost:3001' });
    if (!remove.ok || remove.peers.length !== 0) throw new Error('Expected peer to be removed');
    const chain = verifyBase1Chain();
    if (!chain.ok) throw new Error(`Chain verification failed: ${chain.code}`);

    console.table([
      {
        phase: 'registered',
        peers: add.peers.length,
        messages: 0,
        node: network.node.node_id.slice(0, 16),
      },
      {
        phase: 'message recorded',
        peers: network.peers.length,
        messages: network.messages.length,
        node: network.node.node_id.slice(0, 16),
      },
      {
        phase: 'removed',
        peers: remove.peers.length,
        messages: getBase1NetworkStatus().messages.length,
        node: chain.head_hash.slice(0, 16),
      },
    ]);
  } finally {
    if (hadState) {
      fs.writeFileSync(BASE1_DATA_PATH, backup, 'utf8');
    } else if (fs.existsSync(BASE1_DATA_PATH)) {
      fs.unlinkSync(BASE1_DATA_PATH);
    }
  }
}

main();
