const dnExportAcceptancePolicy = {
  "name": "DN Synthetic Research Export Rubric",
  "version": "0.1",
  "taskId": "demo-research-export",
  "rubricId": "DN-EXPORT-0.1",
  "schemaVersion": "1",
  "asOf": "2026-11-03T18:00:00Z",
  "maxAgeHours": 24,
  "requiredRecordIds": [
    "asset-a",
    "asset-b",
    "asset-c"
  ],
  "currency": "USD",
  "maxValueMinor": 1000000000000,
  "sourceHost": "research.example",
  "limitations": [
    "This fixed rubric is a demonstration, not a universal acceptance rule.",
    "All identifiers, values, hosts and timestamps are invented. No source is fetched.",
    "The checker evaluates declared fields and timestamp claims; it does not authenticate observations or determine factual accuracy.",
    "Passing does not authorize payment or establish legal acceptance."
  ]
}

export function evaluateAgentExport(value) {
  const checks = { structure: 'not-assessed', coverage: 'not-assessed', timeClaims: 'not-assessed', units: 'not-assessed', sourceShape: 'not-assessed' }
  const issues = []
  const issue = (group, message) => { checks[group] = 'fail'; issues.push({ group, message }) }
  const object = x => x !== null && typeof x === 'object' && !Array.isArray(x)
  const shape = (x, fields, label) => {
    if (!object(x)) { issue('structure', label + ' must be an object.'); return false }
    if (fields.some(key => !Object.hasOwn(x, key)) || Object.keys(x).some(key => !fields.includes(key))) issue('structure', label + ' has missing or unsupported fields.')
    return true
  }
  const time = x => {
    if (typeof x !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(x)) return null
    const n = Date.parse(x)
    return Number.isFinite(n) && new Date(n).toISOString().replace('.000Z', 'Z') === x ? n : null
  }
  if (!shape(value, ['taskId', 'rubricId', 'schemaVersion', 'generatedAt', 'records'], 'Export')) return { meetsRubric: false, checks, issues, recordCount: null }
  checks.structure = checks.structure === 'fail' ? 'fail' : 'pass'
  for (const key of ['coverage', 'timeClaims', 'units', 'sourceShape']) checks[key] = 'pass'
  if (value.taskId !== dnExportAcceptancePolicy.taskId || value.rubricId !== dnExportAcceptancePolicy.rubricId || value.schemaVersion !== dnExportAcceptancePolicy.schemaVersion) issue('structure', 'Task, rubric or schema identifier differs from the fixed external policy.')
  const asOf = Date.parse(dnExportAcceptancePolicy.asOf), cutoff = asOf - dnExportAcceptancePolicy.maxAgeHours * 3600000
  const generated = time(value.generatedAt)
  if (generated === null || generated > asOf || generated < cutoff) issue('timeClaims', 'Generated-at claim must be canonical UTC seconds within the fixed 24-hour window.')
  if (!Array.isArray(value.records) || value.records.length < 1 || value.records.length > 100) {
    issue('structure', 'Provide an array containing 1 to 100 records; this rubric requires exactly three named records.')
    for (const key of ['coverage', 'units', 'sourceShape']) checks[key] = 'not-assessed'
    return { meetsRubric: false, checks, issues, recordCount: Array.isArray(value.records) ? value.records.length : null }
  }
  const ids = []
  value.records.forEach((record, index) => {
    const label = 'Record ' + (index + 1)
    if (!shape(record, ['recordId', 'currency', 'valueMinor', 'sourceUrl', 'observedAt'], label)) {
      issue('coverage', label + ' cannot contribute a record identifier.')
      checks.units = checks.units === 'fail' ? 'fail' : 'not-assessed'
      checks.sourceShape = checks.sourceShape === 'fail' ? 'fail' : 'not-assessed'
      checks.timeClaims = checks.timeClaims === 'fail' ? 'fail' : 'not-assessed'
      return
    }
    if (typeof record.recordId !== 'string' || !dnExportAcceptancePolicy.requiredRecordIds.includes(record.recordId)) issue('coverage', label + ' has an unexpected identifier.')
    ids.push(record.recordId)
    if (record.currency !== dnExportAcceptancePolicy.currency || !Number.isSafeInteger(record.valueMinor) || record.valueMinor < 0 || record.valueMinor > dnExportAcceptancePolicy.maxValueMinor) issue('units', label + ' must use USD and bounded nonnegative integer cents, with no string or boolean coercion.')
    const observed = time(record.observedAt)
    if (observed === null || observed < cutoff || observed > asOf || (generated !== null && observed > generated)) issue('timeClaims', label + ' has an invalid, stale, future or post-generation observation-time claim.')
    let sourceOk = false
    if (typeof record.sourceUrl === 'string' && record.sourceUrl.length <= 2000 && record.sourceUrl.startsWith('https://') && !/[\u0000-\u0020\u007f]/.test(record.sourceUrl)) {
      try {
        const u = new URL(record.sourceUrl)
        sourceOk = u.protocol === 'https:' && u.hostname === dnExportAcceptancePolicy.sourceHost && !u.username && !u.password && !u.port
      } catch { sourceOk = false }
    }
    if (!sourceOk) issue('sourceShape', label + ' needs a credential-free HTTPS reference on the exact synthetic host, with no nondefault port.')
  })
  if (value.records.length !== dnExportAcceptancePolicy.requiredRecordIds.length || new Set(ids).size !== dnExportAcceptancePolicy.requiredRecordIds.length || dnExportAcceptancePolicy.requiredRecordIds.some(id => !ids.includes(id))) issue('coverage', 'Cover asset-a, asset-b and asset-c exactly once each; order is not significant.')
  return { meetsRubric: issues.length === 0 && Object.values(checks).every(value => value === 'pass'), checks, issues, recordCount: value.records.length }
}
