import { appConfig, SHIREVAULT_BACKUP_PATH } from './appConfig';
import { NOTIFICATION_TYPES } from './agentTypes';

// Structured notifications ScanForge raises to SHiRE. Each links back to /agents/scanforge.
export function buildShireNotification(type, payload = {}) {
  if (!NOTIFICATION_TYPES.includes(type)) throw new Error('UNSUPPORTED_NOTIFICATION_TYPE');
  return {
    type,
    agentId: 'scanforge',
    link: appConfig.scanforgeRoute,
    payload,
    createdAt: new Date().toISOString()
  };
}

// SHiREVault verification contract. Before any backup-dependent action, ScanForge asks
// the Scan Bridge to confirm the mount is present, identifiable, writable, readable, and
// checksum-verified. If any check fails, the action stops — no silent local fallback.
export async function verifyShireVault(scanBridgeClient) {
  try {
    const result = await scanBridgeClient.request('/api/v1/storage/shirevault/verify', { method: 'POST', body: JSON.stringify({ path: SHIREVAULT_BACKUP_PATH }) });
    const ok = result?.present && result?.writable && result?.readable && result?.identityVerified && result?.checksumVerified;
    return { ok, result, reason: ok ? null : (result?.reason || 'SHiREVault verification failed') };
  } catch (error) {
    return { ok: false, reason: 'SHiREVault unavailable — backup-dependent action stopped' };
  }
}

// Controlled Forge handoff. ScanForge never certifies or manufactures — Forge treats
// the result as imported source geometry. No warnings are removed, no printer is selected
// without confirmation, and no socket/implant/load-bearing geometry is ever generated.
export function buildForgeHandoff({
  sourceProjectId, sourceMeshVersionId, sourceScanMode, intendedUse, scaleStatus,
  dimensions, meshFormat, meshLocationId, meshSha256, watertight, printCheckStatus,
  warnings = [], calibrationProfileId = null
}) {
  if (!['stl', 'obj', 'ply', 'glb'].includes(meshFormat)) throw new Error('UNSUPPORTED_MESH_FORMAT');
  if (dimensions?.unit !== 'mm') throw new Error('FORGE_HANDOFF_REQUIRES_MM');
  return {
    sourceProjectId, sourceMeshVersionId, sourceScanMode, intendedUse, scaleStatus,
    dimensions, meshFormat, meshLocationId, meshSha256, watertight, printCheckStatus,
    warnings, calibrationProfileId,
    createdAt: new Date().toISOString(),
    certification: 'none — imported source geometry only'
  };
}