import {createHash} from 'node:crypto';
import {readFileSync} from 'node:fs';
import {pathToFileURL} from 'node:url';
const canonicalJson=value=>JSON.stringify(sort(value));
function sort(value){return Array.isArray(value)?value.map(sort):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(k=>[k,sort(value[k])])):value;}
const sha256Hex=value=>createHash('sha256').update(value).digest('hex');
class QuoteDiscountError extends Error {
  constructor(code) { super(code); this.name = 'QuoteDiscountError'; this.code = code; }
}
const fail = code => { throw new QuoteDiscountError(code); };

function exact(value, keys) {
  if (!value || typeof value !== 'object' || ![Object.prototype, null].includes(Object.getPrototypeOf(value)) ||
      Reflect.ownKeys(value).length !== keys.length || keys.some(key => !Object.hasOwn(value, key)) ||
      Object.values(Object.getOwnPropertyDescriptors(value)).some(entry => !Object.hasOwn(entry, 'value'))) fail('INVALID_REQUEST');
}
function ref(value) {
  if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,119}$/.test(value)) fail('INVALID_REQUEST');
}
function integer(value, min = 0, max = Number.MAX_SAFE_INTEGER) {
  if (!Number.isSafeInteger(value) || value < min || value > max) fail('INVALID_REQUEST');
}
function validateProposal(request) {
  exact(request, ['quote_id', 'quote_revision', 'discount_bps', 'request_id']);
  for (const key of ['quote_id', 'quote_revision', 'request_id']) ref(request[key]);
  if (request.request_id.length < 8) fail('INVALID_REQUEST');
  integer(request.discount_bps, 0, 10_000);
}
function validatePolicy(policy) {
  exact(policy, ['policy_id', 'version', 'currency', 'max_discount_bps', 'max_discount_minor', 'min_margin_bps', 'valid_from_ms', 'valid_until_ms', 'max_fact_age_ms', 'decision_ttl_ms']);
  ref(policy.policy_id); ref(policy.version);
  if (typeof policy.currency !== 'string' || !/^[A-Z]{3}$/.test(policy.currency)) fail('INVALID_REQUEST');
  integer(policy.max_discount_bps, 0, 10_000); integer(policy.min_margin_bps, 0, 10_000);
  integer(policy.max_discount_minor); integer(policy.valid_from_ms); integer(policy.valid_until_ms);
  integer(policy.max_fact_age_ms, 1, 600_000); integer(policy.decision_ttl_ms, 1, 600_000);
  if (policy.valid_until_ms <= policy.valid_from_ms) fail('INVALID_REQUEST');
}
function validateQuote(quote) {
  exact(quote, ['quote_id', 'revision', 'policy_id', 'currency', 'list_amount_minor', 'cost_minor', 'captured_at_ms', 'status']);
  for (const key of ['quote_id', 'revision', 'policy_id']) ref(quote[key]);
  if (typeof quote.currency !== 'string' || !/^[A-Z]{3}$/.test(quote.currency) || !['draft', 'sent', 'cancelled'].includes(quote.status)) fail('INVALID_REQUEST');
  integer(quote.list_amount_minor, 1); integer(quote.captured_at_ms);
  if (quote.cost_minor !== null) integer(quote.cost_minor);
}

function rulebook(policy) {
  const outcome = (decision, verdict, action, reason_code) => ({ decision, verdict, action, reason_code });
  return {
    schema_version: 'rulebook_v1', rulebook_id: 'quote_discount_approval', version: policy.version,
    input_schema: {
      required: ['discount_bps', 'discount_minor', 'net_positive', 'margin_bps'],
      properties: { discount_bps: { type: 'integer' }, discount_minor: { type: 'integer' }, net_positive: { type: 'boolean' }, margin_bps: { type: 'integer' } },
    },
    rules: [
      { rule_id: 'block_zero_net', priority: 300, condition: { field: 'net_positive', operator: 'eq', value: false }, outcome: outcome('no', 'BLOCK_DISCOUNT', 'reject_discount', 'INVALID_NET_AMOUNT') },
      { rule_id: 'block_margin', priority: 200, condition: { field: 'margin_bps', operator: 'lt', value: policy.min_margin_bps }, outcome: outcome('no', 'BLOCK_DISCOUNT', 'reject_discount', 'MARGIN_FLOOR_BREACH') },
      { rule_id: 'allow_standard', priority: 100, condition: { all: [
        { field: 'discount_bps', operator: 'lte', value: policy.max_discount_bps },
        { field: 'discount_minor', operator: 'lte', value: policy.max_discount_minor },
      ] }, outcome: outcome('yes', 'APPROVE_DISCOUNT', 'approve_discount', 'STANDARD_DISCOUNT_APPROVED') },
    ],
    default_outcome: outcome('review', 'REVIEW_DISCOUNT', 'route_to_customer_review', 'DISCOUNT_EXCEPTION'),
  };
}

function amounts(quote, discountBps) {
  const discount = Number(BigInt(quote.list_amount_minor) * BigInt(discountBps) / 10_000n);
  const net = quote.list_amount_minor - discount;
  let margin = null;
  if (quote.cost_minor !== null && net > 0) {
    const numerator = BigInt(net - quote.cost_minor) * 10_000n, denominator = BigInt(net);
    // BigInt division truncates toward zero; floor negative margins too.
    const value = numerator / denominator - (numerator < 0n && numerator % denominator !== 0n ? 1n : 0n);
    margin = Number(value);
    if (!Number.isSafeInteger(margin)) fail('MONEY_RANGE_UNSUPPORTED');
  } else if (net === 0) margin = 0;
  return { discount_minor: discount, net_amount_minor: net, margin_bps: margin };
}


function buildQuoteDiscountInput({ policy, quote, proposal }) {
  validatePolicy(policy); validateQuote(quote); validateProposal(proposal);
  if (quote.quote_id !== proposal.quote_id || quote.revision !== proposal.quote_revision) fail('QUOTE_CHANGED');
  if (quote.policy_id !== policy.policy_id) fail('POLICY_INACTIVE');
  if (quote.currency !== policy.currency) fail('CURRENCY_MISMATCH');
  if (quote.status !== 'draft') fail('QUOTE_NOT_DRAFT');
  const values = amounts(quote, proposal.discount_bps);
  const inputs = { quote_id: quote.quote_id, quote_revision: quote.revision,
    currency: quote.currency, list_amount_minor: quote.list_amount_minor, cost_minor: quote.cost_minor,
    discount_bps: proposal.discount_bps, discount_minor: values.discount_minor,
    net_positive: values.net_amount_minor > 0 };
  if (values.margin_bps !== null) inputs.margin_bps = values.margin_bps;
  return { input: { mode: 'rulebook', binding_mode: 'direct_declarative_rulebook',
    rulebook: rulebook(policy), context: { inputs } }, amounts: values };
}


// A client recipe over the existing paid Rulebook tool, not a new quote-writing
// service. The caller remains responsible for policy authority and real facts.
function buildQuoteRuntimeOperation({policy,quote,proposal,policy_approved,now=Date.now()}={}){
 if(policy_approved!==true)throw Error('APPROVED_POLICY_REQUIRED');
 const built=buildQuoteDiscountInput({policy,quote,proposal});
 if(!Number.isSafeInteger(now)||now<policy.valid_from_ms||now>=policy.valid_until_ms)throw Error('POLICY_INACTIVE');
 if(quote.captured_at_ms>now||now-quote.captured_at_ms>policy.max_fact_age_ms)throw Error('FRESH_QUOTE_REQUIRED');
 if(quote.cost_minor===null)throw Error('TRUSTED_COST_REQUIRED');
 if(!/^[A-Za-z0-9_-]{8,120}$/.test(proposal.request_id))throw Error('STABLE_OPERATION_ID_REQUIRED');
 const input=structuredClone(built.input);
 input.rulebook.rulebook_id=policy.policy_id;
 input.context.inputs.policy_hash=sha256Hex(canonicalJson(policy));
 input.context.inputs.quote_hash=sha256Hex(canonicalJson(quote));
 input.context.inputs.workflow='quote-discounts';
 input.context.inputs.captured_at_ms=quote.captured_at_ms;
 input.context.inputs.checked_at_ms=now;
 input.context.inputs.valid_until_ms=Math.min(policy.valid_until_ms,quote.captured_at_ms+policy.max_fact_age_ms,now+policy.decision_ttl_ms);
 return {operation_id:proposal.request_id,input};
}
function interpretQuoteRuntimeResult(value,operation){
 const verdict=typeof operation?.operation_id==='string'&&operation.input?.rulebook&&value?.status==='completed'&&value.execution_enabled===false&&value.operation_id===operation.operation_id&&
  value.record?.policy_id===operation?.input?.rulebook?.rulebook_id&&value.record?.policy_version===operation?.input?.rulebook?.version&&
  ['yes','no','review'].includes(value.record?.verdict)?value.record.verdict:null;
 return {verdict,execute:false,operation_id:operation?.operation_id??null,
  next:verdict==='yes'?'The supplied rules pass. A separately authorized application must recheck the exact quote revision and validity before any write.':
   verdict==='review'?'Stop. This exception needs the policy-defined approval path; do not approve it yourself.':
    verdict==='no'?'Stop. The proposed discount is refused.':'Stop. No confirmed decision authorizes any action.'};
}

export {buildQuoteRuntimeOperation,interpretQuoteRuntimeResult};
async function main(){
 const [action,file]=process.argv.slice(2);
 if(!['build','evaluate','read','export'].includes(action)||!file||process.argv.length!==4)throw Error('Usage: node quote-runtime-workflow.mjs build|evaluate|read|export <private-json-file>');
 const bytes=readFileSync(file);if(bytes.length>32768)throw Error('BOUNDED_REQUEST_REQUIRED');const value=JSON.parse(bytes.toString('utf8'));
 if(action==='build'){if(Object.hasOwn(value,'now'))throw Error('Use a fresh trusted quote, never a clock override.');process.stdout.write(JSON.stringify(buildQuoteRuntimeOperation(value),null,2)+'\n');return;}
 if(!value||Object.keys(value).sort().join(',')!=='input,operation_id'||! /^[A-Za-z0-9_-]{8,120}$/.test(value.operation_id||'')||value.input?.context?.inputs?.workflow!=='quote-discounts')throw Error('SAVED_QUOTE_REQUEST_REQUIRED');
 if(action==='evaluate'&&(!Number.isSafeInteger(value.input.context.inputs.valid_until_ms)||Date.now()>=value.input.context.inputs.valid_until_ms))throw Error('Quote expired. Read the original request; do not create a new ID to retry.');
 const key=process.env.DECIDE_RUNTIME_BEARER;if(!/^dk_live_client_cgr_[a-f0-9]{32}_[1-9][0-9]{0,11}_[a-f0-9]{64}$/.test(key||''))throw Error('An owner-approved private scoped Runtime bearer is required.');
 const name={evaluate:'decide_prepaid_evaluate',read:'decide_prepaid_get_record',export:'decide_prepaid_export_record'}[action];
 const response=await fetch('https://mcp-live.decide.fyi/developer-prepaid/v1/mcp',{method:'POST',redirect:'error',credentials:'omit',headers:{authorization:'Bearer '+key,'content-type':'application/json',accept:'application/json, text/event-stream'},body:JSON.stringify({jsonrpc:'2.0',id:1,method:'tools/call',params:{name,arguments:value}}),signal:AbortSignal.timeout(15000)});
 if(response.status!==200)throw Error('Runtime refused or unavailable ('+response.status+'). Stop and preserve the original request.');
 const result=await response.json();if(result.error||!result.result?.structuredContent)throw Error('Unconfirmed response. Stop and preserve the original request.');
 process.stdout.write(JSON.stringify(result.result.structuredContent,null,2)+'\n');
}
if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href)main().catch(error=>{process.stderr.write(error.message+'\n');process.exitCode=1;});
