// SML Quote Inspector — local-only x402 payment quote decoding.
// No network, signing, wallet connection, authorization, or settlement check.
export const BASE_USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
export const BASE_CAIP = 'eip155:8453';
export const SML_PAYTO = '0x5bbd32e0478e49a7540ef2d760e0b0f9aa6328b2';
const address = value => typeof value === 'string' && /^0x[a-f0-9]{40}$/i.test(value);
const eq = (a,b) => String(a).toLowerCase() === String(b).toLowerCase();
const own = (obj,k) => Object.prototype.hasOwnProperty.call(obj,k);
const MAX_INPUT_CHARS = 65536;
function parseRaw(input) {
 if (typeof input !== 'string' || !input.trim()) throw new Error('Paste a PAYMENT-REQUIRED header or JSON challenge.');
 if (input.length > MAX_INPUT_CHARS) throw new Error('Input exceeds the 64 KiB inspection limit.');
 let str = input.trim(), match = str.match(/(?:^|\n)payment-required\s*:\s*([A-Za-z0-9+/_=-]+)/i);
 if (match) str = match[1];
 if (str.startsWith('{')) return JSON.parse(str);
 str = str.replace(/^["']|["']$/g,'').replace(/-/g,'+').replace(/_/g,'/');
 if (!/^[A-Za-z0-9+/]*={0,2}$/.test(str) || str.length % 4 === 1) throw new Error('Header is not valid base64 or JSON.');
 const bin = atob(str.padEnd(Math.ceil(str.length/4)*4,'='));
 const bytes = Uint8Array.from(bin, x=>x.charCodeAt(0));
 const payload = new TextDecoder('utf-8',{fatal:true}).decode(bytes);
 return JSON.parse(payload);
}
function atomic(usd) {
 if (typeof usd !== 'string' || !/^\d+(?:\.\d{1,6})?$/.test(usd)) throw new Error('Budget must be a positive USDC amount with up to 6 decimals.');
 const [w,f=''] = usd.split('.');
 return BigInt(w)*1000000n + BigInt((f+'000000').slice(0,6));
}
function displayAmount(value) {
 const n = BigInt(value);
 const w=n/1000000n, r=(n%1000000n).toString().padStart(6,'0').replace(/0+$/,'');
 return w.toString()+(r?'.'+r:'');
}
export function inspectChallenge(input,{maxUsdc='',expectedPayTo=''}={}) {
 let payload;
 try { payload=parseRaw(input) } catch(e){ return {ok:false,outcome:'INVALID_INPUT',error:'Cannot decode payment quote: '+e.message,offers:[],warnings:[],facts:{}} }
 if(!payload||typeof payload!=='object'||Array.isArray(payload)||!Array.isArray(payload.accepts)||payload.accepts.length===0||payload.accepts.length>32) return {ok:false,outcome:'INVALID_INPUT',error:'Challenge must contain between 1 and 32 payment offers in accepts[].',offers:[],warnings:[],facts:{}};
 if(expectedPayTo && !address(expectedPayTo)) return {ok:false,outcome:'INVALID_INPUT',error:'Expected payee must be a 0x-prefixed 40-byte-hex Ethereum address.',offers:[],warnings:[],facts:{}};
 let limit=null;
 if(maxUsdc!=='' && maxUsdc!==null && maxUsdc!==undefined){try{limit=atomic(String(maxUsdc).trim())}catch(e){return {ok:false,outcome:'INVALID_INPUT',error:e.message,offers:[],warnings:[],facts:{}}}}
 const warnings=[], offers=[];
 const version=payload.x402Version;
 const knownVersion=version===1 || version===2;
 if(!knownVersion) warnings.push('Unsupported x402Version; no payment offer may pass.');
 payload.accepts.forEach((a,index)=>{
   const issues=[];
   if(!a || typeof a!=='object'||Array.isArray(a)){offers.push({index:index+1,decision:'BLOCK',issues:['Malformed payment offer.']});return}
   const scheme=a.scheme, network=a.network, asset=a.asset, payTo=a.payTo;
   // The protocol versions use different required fields. Never silently
   // cross-read amount/maxAmountRequired or accept v1/v2 chain aliases.
   const correctField=version===1?'maxAmountRequired':version===2?'amount':null;
   const rawAmount=correctField?a[correctField]:undefined;
   if(!knownVersion) issues.push('Unknown x402 protocol version; quote semantics cannot be trusted.');
   if(scheme!=='exact') issues.push('Unsupported scheme (expected exact).');
   if((version===1 && network!=='base') || (version===2 && network!==BASE_CAIP) || !knownVersion)
     issues.push('Network does not match the protocol version (v1 base; v2 eip155:8453).');
   if(correctField && !own(a,correctField)) issues.push('Missing required '+correctField+' field for x402 v'+version+'.');
   if(own(a,'amount') && own(a,'maxAmountRequired'))
     issues.push('Ambiguous dual amount fields: cannot safely choose a price.');
   if(!eq(asset,BASE_USDC)) issues.push('Asset is not the Base USDC token contract.');
   if(!address(payTo)) issues.push('payTo is not a valid EVM address.');
   if(expectedPayTo && !eq(payTo,expectedPayTo)) issues.push('Recipient does not match the entered expected payee.');
   let price=null, units=null;
   if(typeof rawAmount==='string' && /^\d+$/.test(rawAmount) && rawAmount.length<=78) {
     try {units=BigInt(rawAmount);price=displayAmount(rawAmount);if(units<=0n) issues.push('Amount must be greater than zero.');if(limit!==null && units>limit) issues.push('Amount exceeds the entered maximum USDC spend.')} catch {issues.push('Invalid atomic payment amount.')}
   } else issues.push('Missing or invalid integer atomic payment amount.');
   offers.push({index:index+1,scheme:String(scheme??''),network:String(network??''),asset:String(asset??''),payTo:String(payTo??''),amountAtomic:String(rawAmount??''),displayUsdc:price,decision:issues.length?'BLOCK':'QUOTE_FIELDS_MATCH',issues});
 });
 const allMatched=offers.length>0 && offers.every(o=>o.decision==='QUOTE_FIELDS_MATCH');
 return {ok:allMatched,outcome:allMatched?'QUOTE_FIELDS_MATCH':'BLOCK',error:null,version,offers,warnings:[...new Set(warnings)],facts:{paymentExecuted:false,signatureRequested:false,settlementVerified:false,providerAuthenticated:false,quoteOnly:true},disclaimer:'Matching quote fields does not authenticate the provider, reserve funds, verify a transaction, or prove accepted delivery. Always check recipient ownership and live contract terms independently.'};
}
export const EXAMPLE_CHALLENGE = {
 x402Version:2,
 resource:{url:'https://example.invalid/paid-resource',description:'FICTIONAL LOCAL TEST ONLY',mimeType:'application/json'},
 accepts:[{scheme:'exact',network:BASE_CAIP,amount:'1000',asset:BASE_USDC,payTo:SML_PAYTO,maxTimeoutSeconds:300}]
};
// No outbound network calls or wallet signatures are performed by this module.
