#!/usr/bin/env node
// configure-rest-agents.mjs — one-shot maintenance.
//
// Sets a deliverable `expected_output` contract on the 13 non-Mines agents that
// were left with an empty contract. Missions + system_prompts are already
// accurate, so only expected_output is written. Idempotent.
//
// Note: completeness-agent and kyc-risk-verifier return STRICT JSON to the
// process engine (schema family completeness_v1 / kyc). Their per-workflow stage
// prompt is authoritative for exact fields; the contracts below document the
// standing JSON shape and make explicit "no markdown" — the opposite of the
// default markdown-report fallback.
//
// Usage:
//   node scripts/configure-rest-agents.mjs          # dry-run
//   node scripts/configure-rest-agents.mjs --apply  # write

process.env.MADARX_DISABLE_INPROC_DAEMON = '1';
const APPLY = process.argv.includes('--apply');

const CONTRACTS = {
  'ai-daily-brief': [
    'A madarX-branded daily brief in markdown — the final message IS the artifact (not a status recap).',
    'Sections in order: Top 5 Stories (each with source, timestamp, link, and a 3–5 sentence dek), Model & Product Releases, Funding & M&A, Policy & Regulation, What to Watch.',
    'Every item carries a real source and a working link to the original. Full prose — never a headline-only scorecard or run-status note.',
  ].join('\n'),

  'ops-agent': [
    'An operations status report in markdown: local workspace/system state inspected, risks ranked high→low with the evidence behind each, and owner-ready next actions.',
    'Concise enough for an ops dashboard, complete enough to act on without opening another document.',
    'No external sends and no destructive changes — findings and recommendations only.',
  ].join('\n'),

  'london-daily-weather-outfit-agent': [
    'A daily London weather + outfit artifact in markdown (filename london-weather-outfit-YYYY-MM-DD.md). Required sections:',
    '1. Header — date, day of week, generation time.',
    '2. Weather Summary — temp + feels-like (°C), daytime high / overnight low, precipitation type + %, wind speed/direction, humidity, UV index, condition summary, any alerts.',
    '3. Dressing Conditions At A Glance — one plain-English paragraph.',
    '4. Outfit A (Practical) and Outfit B (Styled) — each fully itemised: base/mid/outer layers, bottoms, footwear, accessories, fabric notes, with critical-vs-optional flagged.',
    '5. Key Reminders — 2–5 bullets. 6. Footer — data sources + fetch timestamp.',
    'Never fabricate weather: if fetch fails after two attempts, report the failure and list what could not be retrieved. No retail links.',
  ].join('\n'),

  'morning-conflict-brief': [
    'An executive conflict brief in markdown, drawn only from the 13 named independent outlets (no wire-service rewrites).',
    'Sections: headline summary, regional sections, source disagreements (contested facts flagged with which outlets diverge), and primary-source links per claim.',
    'Claims cross-referenced across sources; contested points labelled as contested rather than silently resolved.',
  ].join('\n'),

  'uae-ai-initiatives-tracker': [
    'A UAE AI weekly report saved via create_artifact (UAE_AI_Report_YYYY-MM-DD.md).',
    'Sections: Summary, Government & Policy, Private Sector Developments, Funding & Investment, Partnerships & International Collaboration, Regulatory & Ethics Updates, Research & Academia, Sources (numbered URLs).',
    'Each bullet factual, concise, and source-linked; speculative / low-credibility items tagged [UNVERIFIED]; empty categories marked "No notable updates this week."; recency focused on the past 7 days.',
  ].join('\n'),

  'personal-completeness-agent': [
    'STRICT JSON only — no markdown, no code fences, no prose around the object.',
    'The calling process stage defines the exact required fields; follow that stage prompt and judge ONLY the fields it lists — never invent additional requirements.',
    'Default completeness_v1 shape: { "outcome": "pass" | "needs_info", "missing_fields": [string], "warnings": [string], "summary": "one-paragraph plain-English assessment" }.',
    'Internal-consistency problems → warnings (soft, non-blocking) or missing_fields (blocking).',
  ].join('\n'),

  'personal-engineering-lead': [
    'An engineering status / handoff report in markdown. Sections: Summary, Changes (with PR/issue references via the gh tools), Review findings (severity-tagged), QA / test result, Next actions — marking which require owner approval.',
    'Implementation, review, QA, and preview deploys stay behind explicit approval gates: never merge, deploy, or run destructive commands without approval.',
  ].join('\n'),

  'personal-kyc-risk-verifier': [
    'STRICT JSON only — no markdown, no prose. Demo mode: build a synthetic report from the intake payload alone; never call external KYC services.',
    'The calling process stage defines exact fields; follow it.',
    'Default shape: { "risk_score": 0..1, "flags": [string], "sanctioned_list_hits": [string], "pep_check": "clear" | "review" | "hit", "rationale": "...", "recommended_action": "auto_pass" | "manual_review" | "reject" }.',
  ].join('\n'),

  'personal-marketing-lead': [
    'A marketing deliverable in markdown matching the request type — market research, launch copy, positioning, or a design brief.',
    'Required: clear sections, target audience + positioning stated explicitly, research-based claims cited to source URLs, and concrete next actions.',
    'Drafts only — no external posting or sending without explicit approval.',
  ].join('\n'),

  'personal-meeting-notes': [
    'A meeting-notes artifact in markdown produced from the recording. Sections: Summary, Transcript (or link to it), Decisions, Action Items (each with an owner and due date), Follow-ups.',
    'Action items must be explicit and assignable. Never invent content not present in the recording; flag inaudible or uncertain segments.',
  ].join('\n'),

  'personal-personal-assistant': [
    'An organized assistant briefing in markdown: relevant inbox items (sender, subject, why it matters), the calendar for the period, and DRAFT replies clearly labelled as drafts.',
    'Strict mode: any outbound action (email / WhatsApp) is held for explicit owner approval — never sent autonomously. No action on the operator\'s behalf without confirmation.',
  ].join('\n'),

  'personal-project-watcher': [
    'A weekly project pulse in markdown across the watched repos. Sections: Summary, Per-repo activity (open/merged PRs, new/closed issues, deploy status), Risks & blockers, Recommended next actions.',
    'Every item linked to its GitHub source; facts only — no speculation.',
  ].join('\n'),

  'personal-regulatory-drafter': [
    'A regulatory draft document (e.g. a Memorandum of Association for free-zone entity setup) saved as a markdown artifact.',
    'ALWAYS advisory and for human review: open with a clear disclaimer that it is a draft, not legal advice, and requires qualified legal review before any use.',
    'Mark every assumption and every placeholder field as [TO BE CONFIRMED]. Never file or submit externally.',
  ].join('\n'),
};

const { getAgent, updateAgent } = await import('../lib/runtime.js');
const { PROCESS_AGENT_TEMPLATES } = await import('../lib/process/seeds/agent-templates.js');

// The two JSON-returning verifier agents carry a default "owner-ready markdown"
// system_prompt that contradicts their strict-JSON output. Re-sync their live
// system_prompt from the seed template (single source of truth — see
// lib/process/seeds/agent-templates.js).
const JSON_AGENTS = {
  'personal-completeness-agent': 'completeness-agent',
  'personal-kyc-risk-verifier': 'kyc-risk-verifier',
};

console.log(`[configure-rest] mode: ${APPLY ? 'APPLY' : 'dry-run'}\n`);

console.log('[configure-rest] expected_output contracts:');
for (const [id, expected_output] of Object.entries(CONTRACTS)) {
  const a = getAgent(id);
  if (!a) { console.log(`  ! ${id} — NOT FOUND, skipping`); continue; }
  console.log(`  • ${id.padEnd(34)} (${a.name}) ← expected_output ${expected_output.length} chars`);
  if (APPLY) {
    const res = updateAgent(id, { expected_output });
    if (!res.ok) console.log(`      FAILED: ${res.error}`);
  }
}

console.log('\n[configure-rest] strict-JSON system_prompt re-sync:');
for (const [agentId, slug] of Object.entries(JSON_AGENTS)) {
  const tpl = PROCESS_AGENT_TEMPLATES.find(t => t.slug === slug);
  const a = getAgent(agentId);
  if (!a) { console.log(`  ! ${agentId} — NOT FOUND, skipping`); continue; }
  if (!tpl?.system_prompt) { console.log(`  ! ${slug} — template has no system_prompt, skipping`); continue; }
  console.log(`  • ${agentId.padEnd(34)} ← system_prompt ${tpl.system_prompt.length} chars (from seed ${slug})`);
  if (APPLY) {
    const res = updateAgent(agentId, { system_prompt: tpl.system_prompt });
    if (!res.ok) console.log(`      FAILED: ${res.error}`);
  }
}

console.log(`\n[configure-rest] ${APPLY ? 'done.' : 'dry run — pass --apply to write.'}`);
