const http = require('http');
const fs = require('fs');
const path = require('path');
const {
  checkHttpRequest,
  getMainnetSecurityStatus,
  readJsonBody,
  safeErrorBody,
  securityHeaders,
} = require('./lib/mainnet_security');
const { createBase1P2PNode } = require('./lib/p2p_network');
const {
  createWallet,
  payloadHash,
  signPayload,
  verifySignature,
} = require('./lib/wallet');
const { sha256 } = require('./lib/hash');
const {
  appendBase1ConfirmationBlock,
  base1NodeInfo,
  bootstrapBase1DefaultNetwork,
  bootstrapBase1PriorityRelays,
  bootstrapBase1SeedPeers,
  broadcastBase1SolveCandidate,
  batchBase1Sample,
  discoverBase1Heads,
  getBase1Account,
  getBase1Accounts,
  getBase1ChainBlocks,
  getBase1ChainSummary,
  getBase1Events,
  getBase1BlocksSince,
  getBase1FeeSchedule,
  getBase1FragmentDownload,
  getBase1FragmentRegistry,
  getBase1FragmentRecord,
  getBase1HeadProof,
  getBase1Leaderboard,
  getBase1NetworkStatus,
  getBase1RewardLedger,
  getBase1Reveals,
  getBase1SolveReceipts,
  getBase1PrivateVaultStatus,
  getBase1StorageStatus,
  getBase1TimeProof,
  getBase1WitnessStats,
  getCurrentBase1Public,
  resetBase1State,
  sampleBase1Point,
  snapshotBase1State,
  receiveBase1SolveCandidatePackage,
  recordBase1NetworkMessage,
  quarantineBase1Fragment,
  registerBase1Fragment,
  registerBase1Peer,
  removeBase1Peer,
  replayBase1Chain,
  submitBase1Candidate,
  submitBase1Blocks,
  submitBase1Transfer,
  syncBase1NetworkTime,
  upgradeBase1Fragment,
  verifyBase1Chain,
} = require('./lib/base1_state');
const {
  envOrConfigBool,
  envOrConfigNumber,
  getAppConfig,
  getNetworkConfig,
  getRuntimeConfigSnapshot,
} = require('./lib/config');

const ROOT = path.resolve(__dirname, '..');
const PUBLIC_DIR = path.join(ROOT, 'public');
const APP_CONFIG = getAppConfig().app || {};
const NETWORK_CONFIG = getNetworkConfig().network || {};
const PORT = envOrConfigNumber('PORT', APP_CONFIG.http_port, 3000, { min: 1, max: 65535, integer: true });
const SYNC_INTERVAL_MS = Math.max(0, Number(process.env.MAZEX_SYNC_INTERVAL_MS || 0));
const P2P_ENABLED = envOrConfigBool('MAZEX_P2P_ENABLED', NETWORK_CONFIG.p2p_enabled, false);
const P2P_PORT = envOrConfigNumber('MAZEX_P2P_PORT', NETWORK_CONFIG.p2p_port, PORT + 10000, {
  min: 1,
  max: 65535,
  integer: true,
});
const HEAD_QUERY_TTL = envOrConfigNumber('MAZEX_HEAD_QUERY_TTL', NETWORK_CONFIG.head_query_ttl, 2, {
  min: 0,
  integer: true,
});
const HEAD_QUERY_MAX_PEERS = envOrConfigNumber(
  'MAZEX_HEAD_QUERY_MAX_PEERS',
  NETWORK_CONFIG.head_query_max_peers,
  24,
  { min: 0, integer: true },
);
const HEAD_QUERY_TIMEOUT_MS = envOrConfigNumber(
  'MAZEX_HEAD_QUERY_TIMEOUT_MS',
  NETWORK_CONFIG.head_query_timeout_ms,
  3000,
  { min: 100, integer: true },
);
const p2pNode = P2P_ENABLED ? createBase1P2PNode({ port: P2P_PORT }) : null;

const MIME = {
  '.html': 'text/html; charset=utf-8',
  '.css': 'text/css; charset=utf-8',
  '.js': 'application/javascript; charset=utf-8',
  '.mjs': 'application/javascript; charset=utf-8',
  '.json': 'application/json; charset=utf-8',
  '.pdf': 'application/pdf',
  '.svg': 'image/svg+xml',
};

function sendJson(res, status, body) {
  res.writeHead(status, {
    'Content-Type': 'application/json; charset=utf-8',
    'Cache-Control': 'no-store',
    ...securityHeaders(),
  });
  res.end(JSON.stringify(body, null, 2));
}

function sendError(res, status, message) {
  sendJson(res, status, { ok: false, error: message });
}

function readBody(req) {
  return readJsonBody(req);
}

function candidateHashForSigning(candidate = {}) {
  return sha256({
    algorithm: candidate.algorithm || 'mazex-coordinate-expression-tree-2.0',
    trees: candidate.trees || {
      u: candidate.u_tree || null,
      v: candidate.v_tree || null,
    },
  });
}

function base1SigningPayload({
  current,
  chain,
  latestHeadGuard,
  candidate,
  nonce = 0,
  submitFee = 0,
  accountNonce = 0,
}) {
  return {
    type: 'BASE1_SUBMIT_CANDIDATE',
    chain_id: latestHeadGuard?.chain_id || 'mazexchain-base1-local',
    layer_no: Number(current.layer_no),
    step_no: Number(current.step_no),
    step_commit: current.step_commit,
    formula_hash: current.formula_hash,
    fragment_registry_root: current.fragment_registry_root || null,
    behavior_root: current.behavior_root || null,
    chain_head_hash: latestHeadGuard?.head_hash || chain?.head_hash || null,
    chain_height: Number(latestHeadGuard?.height ?? chain?.height ?? 0),
    chain_cumulative_work_score: Number(
      latestHeadGuard?.cumulative_work_score ?? chain?.cumulative_work_score ?? 0,
    ),
    candidate_hash: candidateHashForSigning(candidate),
    fee_currency: 'MAZEX',
    submit_fee: Math.max(0, Math.trunc(Number(submitFee || 0))),
    account_nonce: Math.max(0, Math.trunc(Number(accountNonce || 0))),
    fee_policy: 'deduct_from_success_reward',
    nonce: Math.max(0, Math.trunc(Number(nonce || 0))),
  };
}

function verifyBase1SignedSubmission({ signedPayload, current, chain, latestHeadGuard, candidate }) {
  if (!signedPayload) {
    return {
      ok: false,
      code: 'SIGNED_SUBMISSION_REQUIRED',
      message: 'Uploading an answer requires a mazexchain wallet signature',
    };
  }
  const signature = signedPayload.signature;
  const publicKey = signedPayload.public_key || signedPayload.publicKey;
  const address = signedPayload.address;
  const payload = signedPayload.payload;
  const signatureResult = verifySignature({ publicKey, address, payload, signature });
  if (!signatureResult.ok) return signatureResult;
  const account = getBase1Account(address);

  const expected = base1SigningPayload({
    current,
    chain,
    latestHeadGuard,
    candidate,
    nonce: payload?.nonce,
    submitFee: current.submit_cost,
    accountNonce: account.nonce + 1,
  });
  const expectedHash = payloadHash(expected);
  const actualHash = payloadHash(payload);
  const latestHeadHash = latestHeadGuard?.head_hash || chain?.head_hash || null;
  if (payload?.chain_head_hash && payload.chain_head_hash !== latestHeadHash) {
    return {
      ok: false,
      code: 'STALE_PARENT_BLOCK',
      message: 'Signed payload is attached to an old mazexchain head',
      signed_head_hash: payload.chain_head_hash,
      latest_head_hash: latestHeadHash,
      signed_height: payload.chain_height,
      latest_height: latestHeadGuard?.height ?? chain?.height,
    };
  }
  if (actualHash !== expectedHash) {
    return {
      ok: false,
      code: 'SIGNED_PAYLOAD_MISMATCH',
      message: 'Signed payload does not match the current Step and candidate answer',
      expected_payload_hash: expectedHash,
      actual_payload_hash: actualHash,
      expected_account_nonce: account.nonce + 1,
      actual_account_nonce: payload?.account_nonce,
      expected_submit_fee: current.submit_cost,
      actual_submit_fee: payload?.submit_fee,
    };
  }
  return {
    ok: true,
    auth_mode: 'wallet_signature',
    address,
    public_key: publicKey,
    payload_hash: actualHash,
  };
}

function base1TransferPayload({ publicState, from, to, amount, fee = 1, accountNonce }) {
  const latest = publicState.latest_head_guard || {};
  return {
    type: 'BASE1_TRANSFER',
    chain_id: latest.chain_id || 'mazexchain-base1-local',
    from,
    to,
    amount: Math.trunc(Number(amount || 0)),
    fee: Math.max(0, Math.trunc(Number(fee || 1))),
    account_nonce: Math.trunc(Number(accountNonce || 0)),
    chain_head_hash: latest.head_hash || publicState.chain?.head_hash || null,
    chain_height: Number(latest.height ?? publicState.chain?.height ?? 0),
    chain_cumulative_work_score: Number(latest.cumulative_work_score ?? publicState.chain?.cumulative_work_score ?? 0),
  };
}

function verifyBase1SignedTransfer({ signedPayload, publicState }) {
  if (!signedPayload) {
    return { ok: false, code: 'SIGNED_TRANSFER_REQUIRED', message: 'Transfer requires wallet signature' };
  }
  const signature = signedPayload.signature;
  const publicKey = signedPayload.public_key || signedPayload.publicKey;
  const address = signedPayload.address;
  const payload = signedPayload.payload;
  const signatureResult = verifySignature({ publicKey, address, payload, signature });
  if (!signatureResult.ok) return signatureResult;
  if (payload?.type !== 'BASE1_TRANSFER') {
    return { ok: false, code: 'INVALID_TRANSFER_PAYLOAD_TYPE', message: 'Signed payload must be BASE1_TRANSFER' };
  }
  if (payload.from !== address) {
    return {
      ok: false,
      code: 'TRANSFER_SIGNER_MISMATCH',
      message: 'Transfer sender must match signed wallet address',
      signer: address,
      from: payload.from,
    };
  }
  const account = getBase1Account(address);
  const expected = base1TransferPayload({
    publicState,
    from: payload.from,
    to: payload.to,
    amount: payload.amount,
    fee: payload.fee,
    accountNonce: payload.account_nonce,
  });
  const expectedHash = payloadHash(expected);
  const actualHash = payloadHash(payload);
  if (actualHash !== expectedHash) {
    return {
      ok: false,
      code: 'TRANSFER_PAYLOAD_MISMATCH',
      message: 'Signed transfer payload does not match current chain state',
      expected_payload_hash: expectedHash,
      actual_payload_hash: actualHash,
      expected_nonce: account.nonce + 1,
      latest_head_hash: publicState.latest_head_guard?.head_hash,
    };
  }
  return {
    ok: true,
    address,
    public_key: publicKey,
    payload,
    payload_hash: actualHash,
  };
}

async function syncBase1BlocksFromPeer(peerUrl, { limit = 100 } = {}) {
  const normalizedPeer = String(peerUrl || '').trim().replace(/\/+$/, '');
  if (!normalizedPeer) return { ok: false, code: 'PEER_URL_REQUIRED', message: 'peer url is required' };
  const local = getBase1ChainSummary();
  const blocksUrl = `${normalizedPeer}/api/base1/chain/blocks-since?after_height=${local.height}&after_hash=${encodeURIComponent(local.head_hash || '')}&limit=${Number(limit || 100)}`;
  const blocksResponse = await fetch(blocksUrl);
  const blocksPayload = await blocksResponse.json().catch(() => ({}));
  if (!blocksResponse.ok) {
    return { ok: false, code: 'PEER_BLOCK_FETCH_FAILED', peer: normalizedPeer, response: blocksPayload };
  }
  const blockResult = submitBase1Blocks({
    blocks: blocksPayload.blocks || [],
    source: normalizedPeer,
  });
  return {
    ok: blockResult.ok,
    peer: normalizedPeer,
    blocks: blockResult,
    chain: getBase1ChainSummary(),
  };
}

async function runBase1SubmitPreflight({
  ttl = HEAD_QUERY_TTL,
  maxPeers = HEAD_QUERY_MAX_PEERS,
  timeoutMs = HEAD_QUERY_TIMEOUT_MS,
} = {}) {
  const before = getCurrentBase1Public();
  const discovery = await discoverBase1Heads({ ttl, maxPeers, timeoutMs });
  let sync = null;
  if (discovery.stronger_than_local && discovery.best?.sync_url) {
    sync = await syncBase1BlocksFromPeer(discovery.best.sync_url, { limit: 200 });
  }
  const after = getCurrentBase1Public();
  const changed =
    before.latest_head_guard?.head_hash !== after.latest_head_guard?.head_hash ||
    before.current?.layer_no !== after.current?.layer_no ||
    before.current?.step_no !== after.current?.step_no;
  const blocked =
    discovery.stronger_than_local &&
    (!sync || !sync.ok || sync.blocks?.adopted !== true);
  const timeSync = await syncBase1NetworkTime({ maxPeers, timeoutMs });
  return {
    ok: !blocked,
    blocked,
    code: blocked ? 'PREFLIGHT_STRONGER_HEAD_NOT_SYNCED' : 'PREFLIGHT_OK',
    before: before.latest_head_guard,
    after: after.latest_head_guard,
    changed,
    discovery: {
      ok: discovery.ok,
      stronger_than_local: discovery.stronger_than_local,
      candidate_count: discovery.candidate_count,
      valid_candidate_count: discovery.valid_candidate_count,
      best: discovery.best
        ? {
            source: discovery.best.source,
            sync_url: discovery.best.sync_url,
            head_hash: discovery.best.head?.head_hash,
            current_layer: discovery.best.head?.current_layer,
            current_step: discovery.best.head?.current_step,
            height: discovery.best.head?.height,
          }
        : null,
      propagation: discovery.propagation,
    },
    sync,
    time_sync: timeSync,
  };
}

function serveStatic(req, res) {
  const url = new URL(req.url, `http://${req.headers.host}`);
  let requested = url.pathname === '/' ? '/index.html' : url.pathname;
  try {
    requested = decodeURIComponent(requested);
  } catch {
    res.writeHead(400, securityHeaders(req));
    res.end('Bad request');
    return;
  }
  const filePath = path.resolve(path.join(PUBLIC_DIR, requested.replace(/^\/+/, '')));
  const relative = path.relative(PUBLIC_DIR, filePath);
  if (relative.startsWith('..') || path.isAbsolute(relative)) {
    res.writeHead(403, securityHeaders(req));
    res.end('Forbidden');
    return;
  }
  if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) {
    res.writeHead(404, securityHeaders(req));
    res.end('Not found');
    return;
  }
  res.writeHead(200, {
    'Content-Type': MIME[path.extname(filePath)] || 'application/octet-stream',
    'Cache-Control': 'no-store',
    ...securityHeaders(req),
  });
  fs.createReadStream(filePath).pipe(res);
}

async function route(req, res) {
  const url = new URL(req.url, `http://${req.headers.host}`);
  try {
    if (req.method === 'GET' && url.pathname === '/api/health') {
      const config = getRuntimeConfigSnapshot();
      return sendJson(res, 200, {
        ok: true,
        service: 'mazexchain',
        chain_id: config.chain.chain_id || 'mazexchain-base1-local',
        protocol: config.runtime.active_protocol || config.chain.protocol || 'Base1',
      });
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/current') {
      if (url.searchParams.get('sync') === '1') {
        const preflight = await runBase1SubmitPreflight({
          ttl: Number(url.searchParams.get('ttl') || HEAD_QUERY_TTL),
          maxPeers: Number(url.searchParams.get('maxPeers') || url.searchParams.get('max_peers') || HEAD_QUERY_MAX_PEERS),
          timeoutMs: Number(url.searchParams.get('timeoutMs') || url.searchParams.get('timeout_ms') || HEAD_QUERY_TIMEOUT_MS),
        });
        return sendJson(res, 200, {
          ...getCurrentBase1Public(),
          preflight,
        });
      }
      return sendJson(res, 200, getCurrentBase1Public());
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/sample') {
      const body = await readBody(req);
      return sendJson(res, 200, sampleBase1Point(body));
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/sample-batch') {
      const body = await readBody(req);
      return sendJson(res, 200, batchBase1Sample(body));
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/signing-payload') {
      const body = await readBody(req);
      const publicState = getCurrentBase1Public();
      const current = publicState.current;
      if (!current) return sendError(res, 400, 'Current base1 Step is missing');
      const address = String(body.address || body.wallet_address || '').trim();
      if (!address) {
        return sendJson(res, 400, {
          ok: false,
          code: 'WALLET_ADDRESS_REQUIRED',
          message: 'Wallet address is required for a paid answer submission payload',
        });
      }
      const account = getBase1Account(address);
      const candidate = body.candidateStep || body.candidate || body.answer || {};
      const payload = base1SigningPayload({
        current,
        chain: publicState.chain,
        latestHeadGuard: publicState.latest_head_guard,
        candidate,
        nonce: body.nonce || Date.now(),
        submitFee: current.submit_cost,
        accountNonce: account.nonce + 1,
      });
      return sendJson(res, 200, {
        payload,
        payload_hash: payloadHash(payload),
        latest_head_guard: publicState.latest_head_guard,
        fee_schedule: publicState.fee_schedule || getBase1FeeSchedule(),
        account,
      });
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/preflight') {
      const body = await readBody(req);
      return sendJson(
        res,
        200,
        await runBase1SubmitPreflight({
          ttl: body.ttl ?? body.preflight?.ttl ?? HEAD_QUERY_TTL,
          maxPeers: body.maxPeers ?? body.max_peers ?? body.preflight?.maxPeers ?? HEAD_QUERY_MAX_PEERS,
          timeoutMs: body.timeoutMs ?? body.timeout_ms ?? body.preflight?.timeoutMs ?? HEAD_QUERY_TIMEOUT_MS,
        }),
      );
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/time') {
      return sendJson(res, 200, { time: getBase1TimeProof() });
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/fees') {
      return sendJson(res, 200, { fees: getBase1FeeSchedule() });
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/fragments') {
      return sendJson(res, 200, { fragment_registry: getBase1FragmentRegistry(undefined, { limit: Number(url.searchParams.get('limit') || 50) }) });
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/fragments/download') {
      return sendJson(res, 200, {
        fragment_download: getBase1FragmentDownload(undefined, {
          limit: Number(url.searchParams.get('limit') || 1000),
          includePayload: url.searchParams.get('include_payload') !== '0',
        }),
      });
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/fragments/record') {
      return sendJson(res, 200, {
        fragment_record: getBase1FragmentRecord(undefined, {
          fragmentId: url.searchParams.get('fragment_id') || url.searchParams.get('fragmentId') || '',
        }),
      });
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/fragments/register') {
      const body = await readBody(req);
      return sendJson(
        res,
        200,
        registerBase1Fragment({
          fragment: body.fragment || body,
          author: body.author || body.owner || '',
          activationDelay: body.activationDelay ?? body.activation_delay ?? 10,
        }),
      );
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/fragments/upgrade') {
      const body = await readBody(req);
      return sendJson(
        res,
        200,
        upgradeBase1Fragment({
          previousFragmentId: body.previousFragmentId || body.previous_fragment_id || '',
          fragment: body.fragment || body,
          author: body.author || body.owner || '',
          activationDelay: body.activationDelay ?? body.activation_delay ?? 10,
        }),
      );
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/fragments/quarantine') {
      const body = await readBody(req);
      return sendJson(
        res,
        200,
        quarantineBase1Fragment({
          fragmentId: body.fragmentId || body.fragment_id || '',
          challenger: body.challenger || body.reporter || '',
          reasonCode: body.reasonCode || body.reason_code || body.reason || '',
          evidence: body.evidence || body.proof || {},
        }),
      );
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/time-sync') {
      const body = await readBody(req);
      return sendJson(
        res,
        200,
        await syncBase1NetworkTime({
          maxPeers: body.maxPeers ?? body.max_peers ?? HEAD_QUERY_MAX_PEERS,
          timeoutMs: body.timeoutMs ?? body.timeout_ms ?? HEAD_QUERY_TIMEOUT_MS,
        }),
      );
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/submit') {
      const body = await readBody(req);
      const preflight = await runBase1SubmitPreflight({
        ttl: body.preflight?.ttl ?? body.ttl ?? HEAD_QUERY_TTL,
        maxPeers: body.preflight?.maxPeers ?? body.preflight?.max_peers ?? body.maxPeers ?? HEAD_QUERY_MAX_PEERS,
        timeoutMs: body.preflight?.timeoutMs ?? body.preflight?.timeout_ms ?? body.timeoutMs ?? HEAD_QUERY_TIMEOUT_MS,
      });
      if (preflight.changed) {
        return sendJson(res, 409, {
          correct: false,
          code: 'PREFLIGHT_SYNCED_STRONGER_HEAD',
          message: 'Preflight found and synced a newer valid head. Refresh current Step and rebuild the answer package.',
          preflight,
          current: getCurrentBase1Public(),
        });
      }
      if (preflight.blocked) {
        return sendJson(res, 409, {
          correct: false,
          code: preflight.code,
          message: 'Preflight found a stronger head but could not sync and replay it. Submission is blocked until the node is aligned.',
          preflight,
          current: getCurrentBase1Public(),
        });
      }
      const candidate = body.candidateStep || body.candidate || body.answer;
      if (!candidate) {
        return sendError(res, 400, 'Missing candidateStep: submit an expression-tree candidate answer JSON.');
      }
      const publicState = getCurrentBase1Public();
      const current = publicState.current;
      if (!current) return sendError(res, 400, 'Current base1 Step is missing');
      const auth = verifyBase1SignedSubmission({
        signedPayload: body.signedPayload || body.signed || null,
        current,
        chain: publicState.chain,
        latestHeadGuard: publicState.latest_head_guard,
        candidate,
      });
      if (!auth.ok) return sendJson(res, 400, auth);
      const submitFee = Number(current.submit_cost || getBase1FeeSchedule().submit_fee || 0);
      const expectedHead = body.expectedHead || body.expected_head || body.signedPayload?.payload || body.signed?.payload || null;
      const networkConfirmation = await broadcastBase1SolveCandidate({
        solver: auth.address || body.solver || body.userId || body.user_id || 'web-solver',
        candidateStep: candidate,
        expectedHead,
        verifierOptions: body.verifierOptions || {},
        networkTimeProof: preflight.time_sync?.time_proof || null,
        signedPayloadHash: auth.payload_hash || null,
        maxPeers: body.confirmation?.maxPeers ?? body.confirmation?.max_peers ?? body.preflight?.maxPeers ?? HEAD_QUERY_MAX_PEERS,
        timeoutMs:
          body.confirmation?.timeoutMs ?? body.confirmation?.timeout_ms ?? body.preflight?.timeoutMs ?? HEAD_QUERY_TIMEOUT_MS,
      });
      if (!networkConfirmation.ok) {
        if (networkConfirmation.status === 'local_rejected') {
          return sendJson(
            res,
            400,
            {
              preflight,
              network_confirmation: networkConfirmation,
              ...submitBase1Candidate({
                solver: auth.address,
                candidateStep: candidate,
                expectedHead,
                verifierOptions: body.verifierOptions || {},
                networkTimeProof: preflight.time_sync?.time_proof || null,
                networkConfirmation: null,
                requireExpectedHead: true,
                chargeFee: true,
                submitFee,
                signedPayloadHash: auth.payload_hash || null,
              }),
            },
          );
        }
        return sendJson(res, 409, {
          correct: false,
          code: networkConfirmation.code || 'NETWORK_CONFIRMATION_FAILED',
          message: 'Solve candidate did not reach the required network confirmation threshold.',
          network_confirmation: networkConfirmation,
          current: getCurrentBase1Public(),
        });
      }
      return sendJson(
        res,
        200,
        submitBase1Candidate({
          solver: auth.address || body.solver || body.userId || body.user_id || 'web-solver',
          candidateStep: candidate,
          expectedHead,
          verifierOptions: body.verifierOptions || {},
          networkTimeProof: preflight.time_sync?.time_proof || null,
          networkConfirmation,
          requireExpectedHead: true,
          chargeFee: true,
          submitFee,
          signedPayloadHash: auth.payload_hash || null,
        }),
      );
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/demo-solve') {
      const body = await readBody(req);
      const preflight = await runBase1SubmitPreflight({
        ttl: body.preflight?.ttl ?? body.ttl ?? HEAD_QUERY_TTL,
        maxPeers: body.preflight?.maxPeers ?? body.preflight?.max_peers ?? body.maxPeers ?? HEAD_QUERY_MAX_PEERS,
        timeoutMs: body.preflight?.timeoutMs ?? body.preflight?.timeout_ms ?? body.timeoutMs ?? HEAD_QUERY_TIMEOUT_MS,
      });
      if (preflight.blocked) {
        return sendJson(res, 409, {
          correct: false,
          code: preflight.code,
          message: 'Preflight found a stronger head but could not sync and replay it. Demo solve is blocked until the node is aligned.',
          preflight,
          current: getCurrentBase1Public(),
        });
      }
      const publicState = getCurrentBase1Public();
      const expectedHead = publicState.latest_head_guard;
      const networkConfirmation = await broadcastBase1SolveCandidate({
        solver: body.solver || body.userId || body.user_id || 'demo-solver',
        candidateStep: null,
        expectedHead,
        verifierOptions: body.verifierOptions || {},
        networkTimeProof: preflight.time_sync?.time_proof || null,
        maxPeers: body.confirmation?.maxPeers ?? body.confirmation?.max_peers ?? body.preflight?.maxPeers ?? HEAD_QUERY_MAX_PEERS,
        timeoutMs:
          body.confirmation?.timeoutMs ?? body.confirmation?.timeout_ms ?? body.preflight?.timeoutMs ?? HEAD_QUERY_TIMEOUT_MS,
      });
      if (!networkConfirmation.ok) {
        return sendJson(res, 409, {
          correct: false,
          code: networkConfirmation.code || 'NETWORK_CONFIRMATION_FAILED',
          message: 'Demo solve candidate did not reach the required network confirmation threshold.',
          network_confirmation: networkConfirmation,
          current: getCurrentBase1Public(),
        });
      }
      const result = submitBase1Candidate({
        solver: body.solver || body.userId || body.user_id || 'demo-solver',
        verifierOptions: body.verifierOptions || {},
        expectedHead,
        networkTimeProof: preflight.time_sync?.time_proof || null,
        networkConfirmation,
        requireExpectedHead: true,
        chargeFee: true,
      });
      return sendJson(
        res,
        200,
        {
          preflight,
          ...result,
        },
      );
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/confirm') {
      const body = await readBody(req);
      return sendJson(res, 200, appendBase1ConfirmationBlock({ producer: body.producer || body.node || 'web-confirmation-node' }));
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/transfer-signing-payload') {
      const body = await readBody(req);
      const publicState = getCurrentBase1Public();
      const from = String(body.from || body.address || '').trim();
      const account = getBase1Account(from);
      const payload = base1TransferPayload({
        publicState,
        from,
        to: String(body.to || '').trim(),
        amount: body.amount,
        fee: body.fee || 1,
        accountNonce: body.accountNonce || body.account_nonce || account.nonce + 1,
      });
      return sendJson(res, 200, {
        payload,
        payload_hash: payloadHash(payload),
        latest_head_guard: publicState.latest_head_guard,
        account,
      });
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/transfer') {
      const body = await readBody(req);
      const publicState = getCurrentBase1Public();
      const auth = verifyBase1SignedTransfer({
        signedPayload: body.signedPayload || body.signed || null,
        publicState,
      });
      if (!auth.ok) return sendJson(res, 400, auth);
      return sendJson(
        res,
        200,
        submitBase1Transfer({
          from: auth.payload.from,
          to: auth.payload.to,
          amount: auth.payload.amount,
          fee: auth.payload.fee,
          nonce: auth.payload.account_nonce,
          expectedHead: auth.payload,
          signedPayloadHash: auth.payload_hash,
        }),
      );
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/reset') {
      return sendJson(res, 200, { ok: true, current: getCurrentBase1Public(resetBase1State()) });
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/account') {
      return sendJson(res, 200, { account: getBase1Account(url.searchParams.get('address') || 'unknown') });
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/accounts') {
      return sendJson(res, 200, { accounts: getBase1Accounts() });
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/rewards') {
      return sendJson(res, 200, { rewards: getBase1RewardLedger({ limit: Number(url.searchParams.get('limit') || 50) }) });
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/solve-receipts') {
      return sendJson(res, 200, getBase1SolveReceipts({ limit: Number(url.searchParams.get('limit') || 50) }));
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/witnesses') {
      return sendJson(res, 200, getBase1WitnessStats({ limit: Number(url.searchParams.get('limit') || 100) }));
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/leaderboard') {
      return sendJson(res, 200, { leaderboard: getBase1Leaderboard() });
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/events') {
      return sendJson(res, 200, { events: getBase1Events() });
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/reveals') {
      return sendJson(res, 200, { reveals: getBase1Reveals() });
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/chain/summary') {
      return sendJson(res, 200, getBase1ChainSummary());
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/chain/blocks') {
      const limit = Number(url.searchParams.get('limit') || 20);
      return sendJson(res, 200, { blocks: getBase1ChainBlocks({ limit }) });
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/chain/blocks-since') {
      return sendJson(
        res,
        200,
        getBase1BlocksSince({
          afterHeight: url.searchParams.get('after_height') ?? url.searchParams.get('afterHeight') ?? -1,
          afterHash: url.searchParams.get('after_hash') || url.searchParams.get('afterHash') || null,
          limit: url.searchParams.get('limit') || 50,
        }),
      );
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/chain/blocks') {
      const body = await readBody(req);
      return sendJson(
        res,
        200,
        submitBase1Blocks({
          blocks: body.blocks || [],
          source: body.source || body.peer || 'block-peer',
        }),
      );
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/chain/verify') {
      return sendJson(res, 200, verifyBase1Chain());
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/chain/replay') {
      return sendJson(res, 200, replayBase1Chain());
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/node/info') {
      return sendJson(res, 200, { node: base1NodeInfo() });
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/node/head') {
      return sendJson(res, 200, { head: getBase1HeadProof() });
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/node/time') {
      return sendJson(res, 200, { time: getBase1TimeProof() });
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/security/status') {
      return sendJson(res, 200, getMainnetSecurityStatus());
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/storage/status') {
      const privateStatus = getBase1PrivateVaultStatus();
      return sendJson(res, 200, {
        public_storage: getBase1StorageStatus(),
        private_vault: {
          enabled: privateStatus.enabled,
          exists: privateStatus.exists,
          encrypted: privateStatus.encrypted,
          current_exists: privateStatus.current_exists,
          step_record_count: privateStatus.step_record_count,
        },
      });
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/p2p/status') {
      return sendJson(res, 200, p2pNode ? p2pNode.status() : { enabled: false });
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/p2p/connect') {
      const body = await readBody(req);
      if (!p2pNode) return sendJson(res, 400, { ok: false, code: 'P2P_DISABLED' });
      return sendJson(res, 200, p2pNode.connect(body.peer || body.address || body.url));
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/p2p/broadcast-head') {
      if (!p2pNode) return sendJson(res, 400, { ok: false, code: 'P2P_DISABLED' });
      return sendJson(res, 200, p2pNode.broadcastHead());
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/node/solve-candidate') {
      const body = await readBody(req);
      return sendJson(
        res,
        200,
        receiveBase1SolveCandidatePackage({
          solver: body.solver || 'network-solver',
          candidateStep: body.candidateStep || body.candidate || null,
          expectedHead: body.expectedHead || body.expected_head || null,
          verifierOptions: body.verifierOptions || {},
          networkTimeProof: body.networkTimeProof || body.network_time_proof || null,
          signedPayloadHash: body.signedPayloadHash || body.signed_payload_hash || null,
          answerHash: body.answer_hash || body.answerHash || null,
          source: body.source || body.source_url || body.peer || 'candidate-peer',
        }),
      );
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/node/peers') {
      return sendJson(res, 200, getBase1NetworkStatus());
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/node/bootstrap') {
      const body = await readBody(req);
      return sendJson(res, 200, bootstrapBase1SeedPeers({ seeds: body.seeds || body.urls || null }));
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/node/bootstrap-priority') {
      const body = await readBody(req);
      return sendJson(res, 200, bootstrapBase1PriorityRelays({ relays: body.relays || body.urls || null }));
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/node/head-query') {
      const body = await readBody(req);
      return sendJson(
        res,
        200,
        await discoverBase1Heads({
          ttl: body.ttl,
          maxPeers: body.maxPeers || body.max_peers,
          timeoutMs: body.timeoutMs || body.timeout_ms,
          queryId: body.queryId || body.query_id,
          visited: body.visited || [],
        }),
      );
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/node/peers') {
      const body = await readBody(req);
      return sendJson(
        res,
        200,
        registerBase1Peer({
          url: body.url,
          name: body.name,
          nodeId: body.nodeId || body.node_id,
          priorityRelay: Boolean(body.priorityRelay || body.priority_relay || body.priority),
          relayTier: body.relayTier || body.relay_tier || '',
        }),
      );
    }

    if (req.method === 'DELETE' && url.pathname === '/api/base1/node/peers') {
      return sendJson(res, 200, removeBase1Peer({ url: url.searchParams.get('url'), id: url.searchParams.get('id') }));
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/node/receive') {
      const body = await readBody(req);
      const blocks = Array.isArray(body.blocks) ? body.blocks : [];
      if (!blocks.length) {
        return sendError(res, 410, 'snapshot-state receive is disabled; use block sync or solve-candidate confirmation');
      }
      const result = submitBase1Blocks({
        blocks,
        source: body.source || body.peer || 'network-peer',
      });
      recordBase1NetworkMessage({
        direction: 'inbound',
        peer: body.source || body.peer || 'network-peer',
        type: 'BLOCKS_RECEIVED',
        status: result.ok ? result.status || 'accepted' : result.code || 'rejected',
        detail: {
          adopted: Boolean(result.adopted),
          accepted_count: result.accepted_count || 0,
          head_hash: result.chain?.head_hash || result.candidate_chain?.head_hash || null,
        },
      });
      return sendJson(res, result.ok ? 200 : 400, {
        ...result,
        current_path: 'tcp_p2p_head_and_blocks',
      });
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/node/broadcast') {
      return sendError(res, 410, 'snapshot broadcast is disabled; broadcast solve candidates or sync blocks');
    }

    if (req.method === 'POST' && url.pathname === '/api/base1/node/sync-peer') {
      const body = await readBody(req);
      const peerUrl = String(body.url || body.peer || '').trim().replace(/\/+$/, '');
      if (!peerUrl) return sendError(res, 400, 'peer url is required');
      const local = getBase1ChainSummary();
      const blocksUrl = `${peerUrl}/api/base1/chain/blocks-since?after_height=${local.height}&after_hash=${encodeURIComponent(local.head_hash || '')}&limit=${Number(body.limit || 100)}`;
      const blocksResponse = await fetch(blocksUrl);
      const blocksPayload = await blocksResponse.json().catch(() => ({}));
      if (!blocksResponse.ok) return sendJson(res, 400, { ok: false, code: 'PEER_BLOCK_FETCH_FAILED', peer: peerUrl, response: blocksPayload });
      const blockResult = submitBase1Blocks({
        blocks: blocksPayload.blocks || [],
        source: peerUrl,
      });
      return sendJson(res, 200, {
        ok: blockResult.ok,
        current_path: 'tcp_p2p_head_and_blocks',
        peer: peerUrl,
        blocks: blockResult,
        chain: getBase1ChainSummary(),
      });
    }

    if (req.method === 'GET' && url.pathname === '/api/base1/chain/snapshot') {
      return sendJson(res, 200, {
        ...snapshotBase1State(undefined, { includePrivate: false }),
        current_path: 'read_only_recovery_snapshot',
      });
    }

    if (req.method === 'POST' && url.pathname === '/api/wallet/create') {
      return sendJson(res, 200, {
        wallet: createWallet(),
        warning: 'This local development endpoint returns private_key. Production wallets must keep private keys client-side.',
      });
    }

    if (req.method === 'POST' && url.pathname === '/api/wallet/sign') {
      const body = await readBody(req);
      return sendJson(res, 200, signPayload({ privateKey: body.privateKey || body.private_key, payload: body.payload }));
    }

    if (url.pathname.startsWith('/api/')) {
      return sendError(res, 404, 'API endpoint does not exist');
    }

    return serveStatic(req, res);
  } catch (error) {
    const status = Math.max(400, Math.trunc(Number(error.status || error.statusCode || 400)));
    return sendJson(res, status, safeErrorBody(error, req));
  }
}

const server = http.createServer((req, res) => {
  const security = checkHttpRequest(req);
  for (const [key, value] of Object.entries(securityHeaders(req))) {
    res.setHeader(key, value);
  }
  if (req.method === 'OPTIONS') {
    res.writeHead(security.ok ? 204 : security.status || 400);
    res.end();
    return;
  }
  if (!security.ok) {
    return sendJson(res, security.status || 400, security);
  }
  route(req, res);
});

if (require.main === module) {
  getCurrentBase1Public();
  bootstrapBase1DefaultNetwork();
  server.listen(PORT, () => {
    console.log(`mazexchain running at http://localhost:${PORT}`);
    if (p2pNode) {
      p2pNode.start();
      console.log(`mazexchain p2p listening at tcp://0.0.0.0:${P2P_PORT}`);
    }
    if (SYNC_INTERVAL_MS > 0 && !p2pNode) {
      setInterval(() => {
        discoverBase1Heads({ ttl: 2, maxPeers: 24, timeoutMs: 3000 }).catch((error) => {
          recordBase1NetworkMessage({
            direction: 'outbound',
            peer: 'all',
            type: 'PERIODIC_SYNC',
            status: 'failed',
            detail: { error: error.message || 'periodic sync failed' },
          });
        });
      }, SYNC_INTERVAL_MS);
    }
  });
}

module.exports = { server };
