const {
  DYNAMIC_PARAMETER_POOL,
  extractDynamicParameters,
  selectDynamicParametersForStep,
} = require('../src/lib/dynamic_parameter_extractors');
const { injectDynamicParameters } = require('../src/lib/dynamic_parameter_injector');
const { resolveDynamicParameters } = require('../src/lib/dynamic_context');

function readArg(name, fallback) {
  const index = process.argv.indexOf(`--${name}`);
  if (index === -1 || index + 1 >= process.argv.length) return fallback;
  return process.argv[index + 1];
}

function readNumber(name, fallback) {
  const value = Number(readArg(name, fallback));
  return Number.isFinite(value) ? value : fallback;
}

function main() {
  const seed = readArg('seed', 'mazex-dynamic-demo');
  const expression = readArg('expr', 'x + y');
  const layerNo = readNumber('layer', 301);
  const stepNo = readNumber('step', 1);
  const stepCount = readNumber('steps', 30);
  const band = readArg('band', 'main');
  const elapsedSeconds = readNumber('elapsed', 180);
  const count = readNumber('count', NaN);

  const plan = Number.isFinite(count)
    ? {
        dynamic_parameter_count: count,
        dynamic_parameters: extractDynamicParameters({
          seed,
          layerNo,
          count,
        }),
      }
    : selectDynamicParametersForStep({
        seed,
        layerNo,
        stepNo,
        stepCount,
        band,
      });
  const injected = injectDynamicParameters({
    expression,
    seed,
    layerNo,
    stepNo,
    stepCount,
    band,
    dynamicParameters: plan.dynamic_parameters,
    context: {
      layerNo,
      stepNo,
      elapsedSeconds,
      previousBlockHash: 'demo-previous-block',
      previousAnswerHash: 'demo-previous-answer',
    },
  });
  const resolved = resolveDynamicParameters(
    plan.dynamic_parameters,
    {
      layerNo,
      stepNo,
      elapsedSeconds,
      previousBlockHash: 'demo-previous-block',
      previousAnswerHash: 'demo-previous-answer',
    },
    40,
  );

  console.log(
    JSON.stringify(
      {
        dynamic_parameter_pool_size: DYNAMIC_PARAMETER_POOL.length,
        plan,
        resolved,
        injected,
      },
      null,
      2,
    ),
  );
}

main();
