require('../config/loadEnv')();

const fs = require('fs');
const path = require('path');
const { getServiceSecret } = require('../config/serviceCredentials');
const { postRewardPayload } = require('../lib/rewardIntegrationClient');
const rewardPolicyService = require('../services/rewardPolicyService');

function getArg(name, fallback = '') {
  const prefix = `--${name}=`;
  const found = process.argv.find((arg) => arg.startsWith(prefix));
  return found ? found.slice(prefix.length) : fallback;
}

async function main() {
  const serviceName = String(getArg('service', process.env.REWARD_CLIENT_SERVICE || 'AISFOR')).trim().toUpperCase();
  const baseUrl = getArg('base-url', process.env.REWARD_CLIENT_BASE_URL || 'http://127.0.0.1:4317');
  const confirm = getArg('confirm', '');
  const live = confirm === 'LIVE_SIMULATION_WRITE';
  const secret = getServiceSecret(serviceName);
  if (!secret) throw new Error(`${serviceName} chain credential is not configured.`);

  const manifest = rewardPolicyService.getIntegrationManifest();
  const service = manifest.services.find((row) => row.serviceName === serviceName);
  if (!service || !service.samplePayloads.length) throw new Error(`${serviceName} sample payload is not available.`);

  const payload = {
    ...service.samplePayloads[0],
    idempotencyKey: `${serviceName}:LIVE_CANARY:${Date.now()}`,
    refType: `${serviceName}_LIVE_CANARY`,
    note: live
      ? `${serviceName} controlled live simulation canary`
      : `${serviceName} dry-run live canary rehearsal`
  };

  const result = await postRewardPayload({
    baseUrl,
    serviceName,
    secret,
    payload,
    dryRun: !live
  });

  const output = {
    ok: result.ok,
    mode: live ? 'live-simulation-write' : 'dry-run-canary',
    live,
    status: result.status,
    serviceName,
    endpoint: result.url,
    idempotencyKey: payload.idempotencyKey,
    rewardId: result.body?.reward?.id || null,
    auditId: result.body?.audit?.id || null,
    rewardAmount: result.body?.dryRun?.rewardAmount || result.body?.reward?.rewardAmount || 0,
    wouldNeedReview: Boolean(result.body?.dryRun?.wouldNeedReview || (result.body?.reward?.flags || []).length),
    flags: result.body?.dryRun?.flags || result.body?.reward?.flags || [],
    confirmRequiredForLive: 'LIVE_SIMULATION_WRITE',
    checkedAt: new Date().toISOString()
  };

  const outputPath = path.join(__dirname, '..', 'data', 'reward-live-canary.json');
  fs.writeFileSync(outputPath, JSON.stringify(output, null, 2));
  console.log(JSON.stringify(output, null, 2));

  if (!output.ok) process.exitCode = 1;
}

main().catch((err) => {
  console.error(err.message);
  process.exitCode = 1;
});
