import { base44 } from '@/api/base44Client';
import { convertStationsToRings } from '@/components/viewportV2/AnatomicalMesh';

export const MM_PER_UNIT = 70;
export const SOCKET_BASE_Y = 2.92;
export const COVER_BASE_Y = 2.78;

export const GEOMETRY_STATUS = {
  generic: 'Generic visual geometry — not customer-specific and not manufacturing CAD.',
  measurement: 'Measurement-driven visualisation — review required and not manufacturing geometry.',
  ready: 'Verified inputs complete — ready for the external CAD generator.',
  manufacturing: 'Manufacturing geometry imported — validation required.',
};

export const STATUS_TONE = {
  generic: 'slate',
  measurement: 'amber',
  ready: 'green',
  manufacturing: 'purple',
};

/**
 * Build a geometry input object for Babylon V2 from verified workshop
 * envelope-station measurements. Babylon never queries the DB directly —
 * it receives this prepared object via props.
 */
export async function loadProjectGeometry(projectUuid) {
  if (!projectUuid) return emptyGeometry();
  let project = null;
  try { project = await base44.entities.CoverProject.get(projectUuid); } catch (_) { project = null; }

  let sessions = [];
  try { sessions = await base44.entities.MeasurementSession.filter({ project_uuid: projectUuid }); } catch (_) {}
  sessions = (sessions || []).filter((s) => s.record_state !== 'archived');
  const sessionIds = sessions.map((s) => s.uuid);

  let stations = [];
  if (sessionIds.length) {
    try { stations = await base44.entities.EnvelopeStation.filter({ session_uuid: { $in: sessionIds } }); } catch (_) { stations = []; }
    if (!stations.length) {
      for (const sid of sessionIds) {
        try { const part = await base44.entities.EnvelopeStation.filter({ session_uuid: sid }); if (part) stations = stations.concat(part); } catch (_) {}
      }
    }
  }
  stations = stations || [];

  const withDims = stations.filter((s) => (s.total_width_mm || (s.max_medial_mm != null && s.max_lateral_mm != null)) && (s.total_depth_mm || (s.max_anterior_mm != null && s.max_posterior_mm != null)));

  const coverRings = convertStationsToRings(stations, MM_PER_UNIT, COVER_BASE_Y, 1);
  const socketRings = convertStationsToRings(stations, MM_PER_UNIT, SOCKET_BASE_Y, 0.82);

  let status = 'generic';
  if (withDims.length >= 6) status = 'ready';
  else if (withDims.length > 0) status = 'measurement';

  return {
    geometryStatus: status,
    statusLabel: GEOMETRY_STATUS[status],
    statusTone: STATUS_TONE[status],
    coverStations: coverRings,
    socketStations: socketRings,
    envelopeStations: stations,
    sourceCount: stations.length,
    dimensionedCount: withDims.length,
    missing: withDims.length < 6 ? [`${6 - withDims.length} more cross-section station(s) with width & depth required`] : [],
    project,
    sessions,
  };
}

function emptyGeometry() {
  return {
    geometryStatus: 'generic',
    statusLabel: GEOMETRY_STATUS.generic,
    statusTone: STATUS_TONE.generic,
    coverStations: null,
    socketStations: null,
    envelopeStations: [],
    sourceCount: 0,
    dimensionedCount: 0,
    missing: [],
    project: null,
    sessions: [],
  };
}

/**
 * Upsert a workshop cross-section station measurement (drives geometry).
 */
export async function saveStationMeasurement({ sessionUuid, componentUuid, station }) {
  let existing = null;
  try {
    const list = await base44.entities.EnvelopeStation.filter({ session_uuid: sessionUuid, station_name: station.station_name });
    if (list && list.length) existing = list[0];
  } catch (_) {}
  const today = new Date().toISOString().slice(0, 10);
  const payload = {
    component_uuid: componentUuid || 'generic',
    session_uuid: sessionUuid,
    station_name: station.station_name,
    height_from_origin_mm: num(station.height_from_origin_mm),
    total_width_mm: num(station.total_width_mm),
    total_depth_mm: num(station.total_depth_mm),
    max_medial_mm: num(station.max_medial_mm),
    max_lateral_mm: num(station.max_lateral_mm),
    max_anterior_mm: num(station.max_anterior_mm),
    max_posterior_mm: num(station.max_posterior_mm),
    circumference_mm: num(station.circumference_mm),
    clearance_requirement_mm: num(station.clearance_requirement_mm),
    shape_classification: station.shape_classification || 'Workshop measured',
    entered_by: station.entered_by || 'Workshop',
    date_entered: today,
    notes: station.notes || '',
  };
  if (existing) return base44.entities.EnvelopeStation.update(existing.id, payload);
  return base44.entities.EnvelopeStation.create(payload);
}

const num = (v) => (v === '' || v == null ? undefined : Number(v));