const fs = require('fs');
const path = require('path');
const rewardAuditService = require('./rewardAuditService');
const rewardLedgerService = require('./rewardLedgerService');

function readLatestLiveCanary() {
  const canaryPath = path.join(__dirname, '..', 'data', 'reward-live-canary.json');
  if (!fs.existsSync(canaryPath)) {
    return {
      ok: false,
      mode: 'not-run',
      detail: 'no live canary result yet'
    };
  }

  try {
    return JSON.parse(fs.readFileSync(canaryPath, 'utf8'));
  } catch (err) {
    return {
      ok: false,
      mode: 'parse-failed',
      detail: `live canary result parse failed: ${err.message}`
    };
  }
}

function getStatus() {
  const canary = readLatestLiveCanary();
  const rewards = rewardLedgerService.listEntries();
  const audits = rewardAuditService.listEntries();
  const rewardById = canary.rewardId
    ? rewards.find((row) => row.id === canary.rewardId)
    : null;
  const rewardByIdempotency = canary.idempotencyKey
    ? rewards.find((row) => row.metadata?.idempotencyKey === canary.idempotencyKey)
    : null;
  const auditById = canary.auditId
    ? audits.find((row) => row.id === canary.auditId)
    : null;
  const auditByIdempotency = canary.idempotencyKey
    ? audits.find((row) => row.idempotencyKey === canary.idempotencyKey)
    : null;
  const checks = [];

  checks.push({
    key: 'canary_result_ok',
    ok: Boolean(canary.ok),
    detail: `${canary.mode || 'unknown'} / ${canary.serviceName || '-'}`
  });

  if (canary.live) {
    checks.push({
      key: 'live_reward_exists',
      ok: Boolean(rewardById && rewardByIdempotency),
      detail: `rewardId ${canary.rewardId || '-'}`
    });
    checks.push({
      key: 'live_audit_exists',
      ok: Boolean(auditById && auditByIdempotency),
      detail: `auditId ${canary.auditId || '-'}`
    });
    checks.push({
      key: 'live_audit_reward_link',
      ok: Boolean(auditById && rewardById && auditById.rewardId === rewardById.id),
      detail: `audit reward ${auditById?.rewardId || '-'}`
    });
  } else {
    checks.push({
      key: 'dry_run_no_reward_write',
      ok: !rewardByIdempotency,
      detail: `idempotency ${canary.idempotencyKey || '-'}`
    });
    checks.push({
      key: 'dry_run_no_audit_write',
      ok: !auditByIdempotency,
      detail: `idempotency ${canary.idempotencyKey || '-'}`
    });
  }

  const failed = checks.filter((row) => !row.ok);
  return {
    ok: failed.length === 0,
    mode: 'reward-live-canary-postcheck',
    canaryMode: canary.mode || 'unknown',
    live: Boolean(canary.live),
    serviceName: canary.serviceName || '',
    rewardId: canary.rewardId || null,
    auditId: canary.auditId || null,
    idempotencyKey: canary.idempotencyKey || '',
    checks,
    failed,
    checkedAt: new Date().toISOString()
  };
}

module.exports = {
  getStatus
};
