// retoor <retoor@molodetz.nl>
export const meta = {
  name: 'fleet',
  description: 'DevPlace maintenance fleet: 12 dimension subagents scan in parallel, then every finding is adversarially verified against source before it is reported',
  phases: [
    { title: 'Review', detail: '12 dimension subagents scan devplacepy/ and tests/ in parallel' },
    { title: 'Verify', detail: 'adversarially refute each candidate finding against the actual source' },
  ],
}

const DIMENSIONS = [
  { key: 'style', agent: 'style-maintainer' },
  { key: 'dry', agent: 'dry-maintainer' },
  { key: 'security', agent: 'security-maintainer' },
  { key: 'audit', agent: 'audit-maintainer' },
  { key: 'devii', agent: 'devii-maintainer' },
  { key: 'seo', agent: 'seo-maintainer' },
  { key: 'frontend', agent: 'frontend-maintainer' },
  { key: 'fanout', agent: 'fanout-maintainer' },
  { key: 'docs', agent: 'docs-maintainer' },
  { key: 'test', agent: 'test-maintainer' },
  { key: 'background', agent: 'background-maintainer' },
  { key: 'locust', agent: 'locust-maintainer' },
]

const FINDINGS_SCHEMA = {
  type: 'object',
  additionalProperties: false,
  required: ['summary', 'findings'],
  properties: {
    summary: { type: 'string' },
    findings: {
      type: 'array',
      items: {
        type: 'object',
        additionalProperties: false,
        required: ['severity', 'file', 'rule', 'message'],
        properties: {
          severity: { type: 'string', enum: ['error', 'warning', 'info'] },
          file: { type: 'string' },
          line: { type: 'integer' },
          rule: { type: 'string' },
          message: { type: 'string' },
        },
      },
    },
  },
}

const VERDICT_SCHEMA = {
  type: 'object',
  additionalProperties: false,
  required: ['isReal', 'reason'],
  properties: {
    isReal: { type: 'boolean' },
    reason: { type: 'string' },
    severity: { type: 'string', enum: ['error', 'warning', 'info'] },
  },
}

function requestedKeys() {
  if (Array.isArray(args && args.only)) return args.only
  if (typeof (args && args.only) === 'string') return args.only.split(',').map((s) => s.trim()).filter(Boolean)
  return null
}

function scopedFiles() {
  if (Array.isArray(args && args.files)) return args.files
  return null
}

const wanted = requestedKeys()
const files = scopedFiles()
const selected = wanted ? DIMENSIONS.filter((d) => wanted.includes(d.key)) : DIMENSIONS
const scopeNote = files && files.length
  ? `\n\nRestrict every finding strictly to these files (you may read other files only for cross-reference):\n${files.join('\n')}`
  : ''

function reportPrompt(dimension) {
  return (
    `Operate in REPORT mode (read-only). Do not modify any file. Scan your single quality dimension across the ` +
    `devplacepy/ package and tests/, following your mandate, scope units, and accuracy doctrine. ` +
    `Confirm each candidate against the actual source before recording it. Return your findings as ` +
    `structured output: a one-line summary and one entry per confirmed finding (severity, file, line, rule, message).` +
    scopeNote
  )
}

function verifyPrompt(dimension, finding) {
  return (
    `You are an independent skeptic, not the agent that raised this finding. A "${dimension}"-dimension maintenance agent flagged the candidate below; your job is solely to REFUTE it from a fresh, unbiased read of the source. Open the exact file and read ` +
    `enough surrounding context (the whole function, the caller, the contract) to judge intent. It is REAL only if it ` +
    `survives refutation as a genuine violation of the ${dimension} dimension. Rule it out (isReal=false) if it is a ` +
    `contract identifier, DATA rather than authored prose, generated or vendored or third-party, or already correct ` +
    `under a known exemption. When uncertain, default to isReal=false.\n\n` +
    `Candidate finding:\n` +
    `- file: ${finding.file}\n` +
    `- line: ${finding.line == null ? 'unspecified' : finding.line}\n` +
    `- severity: ${finding.severity}\n` +
    `- rule: ${finding.rule}\n` +
    `- message: ${finding.message}\n\n` +
    `Return isReal and a one-line reason.`
  )
}

log(`Fleet check over ${selected.length} dimension(s)${files ? ` scoped to ${files.length} file(s)` : ''}`)

const reviewed = await pipeline(
  selected,
  (dimension) =>
    agent(reportPrompt(dimension), {
      agentType: dimension.agent,
      label: `review:${dimension.key}`,
      phase: 'Review',
      schema: FINDINGS_SCHEMA,
    }),
  (review, dimension) =>
    parallel(
      ((review && review.findings) || []).map((finding) => () =>
        agent(verifyPrompt(dimension.key, finding), {
          label: `verify:${dimension.key}`,
          phase: 'Verify',
          schema: VERDICT_SCHEMA,
        }).then((verdict) => ({ ...finding, dimension: dimension.key, verdict }))
      )
    )
)

const candidates = reviewed.flat().filter(Boolean)
const confirmed = candidates.filter((finding) => finding.verdict && finding.verdict.isReal)
const dropped = candidates.length - confirmed.length

log(`Confirmed ${confirmed.length} finding(s); dropped ${dropped} as refuted false positive(s)`)

return {
  mode: 'check',
  dimensions: selected.map((dimension) => dimension.key),
  candidates: candidates.length,
  confirmed,
  droppedAsFalsePositive: dropped,
}
