// lib/hail/pilot.js — HAIL pilot stage (artifact-first).
//
// When the pilot-launch gate is approved, lib/hail/review-gates.js marks the
// engagement's PROVISIONED agents 'live' (only agents the applier actually
// created can go live — the approved/applied setup package is the prerequisite).
// This module renders the artifact-first pilot test report and reads pilot
// status for the cockpit / API. It writes only the artifacts table (via
// createArtifact) and never process_cases.* nor any runtime config.

import { getDb } from '../db.js';
import { getEngagement } from './engagements.js';
import { renderPilotTestReportArtifact } from './artifacts.js';

function safeParse(s) { try { return JSON.parse(s); } catch { return {}; } }

// Blueprint agents with their provisioning/live status.
export function listPilotAgents(engagement_id) {
  if (!engagement_id) return [];
  return getDb()
    .prepare('SELECT agent_slug, payload_json, status, provisioned_agent_id FROM hail_agent_blueprints WHERE engagement_id = ? ORDER BY created_at ASC')
    .all(engagement_id)
    .map((r) => ({ agent_slug: r.agent_slug, name: safeParse(r.payload_json).name || r.agent_slug, status: r.status, provisioned_agent_id: r.provisioned_agent_id }));
}

// True once the pilot-launch gate has been approved for this engagement.
export function isPilotLaunched(engagement_id) {
  if (!engagement_id) return false;
  const row = getDb()
    .prepare("SELECT 1 FROM hail_review_gates WHERE engagement_id = ? AND gate_type = 'pilot_launch' AND decision = 'approved' LIMIT 1")
    .get(engagement_id);
  return !!row;
}

// Render the pilot test report artifact. Idempotent (dedupe_key in the renderer)
// so repeated calls return the same artifact without rewriting.
export function renderPilotTestReport(engagement_id) {
  const engagement = getEngagement(engagement_id);
  if (!engagement) throw new Error('renderPilotTestReport: engagement not found');
  return renderPilotTestReportArtifact({ engagement, agents: listPilotAgents(engagement_id) });
}

// Ensure the pilot report exists once the pilot has launched (idempotent). Safe
// to call on every cockpit/API read. Returns the pilot status snapshot.
export function syncPilotState(engagement) {
  const eid = engagement?.id;
  if (!eid) return { pilot_launched: false, agents: [], report_artifact_id: null };
  const launched = isPilotLaunched(eid);
  let reportId = null;
  if (launched) {
    try { reportId = renderPilotTestReport(eid).artifact_id; } catch { reportId = null; }
  }
  return {
    pilot_launched: launched,
    managed_layer: engagement.current_stage === 'managed_layer',
    agents: listPilotAgents(eid),
    report_artifact_id: reportId,
  };
}

export function getPilotStatus(engagement_id) {
  const engagement = getEngagement(engagement_id);
  if (!engagement) return null;
  return { engagement_id, ...syncPilotState(engagement) };
}
