// lib/hail/artifacts.js — renderers for HAIL operating-model artifacts.
//
// Each renderer turns a SYNTHESIZED (derived) diagnostic payload into a durable
// markdown artifact via lib/runtime.js::createArtifact, so it lands in the
// engagement's project library and respects existing ACL / encryption rules.
//
// These render the diagnostic AGENT'S synthesized prose — never raw interview
// answers — so a restricted answer value cannot appear here by construction.
// All interpolated values are still markdown-escaped defensively.

import { createArtifact } from '../runtime.js';

function esc(s) {
  return String(s == null ? '' : s).replace(/[\\`*_{}\[\]<>|]/g, (c) => `\\${c}`);
}

function bullet(label, value) {
  return `- **${esc(label)}:** ${esc(value) || '_—_'}`;
}

// ── Operating profile ────────────────────────────────────────────────────────

export function renderOperatingProfileArtifact({ engagement, profile, confidence_notes = [] }) {
  const p = profile || {};
  const lines = [
    `# Operating Profile — ${esc(engagement?.principal_name || 'Principal')}`,
    '',
    '> How the principal decides, delegates, and protects their reputation. Observation is kept separate from inference; items needing confirmation are flagged.',
    '',
    '## Profile',
    bullet('Decision style', p.decision_style),
    bullet('Delegation', p.delegation),
    bullet('Review thresholds', p.review_thresholds),
    bullet('Tone', p.tone),
    bullet('Escalation', p.escalation),
    '',
  ];
  const needs = confidence_notes.filter((n) => n && n.confidence === 'needs_confirmation');
  if (needs.length) {
    lines.push('## Needs practitioner confirmation', '');
    for (const n of needs) lines.push(`- ${esc(n.item)}`);
    lines.push('');
  }
  return createArtifact({
    title: `Operating profile — ${engagement?.principal_name || engagement?.id}`,
    kind: 'markdown',
    content: lines.join('\n'),
    project_id: engagement?.project_id || null,
    agent_id: 'hail-diagnostic-analyst',
  });
}

// ── Role / capacity map ──────────────────────────────────────────────────────

export function renderRoleMapArtifact({ engagement, roles = [], boundaries = [] }) {
  const lines = [
    `# Role & Capacity Map — ${esc(engagement?.principal_name || 'Principal')}`,
    '',
    '> Every hat the principal wears, the data classes each touches, and where contexts must never overlap.',
    '',
    '## Roles & capacities',
    '',
  ];
  if (roles.length === 0) lines.push('_No roles identified._', '');
  for (const r of roles) {
    lines.push(`### ${esc(r.name || r.slug)}`);
    lines.push(bullet('Scope', r.scope));
    lines.push(bullet('Counterparties', Array.isArray(r.counterparties) ? r.counterparties.join(', ') : r.counterparties));
    lines.push(bullet('Data classes', Array.isArray(r.data_classes) ? r.data_classes.join(', ') : r.data_classes));
    lines.push('');
  }
  lines.push('## Boundaries & prohibited overlaps', '');
  if (boundaries.length === 0) lines.push('_No boundaries recorded._', '');
  for (const b of boundaries) {
    const between = b.role_b_slug ? `${esc(b.role_a_slug)} ↔ ${esc(b.role_b_slug)}` : esc(b.role_a_slug);
    lines.push(`- **${esc(b.boundary_kind)}** (${esc(b.severity || 'high')}) — ${between}: ${esc(b.description)}`);
  }
  lines.push('');
  return createArtifact({
    title: `Role & capacity map — ${engagement?.principal_name || engagement?.id}`,
    kind: 'markdown',
    content: lines.join('\n'),
    project_id: engagement?.project_id || null,
    agent_id: 'hail-diagnostic-analyst',
  });
}

// ── Friction map ─────────────────────────────────────────────────────────────

export function renderFrictionMapArtifact({ engagement, frictions = [] }) {
  const lines = [
    `# Friction Map — ${esc(engagement?.principal_name || 'Principal')}`,
    '',
    '> Where work stalls, information disappears, bottlenecks form, or judgment is overloaded — prioritised for the blueprint.',
    '',
  ];
  if (frictions.length === 0) lines.push('_No frictions identified._', '');
  const sorted = [...frictions].sort((a, b) => (b.priority || 0) - (a.priority || 0));
  for (const f of sorted) {
    lines.push(`## [${esc(f.grouping || 'general')}] ${esc(f.description)}`);
    lines.push(bullet('Impact', f.impact));
    lines.push(bullet('Frequency', f.frequency));
    lines.push(bullet('Current workaround', f.current_workaround));
    lines.push(bullet('Suggested agent function', f.suggested_agent_function));
    lines.push(bullet('Risk level', f.risk_level));
    lines.push(bullet('Priority', f.priority));
    lines.push('');
  }
  return createArtifact({
    title: `Friction map — ${engagement?.principal_name || engagement?.id}`,
    kind: 'markdown',
    content: lines.join('\n'),
    project_id: engagement?.project_id || null,
    agent_id: 'hail-diagnostic-analyst',
  });
}

// ── Governance matrix + classification framework ─────────────────────────────

export function renderGovernanceMatrixArtifact({ engagement, rules = [], classification_framework = null }) {
  const lines = [
    `# Governance Matrix — ${esc(engagement?.principal_name || 'Principal')}`,
    '',
    '> What each agent function may decide, draft, recommend, execute, or must escalate — and what requires human approval. Compatible with the madarX OS trust-mode / approval / audit model.',
    '',
    '| Action | Risk | Authority | Role | Data class | Reviewer | Approval | Evidence |',
    '| --- | --- | --- | --- | --- | --- | --- | --- |',
  ];
  for (const r of rules) {
    lines.push(`| ${esc(r.action_type)} | ${esc(r.risk)} | ${esc(r.authority)} | ${esc(r.role_slug) || '—'} | ${esc(r.data_class) || '—'} | ${esc(r.reviewer_role) || '—'} | ${r.approval_required ? 'required' : 'auto'} | ${r.evidence_required ? 'yes' : 'no'} |`);
  }
  lines.push('');
  if (classification_framework && (classification_framework.default || (classification_framework.rules || []).length)) {
    lines.push('## Classification framework', '');
    if (classification_framework.default) lines.push(bullet('Default sensitivity', classification_framework.default));
    for (const cr of classification_framework.rules || []) {
      lines.push(`- **${esc(cr.data)}** → ${esc(cr.sensitivity)}`);
    }
    lines.push('');
  }
  return createArtifact({
    title: `Governance matrix — ${engagement?.principal_name || engagement?.id}`,
    kind: 'markdown',
    content: lines.join('\n'),
    project_id: engagement?.project_id || null,
    agent_id: 'hail-blueprint-architect',
  });
}

// ── Agent operating model / roster ───────────────────────────────────────────

export function renderAgentRosterArtifact({ engagement, blueprints = [] }) {
  const lines = [
    `# Agent Operating Model — ${esc(engagement?.principal_name || 'Principal')}`,
    '',
    '> The designed set of intelligent functions, each with a clear purpose, role scope, authority, and review gates. No agent acts in the principal’s name without a gate.',
    '',
  ];
  if (blueprints.length === 0) lines.push('_No agents proposed._', '');
  for (const b of blueprints) {
    lines.push(`## ${esc(b.name)} \`${esc(b.id)}\``);
    lines.push(bullet('Purpose', b.purpose));
    lines.push(bullet('Role scope', b.role_scope));
    lines.push(bullet('Engine', b.engine));
    lines.push(bullet('Memory scope', b.memory_scope));
    lines.push(bullet('Schedule', b.schedule));
    lines.push(bullet('Risk tier', b.risk_tier));
    lines.push(bullet('Approval', b.approval));
    lines.push(bullet('Tools', Array.isArray(b.tools) ? b.tools.join(', ') : b.tools));
    lines.push(bullet('Review gates', Array.isArray(b.review_gates) ? b.review_gates.join(', ') : b.review_gates));
    lines.push('');
  }
  return createArtifact({
    title: `Agent operating model — ${engagement?.principal_name || engagement?.id}`,
    kind: 'markdown',
    content: lines.join('\n'),
    project_id: engagement?.project_id || null,
    agent_id: 'hail-blueprint-architect',
  });
}

// ── Setup plan (dry-run) ─────────────────────────────────────────────────────

export function renderSetupPlanArtifact({ engagement, setup_package }) {
  const items = (setup_package?.items) || [];
  const lines = [
    `# Setup Plan (dry-run) — ${esc(engagement?.principal_name || 'Principal')}`,
    '',
    '> A **dry-run** proposal of the madarX OS configuration this engagement needs. Nothing here is applied. Promotion to live configuration requires the setup-package approval gate, and every irreversible item still gates individually. No secret values appear in this plan.',
    '',
    `Generated by: ${esc(setup_package?.generated_by) || '—'} · Items: ${items.length}`,
    '',
    '| Type | Ref | Risk | Approval | Rationale |',
    '| --- | --- | --- | --- | --- |',
  ];
  for (const it of items) {
    lines.push(`| ${esc(it.type)} | ${esc(it.ref)} | ${esc(it.risk)} | ${it.requires_approval ? 'required' : 'auto'} | ${esc(it.rationale) || '—'} |`);
  }
  lines.push('');
  return createArtifact({
    title: `Setup plan (dry-run) — ${engagement?.principal_name || engagement?.id}`,
    kind: 'markdown',
    content: lines.join('\n'),
    project_id: engagement?.project_id || null,
    agent_id: 'hail-blueprint-architect',
  });
}

// ── Pilot test report ────────────────────────────────────────────────────────

export function renderPilotTestReportArtifact({ engagement, agents = [] }) {
  const live = agents.filter((a) => a.status === 'live');
  const lines = [
    `# Pilot Test Report — ${esc(engagement?.principal_name || 'Principal')}`,
    '',
    '> A focused set of pilot agents is live on the principal’s own infrastructure, tested against real work. Each acts only within its governance authority and review gates.',
    '',
    `## Pilot agents live: ${live.length} / ${agents.length}`,
    '',
    '| Agent | Status | Provisioned id |',
    '| --- | --- | --- |',
  ];
  for (const a of agents) {
    lines.push(`| ${esc(a.name || a.agent_slug)} | ${esc(a.status)} | ${esc(a.provisioned_agent_id) || '—'} |`);
  }
  lines.push('', '## Notes', '- Pilot agents operate under the approved governance matrix; every in-name action passes its review threshold.', '- Outcomes from this pilot inform the Managed Layer activation decision.', '');
  return createArtifact({
    title: `Pilot test report — ${engagement?.principal_name || engagement?.id}`,
    kind: 'markdown',
    content: lines.join('\n'),
    project_id: engagement?.project_id || null,
    agent_id: 'hail-pilot',
    dedupe_key: `hail-pilot-report-${engagement?.id}`,
  });
}

// ── Diagnostic report (cover) ────────────────────────────────────────────────

export function renderDiagnosticReportArtifact({ engagement, payload, artifact_links = {} }) {
  const p = payload || {};
  const lines = [
    `# Diagnostic Report — ${esc(engagement?.principal_name || 'Principal')}`,
    '',
    esc(p.summary || 'Operating-model diagnostic from the HAIL Configuration Interview.'),
    '',
    '## Deliverables',
    `- Operating profile${artifact_links.operating_profile ? ` (artifact ${esc(artifact_links.operating_profile)})` : ''}`,
    `- Role & capacity map${artifact_links.role_map ? ` (artifact ${esc(artifact_links.role_map)})` : ''}`,
    `- Friction map${artifact_links.friction_map ? ` (artifact ${esc(artifact_links.friction_map)})` : ''}`,
    '',
    `## Roles identified: ${(p.roles || []).length}`,
    `## Frictions identified: ${(p.frictions || []).length}`,
    `## Items needing confirmation: ${(p.confidence_notes || []).filter((n) => n?.confidence === 'needs_confirmation').length}`,
    '',
  ];
  return createArtifact({
    title: `Diagnostic report — ${engagement?.principal_name || engagement?.id}`,
    kind: 'markdown',
    content: lines.join('\n'),
    project_id: engagement?.project_id || null,
    agent_id: 'hail-diagnostic-analyst',
  });
}
