// verify.mjs — the check behind "StrictCheck".
//   node research/strictcheck/verify.mjs
//
// The tool's whole value is that its per-provider ruleset is CORRECT. This
// asserts the LOAD-BEARING verdicts in the page's ruleset match what the
// official docs actually say (each sourced in the tool footer + the research),
// re-implements the schema analyzer and confirms it detects the structural
// traps, and checks the honesty guardrails are present. If a future edit drifts
// a verdict away from the docs, this fails.
//
// Surfaces: oa=OpenAI strict · an=Anthropic strict · gj=Gemini responseJsonSchema
// · go=Gemini responseSchema (OpenAPI subset). Codes: E enforced · I silently
// ignored · X rejected · L limited · F additionalProperties-must-be-false · U unverified.
//
// Sources (also linked on the page):
//   OpenAI: developers.openai.com/api/docs/guides/{structured-outputs,function-calling} + changelog (value keywords enforced May 2025).
//   Anthropic: platform.claude.com/docs/en/build-with-claude/structured-outputs (JSON-schema limitations) + strict-tool-use.
//   Gemini: ai.google.dev/api/generate-content (responseJsonSchema whitelist; responseSchema OpenAPI subset) + structured-output guide.

import { readFileSync } from 'fs';

let pass = 0, fail = 0;
const ok = (n, c, extra = '') => { console.log((c ? '  ok   ' : '  FAIL ') + n + (extra ? '  ' + extra : '')); c ? pass++ : fail++; };

const html = readFileSync(new URL('../../public/tools/strictcheck/index.html', import.meta.url).pathname, 'utf8');

/* ── extract the R ruleset cells from the page (source of truth) ─────────── */
function cell(keyword, surface) {
  const kw = keyword.startsWith('$') ? "'\\" + keyword + "'" : "(?:'" + keyword + "'|" + keyword + ")";
  const re = new RegExp('(?:^|\\n)\\s*' + kw + ':\\s*\\{([^}]*)\\}', 'm');
  const m = html.match(re);
  if (!m) return null;
  const cm = m[1].match(new RegExp(surface + ":\\s*'([EIXLFU])'"));
  return cm ? cm[1] : null;
}

/* ── (1) load-bearing verdicts match the official docs ──────────────────── */
console.log('[ruleset vs official docs]');

// OpenAI strict
ok('OpenAI: additionalProperties must be false (F)',            cell('additionalProperties','oa') === 'F');
ok('OpenAI: oneOf rejected (X)',                                cell('oneOf','oa') === 'X');
ok('OpenAI: allOf rejected (X)',                                cell('allOf','oa') === 'X');
ok('OpenAI: uniqueItems rejected (X)',                          cell('uniqueItems','oa') === 'X');
ok('OpenAI: minLength enforced since May 2025 (E)',             cell('minLength','oa') === 'E');
ok('OpenAI: pattern enforced (E)',                              cell('pattern','oa') === 'E');
ok('OpenAI: $ref supported (E, recursion allowed)',             cell('$ref','oa') === 'E');
ok('OpenAI: minProperties rejected (X)',                        cell('minProperties','oa') === 'X');

// Anthropic strict
ok('Anthropic: additionalProperties must be false (F)',         cell('additionalProperties','an') === 'F');
ok('Anthropic: minLength rejected (X)',                         cell('minLength','an') === 'X');
ok('Anthropic: minimum rejected (X)',                           cell('minimum','an') === 'X');
ok('Anthropic: maxItems rejected (X)',                          cell('maxItems','an') === 'X');
ok('Anthropic: minItems limited to 0/1 (L)',                    cell('minItems','an') === 'L');
ok('Anthropic: default supported (E) — opposite of OpenAI',     cell('default','an') === 'E' && cell('default','oa') === 'X');
ok('Anthropic: allOf limited (L, not with $ref)',               cell('allOf','an') === 'L');

// Gemini responseJsonSchema (the silent-ignore surface — the headline)
ok('Gemini(json): minLength SILENTLY IGNORED (I) — the headline', cell('minLength','gj') === 'I');
ok('Gemini(json): pattern silently ignored (I)',                cell('pattern','gj') === 'I');
ok('Gemini(json): maxLength silently ignored (I)',              cell('maxLength','gj') === 'I');
ok('Gemini(json): const silently ignored (I)',                  cell('const','gj') === 'I');
ok('Gemini(json): additionalProperties supported (E)',          cell('additionalProperties','gj') === 'E');
ok('Gemini(json): minimum/maximum supported (E)',               cell('minimum','gj') === 'E' && cell('maximum','gj') === 'E');
ok('Gemini(json): oneOf limited — treated as anyOf (L)',        cell('oneOf','gj') === 'L');

// Gemini responseSchema (OpenAPI subset — the reject surface)
ok('Gemini(openapi): additionalProperties REJECTED (X)',        cell('additionalProperties','go') === 'X');
ok('Gemini(openapi): $ref rejected (X)',                        cell('$ref','go') === 'X');
ok('Gemini(openapi): const rejected (X)',                       cell('const','go') === 'X');
ok('Gemini(openapi): minLength supported on this surface (E)',  cell('minLength','go') === 'E');
ok('Gemini(openapi): default ignored (I)',                      cell('default','go') === 'I');

// the two Gemini surfaces genuinely diverge (the reason "Gemini" is two answers)
ok('the two Gemini surfaces diverge on additionalProperties',   cell('additionalProperties','gj') !== cell('additionalProperties','go'));
ok('the two Gemini surfaces diverge on $ref',                   cell('$ref','gj') !== cell('$ref','go'));

/* ── (2) the analyzer detects the structural traps ──────────────────────── */
console.log('\n[analyzer logic]');
const KNOWN = ['type','properties','required','additionalProperties','enum','const','description','title','format','pattern','minLength','maxLength','minimum','maximum','exclusiveMinimum','exclusiveMaximum','multipleOf','minItems','maxItems','uniqueItems','items','prefixItems','minProperties','maxProperties','anyOf','oneOf','allOf','not','$ref','$defs','definitions','default','propertyOrdering','nullable'];
// The descent lists are LIFTED FROM THE PAGE, never restated here.
//
// Until 2026-09-04 this file kept its own copy of a ten-key walk identical to
// the page's, so when the page's walk turned out to skip patternProperties,
// if/then/else, contains, propertyNames and dependentSchemas, this verifier
// skipped them too and reported 42 of 42. A guard that iterates over a
// collection it under-collected does not fail, it approves. Reading the lists
// out of the source removes the second copy that made that possible.
function listFromPage(name){
  const m = html.match(new RegExp('const ' + name.replace('$','\\$') + '\\s*=\\s*\\[([^\\]]*)\\]'));
  if(!m) return null;
  return m[1].split(',').map(x=>x.trim().replace(/^'|'$/g,'')).filter(Boolean);
}
const SUB_MAP  = listFromPage('SUB_MAP');
const SUB_ONE  = listFromPage('SUB_ONE');
const SUB_LIST = listFromPage('SUB_LIST');

function analyze(schema){
  const used=new Set(); const objsMissingAddl=[]; const objsWithOptional=[]; let rootAnyOf=false, hasRef=false;
  (function walk(node,path,depth){
    if(!node||typeof node!=='object') return;
    if(Array.isArray(node)){ node.forEach((n,i)=>walk(n,path+'/'+i,depth)); return; }
    for(const k of Object.keys(node)) if(KNOWN.includes(k)) used.add(k);
    if('$ref' in node) hasRef=true;
    if(node.type==='object'||node.properties){
      if(node.additionalProperties!==false) objsMissingAddl.push(path||'root');
      const props=node.properties?Object.keys(node.properties):[]; const req=Array.isArray(node.required)?node.required:[];
      if(props.length&&props.some(p=>!req.includes(p))) objsWithOptional.push(path||'root');
    }
    if(Array.isArray(node.anyOf)&&depth===0) rootAnyOf=true;
    for(const k of SUB_MAP)  if(node[k]&&typeof node[k]==='object'&&!Array.isArray(node[k])) for(const kk of Object.keys(node[k])) walk(node[k][kk],path+'/'+k+'/'+kk,depth+1);
    for(const k of SUB_ONE)  if(node[k]&&typeof node[k]==='object') walk(node[k],path+'/'+k,depth+1);
    for(const k of SUB_LIST) if(Array.isArray(node[k])) node[k].forEach((n,i)=>walk(n,path+'/'+k+'/'+i,depth+1));
  })(schema,'',0);
  return { used:[...used], objsMissingAddl, objsWithOptional, rootAnyOf, hasRef };
}

const constraints = { type:'object', additionalProperties:false, properties:{ u:{type:'string',minLength:3,pattern:'^x$'}, t:{type:'array',items:{type:'string'},uniqueItems:true} }, required:['u','t'] };
let A = analyze(constraints);
ok('detects minLength / pattern / uniqueItems in a constraints schema', ['minLength','pattern','uniqueItems'].every(k=>A.used.includes(k)));
ok('constraints schema has additionalProperties:false everywhere', A.objsMissingAddl.length === 0);

const optionalSchema = { type:'object', additionalProperties:false, properties:{ city:{type:'string'}, unit:{type:'string'} }, required:['city'] };
A = analyze(optionalSchema);
ok('detects an optional field (matters for OpenAI)', A.objsWithOptional.length === 1);

const missingAddl = { type:'object', properties:{ a:{type:'string'} }, required:['a'] };
A = analyze(missingAddl);
ok('detects a missing additionalProperties:false', A.objsMissingAddl.includes('root'));

const rootUnion = { anyOf:[{type:'object',additionalProperties:false,properties:{},}, {type:'string'}] };
A = analyze(rootUnion);
ok('detects anyOf at the root (OpenAI forbids)', A.rootAnyOf === true);

// the headline: a schema with minLength should be flagged as silently-ignored by Gemini(json)
A = analyze(constraints);
const silentByGemini = A.used.filter(k => cell(k,'gj') === 'I');
ok('a schema with minLength triggers a Gemini-silent-ignore finding', silentByGemini.includes('minLength'));

/* ── (2b) the analyzer reaches every subschema position ─────────────────── */
// Reported by Marco (marcologs.com), an autonomous agent, through the door on
// 2026-09-04, and reproduced in a browser before the fix: the banner read "No
// silent drops or rejections detected" over a schema whose patternProperties
// carried minLength, which this very table grades X on Anthropic.
console.log('\n[the analyzer reaches every subschema position]');
ok('the page declares its descent lists', !!(SUB_MAP && SUB_ONE && SUB_LIST));
for(const k of ['properties','$defs','definitions','patternProperties','dependentSchemas'])
  ok('descends into map-valued ' + k, (SUB_MAP||[]).includes(k));
for(const k of ['items','not','additionalProperties','contains','propertyNames','if','then','else','unevaluatedProperties','unevaluatedItems','additionalItems'])
  ok('descends into schema-valued ' + k, (SUB_ONE||[]).includes(k));
for(const k of ['anyOf','oneOf','allOf','prefixItems'])
  ok('descends into list-valued ' + k, (SUB_LIST||[]).includes(k));

// Each pair differs by ONE graded keyword. If `used` does not move between
// them, the analyzer is not looking there.
const DEPTH_PAIRS = [
  ['patternProperties','minLength',
    { type:'object', additionalProperties:false, properties:{id:{type:'string'}}, required:['id'], patternProperties:{'^x-':{type:'string'}} },
    { type:'object', additionalProperties:false, properties:{id:{type:'string'}}, required:['id'], patternProperties:{'^x-':{type:'string',minLength:3}} }],
  ['if/then','maximum',
    { type:'object', additionalProperties:false, properties:{n:{type:'integer'}}, required:['n'], if:{properties:{n:{type:'integer'}}}, then:{properties:{n:{type:'integer'}}} },
    { type:'object', additionalProperties:false, properties:{n:{type:'integer'}}, required:['n'], if:{properties:{n:{type:'integer'}}}, then:{properties:{n:{type:'integer',maximum:10}}} }],
  ['contains','maxLength',
    { type:'object', additionalProperties:false, properties:{a:{type:'array',contains:{type:'string'}}}, required:['a'] },
    { type:'object', additionalProperties:false, properties:{a:{type:'array',contains:{type:'string',maxLength:5}}}, required:['a'] }],
];
for(const [where, kw, without, withIt] of DEPTH_PAIRS){
  const a0 = analyze(without), a1 = analyze(withIt);
  ok('a graded keyword under ' + where + ' changes the verdict', !a0.used.includes(kw) && a1.used.includes(kw),
     kw + ': without=' + a0.used.includes(kw) + ' with=' + a1.used.includes(kw));
}
// The census is the half that survives the specification growing, so require
// the page to carry one and to gate the clean banner on it.
ok('the page carries a structure-blind census', /function census\(/.test(html));
ok('the clean banner is gated on what the census missed', /a\.missed\.length \? '' : clean/.test(html));
ok('the census reports where a missed keyword hides', /missed\.map\(m=>'<code>'\+m\.kw/.test(html));

/* ── (3) honesty guardrails present ─────────────────────────────────────── */
console.log('\n[honesty guardrails present]');
ok('carries a dated "rules verified" stamp', /rules verified/i.test(html) && /2026-07-09/.test(html));
ok('has an "unverified" verdict category', /unverified/i.test(html) && /'U'/.test(html));
ok('names the silent drop explicitly', /silently ignore/i.test(html));
ok('flags provider rules as a moving target', /moving target/i.test(html));
ok('notes "enforced" ≠ guaranteed model obedience', /always validate/i.test(html));
ok('says the schema is never sent (client-side)', /never sent/i.test(html) && /your browser/i.test(html));
ok('links all three providers\' official docs', /developers\.openai\.com/.test(html) && /platform\.claude\.com/.test(html) && /ai\.google\.dev/.test(html));

console.log('\n' + (fail === 0 ? pass + ' passes / 0 failures — ALL CHECKS PASS' : pass + ' passes / ' + fail + ' FAILURES'));
process.exit(fail === 0 ? 0 : 1);
