// GeometryService adapter — development mock.
// Every mocked response includes simulation: true.
// Never display "Print Ready", "Export Complete" or "Validated Geometry" from a simulated response.

// Assemble the full LimbForge Geometry Engine request payload from project data.
// Includes original + processed artwork, processing settings, layer transforms,
// projection/application mode, emboss/engraving/relief/stencil settings, cover
// model reference and all zone data.
export function buildGeometryRequest({ project, cover, layers = [], assets = [], concept = null } = {}) {
  const activeLayers = (layers || []).filter(l => l.visible);
  const assetFor = (l) => (assets || []).find(a => a.id === l?.artworkAssetId);
  const appMode = project?.applicationMode || 'colour_texture';
  const gs = project?.geometrySettings || {};
  return {
    project_id: project?.id || null,
    simulation: true,
    cover_model: {
      reference: cover?.sourceFile || null,
      id: cover?.id || null,
      name: cover?.name || null,
      limb_type: cover?.limbType || null,
      side: cover?.side || null,
      source_format: cover?.sourceFormat || null,
      bounding_box: cover?.boundingBox || null,
      connector_type: cover?.connectorType || null,
      ossiguard_profile: cover?.ossiguardProfile || null
    },
    artwork: {
      original_reference: assetFor(activeLayers[0])?.originalFile || null,
      processed_reference: assetFor(activeLayers[0])?.processedFile || assetFor(activeLayers[0])?.originalFile || null,
      processing_settings: assetFor(activeLayers[0])?.processingSettings || {},
      width: assetFor(activeLayers[0])?.width || null,
      height: assetFor(activeLayers[0])?.height || null
    },
    layers: activeLayers.map(l => ({
      id: l.id,
      name: l.name,
      transform: {
        position_x: l.positionX || 0,
        position_y: l.positionY || 0,
        scale_x: l.scaleX ?? 1,
        scale_y: l.scaleY ?? 1,
        rotation: l.rotation || 0,
        mirrored: !!l.mirrored,
        opacity: l.opacity ?? 1
      },
      projection_mode: l.projectionMode || 'planar'
    })),
    application_mode: appMode,
    emboss: appMode === 'raised_emboss' ? {
      height: activeLayers[0]?.embossHeight ?? gs.embossHeight ?? null,
      bevel: gs.embossBevel ?? null,
      smoothing: gs.embossSmooth ?? null,
      minimum_feature: gs.embossMinFeature ?? null
    } : null,
    engraving: appMode === 'engraving' ? {
      depth: activeLayers[0]?.engravingDepth ?? gs.engravingDepth ?? null,
      bevel: gs.engraveBevel ?? null,
      smoothing: gs.engraveSmooth ?? null,
      minimum_feature: gs.engraveMinFeature ?? null
    } : null,
    relief: appMode === 'sculpted_relief' ? {
      strength: activeLayers[0]?.reliefStrength ?? gs.reliefStrength ?? null,
      height_range: gs.reliefRange ?? null,
      contrast: gs.reliefContrast ?? null,
      surface_blend: gs.reliefBlend ?? null
    } : null,
    stencil: appMode === 'stencil' ? {
      cut_depth: gs.stencilDepth ?? null,
      minimum_bridge: gs.stencilBridge ?? null,
      minimum_opening: gs.stencilOpening ?? null,
      island_removal: !!gs.stencilIslandRemoval
    } : null,
    decoration_zones: cover?.decorationZones || [],
    protected_zones: cover?.protectedZones || [],
    branding_zones: cover?.brandingZones || [],
    selected_concept_id: project?.selectedConceptId || concept?.id || null
  };
}

const simulated = (operation, extra = {}) =>
  new Promise(resolve => setTimeout(() => resolve({
    ok: true,
    simulation: true,
    operation,
    service_version: 'mock-0.1',
    ...extra
  }), 600));

export const GeometryService = {
  buildGeometryRequest,
  checkHealth: () => simulated('health', { status: 'simulation_only', connected: false }),
  uploadCover: payload => simulated('upload_cover', { cover_reference: payload?.cover_model?.reference || payload?.sourceFile || null }),
  uploadArtwork: payload => simulated('upload_artwork', { artwork_reference: payload?.artwork?.original_reference || payload?.originalFile || null }),
  generatePromptConcepts: payload => simulated('prompt_concepts', { concepts: [], prompt: payload?.promptText || '' }),
  createProjectionPreview: payload => simulated('projection_preview', { projection: payload?.application_mode || payload?.projectionMode || 'planar', layers: payload?.layers?.length || 0, real: false }),
  generateEmboss: payload => simulated('emboss', { settings: payload?.emboss, real: false }),
  generateEngraving: payload => simulated('engraving', { settings: payload?.engraving, real: false }),
  generateRelief: payload => simulated('relief', { settings: payload?.relief, real: false }),
  generateStencil: payload => simulated('stencil', { settings: payload?.stencil, real: false }),
  validateGeometry: payload => simulated('validate_geometry', { request: !!payload, real: false }),
  exportCover: () => Promise.resolve({
    ok: false,
    simulation: true,
    blocked: true,
    error: 'Real geometry service and writable SHiREVault are required for export.'
  }),
  getJobStatus: id => simulated('job_status', { id, status: 'completed', progress: 100, real: false }),

  // --- Design-first (Universal Design → Cover Variant) adapter methods ---
  // All mocked with simulation: true. None of these unlock Real Geometry,
  // Validated, or Print Ready states.

  // Evaluate browser-available cover metadata for design compatibility.
  analyseCoverCompatibility: payload => simulated('analyse_cover_compatibility', {
    cover_id: payload?.coverModelId || payload?.cover?.id || null,
    design_id: payload?.universalDesignId || payload?.design?.id || null,
    level: 'requires_processing',
    notes: 'Browser metadata only — final geometric compatibility needs the Geometry Engine.'
  }),

  // Browser adaptation preview is computed locally in src/lib/adaptation.js.
  // This method records that a preview was generated and never claims real fit.
  createAdaptationPreview: payload => simulated('create_adaptation_preview', {
    universal_design_id: payload?.universalDesignId || null,
    cover_model_id: payload?.coverModelId || null,
    strategy: payload?.strategy || 'best_fit',
    preview: 'browser_only',
    real: false
  }),

  // Submit a real adaptation request to the LimbForge Geometry Engine.
  submitDesignAdaptation: payload => simulated('submit_design_adaptation', {
    job_id: 'sim-' + (Date.now().toString(36)),
    request: payload,
    status: 'queued',
    real: false
  }),

  getAdaptationStatus: id => simulated('get_adaptation_status', { id, status: 'queued', progress: 0, real: false }),

  compareAdaptationStrategies: payload => simulated('compare_adaptation_strategies', {
    strategies: (payload?.strategies || ['best_fit', 'front_feature', 'full_wrap']).map(s => ({ strategy: s, score: null, real: false }))
  }),

  generateCoverVariant: payload => simulated('generate_cover_variant', {
    variant_id: null,
    universal_design_id: payload?.universalDesignId || null,
    cover_model_id: payload?.coverModelId || null,
    real: false
  }),

  validateCoverVariant: payload => simulated('validate_cover_variant', {
    variant_id: payload?.variantId || null,
    real: false
  }),

  // Export remains blocked until real geometry service + writable SHiREVault exist.
  exportCoverVariant: () => Promise.resolve({
    ok: false,
    simulation: true,
    blocked: true,
    error: 'Real geometry service and writable SHiREVault are required to export a cover variant.'
  })
};