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

const { spawnSync } = require('child_process');
const path = require('path');
const rewardLiveCanaryApprovalService = require('../services/rewardLiveCanaryApprovalService');
const rewardReadinessService = require('../services/rewardReadinessService');

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

function printAndExit(result, code = 0) {
  console.log(JSON.stringify(result, null, 2));
  process.exitCode = code;
}

const confirm = getArg('confirm', '');
const baseUrl = getArg('base-url', process.env.REWARD_CLIENT_BASE_URL || 'http://127.0.0.1:4317');
const approval = rewardLiveCanaryApprovalService.getApproval();
const readiness = rewardReadinessService.getStatus();
const permit = readiness.liveCanaryPermit || {};

const checks = [
  {
    key: 'approval_recorded',
    ok: approval.approved === true,
    detail: approval.approvalId || 'no approval recorded'
  },
  {
    key: 'permit_still_valid',
    ok: permit.ok === true && approval.permitId === permit.permitId,
    detail: `${approval.permitId || '-'} / current ${permit.permitId || '-'}`
  },
  {
    key: 'service_matches',
    ok: Boolean(approval.serviceName && approval.serviceName === permit.serviceName),
    detail: `${approval.serviceName || '-'} / current ${permit.serviceName || '-'}`
  },
  {
    key: 'confirm_token_present',
    ok: confirm === 'LIVE_SIMULATION_WRITE',
    detail: confirm || 'missing'
  }
];
const failed = checks.filter((row) => !row.ok);

if (failed.length) {
  printAndExit({
    ok: false,
    mode: 'reward-live-canary-approved-run',
    status: 'LOCKED',
    approval,
    permit: {
      ok: Boolean(permit.ok),
      status: permit.status || '',
      permitId: permit.permitId || '',
      serviceName: permit.serviceName || ''
    },
    checks,
    failed,
    reason: 'Live simulation canary was not executed.'
  }, 1);
  return;
}

const scriptPath = path.join(__dirname, 'reward-live-canary.js');
const args = [
  scriptPath,
  `--service=${approval.serviceName}`,
  `--base-url=${baseUrl}`,
  '--confirm=LIVE_SIMULATION_WRITE'
];
const run = spawnSync(process.execPath, args, {
  cwd: path.join(__dirname, '..'),
  encoding: 'utf8'
});

let canary = null;
try {
  canary = JSON.parse(run.stdout);
} catch (err) {
  canary = {
    ok: false,
    parseError: err.message,
    stdout: run.stdout,
    stderr: run.stderr
  };
}

const postcheckScript = path.join(__dirname, 'reward-live-canary-postcheck.js');
const postcheckRun = spawnSync(process.execPath, [postcheckScript], {
  cwd: path.join(__dirname, '..'),
  encoding: 'utf8'
});
let postcheck = null;
try {
  postcheck = JSON.parse(postcheckRun.stdout);
} catch (err) {
  postcheck = {
    ok: false,
    parseError: err.message,
    stdout: postcheckRun.stdout,
    stderr: postcheckRun.stderr
  };
}

const ok = run.status === 0 && canary?.ok === true && postcheck?.ok === true;
printAndExit({
  ok,
  mode: 'reward-live-canary-approved-run',
  status: ok ? 'LIVE_CANARY_COMPLETE' : 'LIVE_CANARY_FAILED',
  approvalId: approval.approvalId,
  serviceName: approval.serviceName,
  permitId: approval.permitId,
  canary,
  postcheck,
  checkedAt: new Date().toISOString()
}, ok ? 0 : 1);
