import { adapters, migrationFields, newUuid } from '@/services/serviceConfig';
import { auditService } from '@/services/auditService';

export const OSSIGUARD_APPROVAL_STATUSES = ['Prototype', 'Measurement Required', 'Workshop Verified', 'CAD Verified', 'Approved Connector Revision', 'Superseded'];
export const OSSIGUARD_GEOMETRY_STATUSES = ['Visual Reference', 'Measurement Required', 'Workshop Verified', 'CAD Verified', 'Approved Connector Revision', 'Superseded'];
export const OSSIGUARD_RETENTION_METHODS = ['Screw fasteners', 'Captive clips', 'Alignment pins + clips', 'Flexible receiver insert', 'Replaceable tabs', 'Secondary safety retention', 'Custom'];
export const OSSIGUARD_COVER_INTERFACES = ['Two-piece clam shell', 'Front and rear shell', 'Left and right shell', 'Hinged cover', 'Slide-on panel', 'Clip-on panel', 'Replaceable outer panel', 'Modular armour plates'];
export const ATTACHMENT_METHODS = ['None', 'SHiRE Ossiguard', 'Direct adhesive', 'Strap', 'Custom'];

export const SAFETY_BANNER = 'Ossiguard and all attached covers are non-load-bearing, cosmetic only, and must never support body weight or alter prosthetic alignment.';

export const PROHIBITED_ATTACH_TARGETS = ['Osseointegration implant', 'Abutment', 'Stoma', 'Skin', 'Residual limb', 'Unknown structural component', 'Joint movement surface', 'Safety-release mechanism'];

export const ossiguardService = {
  list: () => adapters.database.list('OssiguardProfile'),
  forCustomer: (customer_uuid) => adapters.database.filter('OssiguardProfile', { customer_uuid }, '-connector_revision'),
  get: async (uuid) => (await adapters.database.filter('OssiguardProfile', { uuid }, '-updated_date', 1))[0],

  async create(data, actor) {
    const { id, created_date, updated_date, created_by_id, ...portable } = data;
    const record = await adapters.database.create('OssiguardProfile', {
      ...portable,
      uuid: newUuid('ossiguard'),
      geometry_status: data.geometry_status || 'Visual Reference',
      approval_status: data.approval_status || 'Prototype',
      connector_revision: data.connector_revision || 1,
      ...migrationFields(actor),
    });
    await auditService.record('ossiguard_created', 'OssiguardProfile', record.uuid, `Ossiguard profile ${record.profile_name} v${record.version} rev${record.connector_revision} created`, actor);
    return record;
  },

  async update(record, data, actor) {
    const { id, created_date, updated_date, created_by_id, ...editable } = data;
    const updated = await adapters.database.update('OssiguardProfile', record.id, { ...editable, updated_by_name: actor });
    await auditService.record('ossiguard_updated', 'OssiguardProfile', record.uuid, `Ossiguard profile ${record.profile_name} updated`, actor);
    return updated;
  },

  async newRevision(uuid, data, actor) {
    const current = await ossiguardService.get(uuid);
    if (!current) return null;
    const { id, created_date, updated_date, created_by_id, revision, connector_revision, uuid: _uuid, ...rest } = current;
    const nextRev = (current.connector_revision || 1) + 1;
    const record = await ossiguardService.create({
      ...rest, ...data,
      connector_revision: nextRev,
      approval_status: data.approval_status || 'Prototype',
      geometry_status: data.geometry_status || 'Visual Reference',
      revision_notes: data.revision_notes || `Revision ${nextRev} from ${current.profile_name} rev${current.connector_revision}`,
    }, actor);
    await adapters.database.update('OssiguardProfile', current.id, { approval_status: 'Superseded', geometry_status: 'Superseded', updated_by_name: actor });
    await auditService.record('ossiguard_revision', 'OssiguardProfile', record.uuid, `Ossiguard ${record.profile_name} rev${nextRev} created — previous rev${current.connector_revision} preserved as superseded`, actor);
    return record;
  },

  async assignToProject(project, profile, actor) {
    const target = (profile.attaches_to_component_label || '').toLowerCase();
    const prohibited = PROHIBITED_ATTACH_TARGETS.some((p) => target.includes(p.toLowerCase().split(' ')[0]));
    if (prohibited) {
      await auditService.record('ossiguard_assign_blocked', 'OssiguardProfile', profile.uuid, `BLOCKED: attempt to attach Ossiguard to prohibited target "${profile.attaches_to_component_label}"`, actor);
      throw new Error(`Ossiguard must not attach to "${profile.attaches_to_component_label}". Attach only to approved external prosthetic components or cosmetic mounting brackets.`);
    }
    const updated = await adapters.database.update('CoverProject', project.id, {
      ossiguard_profile_uuid: profile.uuid,
      ossiguard_profile_label: `${profile.profile_name} v${profile.version} rev${profile.connector_revision}`,
      ossiguard_revision: profile.connector_revision,
      ossiguard_attachment_method: 'SHiRE Ossiguard',
      updated_by_name: actor,
    });
    await auditService.record('ossiguard_assigned', 'CoverProject', project.uuid, `Ossiguard ${profile.profile_name} rev${profile.connector_revision} assigned to project`, actor);
    return updated;
  },

  async removeFromProject(project, actor) {
    const updated = await adapters.database.update('CoverProject', project.id, {
      ossiguard_profile_uuid: null,
      ossiguard_profile_label: null,
      ossiguard_revision: null,
      ossiguard_attachment_method: 'None',
      updated_by_name: actor,
    });
    await auditService.record('ossiguard_removed', 'CoverProject', project.uuid, 'Ossiguard connector removed from project', actor);
    return updated;
  },

  async reuseForCustomer(sourceProfileUuid, customerUuid, actor) {
    const source = await ossiguardService.get(sourceProfileUuid);
    if (!source) return null;
    const { id, created_date, updated_date, created_by_id, revision, connector_revision, uuid, ...rest } = source;
    const record = await ossiguardService.create({
      ...rest,
      customer_uuid: customerUuid,
      data_label: `Reused from ${source.profile_name} rev${source.connector_revision}`,
    }, actor);
    await auditService.record('ossiguard_reused', 'OssiguardProfile', record.uuid, `Ossiguard fit reused for customer (source ${source.profile_name} rev${source.connector_revision})`, actor);
    return record;
  },

  async listRevisions(profileName) {
    const all = await adapters.database.list('OssiguardProfile');
    return all.filter((p) => p.profile_name === profileName).sort((a, b) => (b.connector_revision || 0) - (a.connector_revision || 0));
  },

  validate(profile, project) {
    if (!profile) return { status: 'Blocked', issues: ['No Ossiguard profile selected'], level: 'blocked', issueObjects: [] };
    const issues = [];
    if (!profile.profile_name) issues.push({ level: 'blocked', text: 'Exact Ossiguard profile not selected' });
    if (!profile.connector_revision) issues.push({ level: 'blocked', text: 'Revision not identified' });
    if (!profile.attaches_to_component_uuid && !profile.attaches_to_component_label) issues.push({ level: 'blocked', text: 'Receiving prosthetic component not identified' });
    if (!profile.approved_contact_surfaces) issues.push({ level: 'warning', text: 'Attachment surface not documented as approved' });

    const dimsMissing = [];
    if (!profile.overall_width_mm) dimsMissing.push('overall width');
    if (!profile.overall_depth_mm) dimsMissing.push('overall depth');
    if (!profile.overall_height_mm) dimsMissing.push('overall height');
    if (!profile.attachment_point_count) dimsMissing.push('attachment point count');
    if (!profile.attachment_point_coordinates) dimsMissing.push('attachment point coordinates');
    if (dimsMissing.length) issues.push({ level: (profile.geometry_status === 'Approved Connector Revision' || profile.geometry_status === 'CAD Verified') ? 'blocked' : 'warning', text: `Dimensions not verified: ${dimsMissing.join(', ')}` });

    if (!profile.fastener_type && !profile.retention_method) issues.push({ level: 'warning', text: 'Hardware not identified' });
    if (!profile.insertion_direction) issues.push({ level: 'warning', text: 'Insertion direction not recorded' });
    if (!profile.removal_direction) issues.push({ level: 'warning', text: 'Removal direction not recorded' });

    if (profile.geometry_status === 'Visual Reference') issues.push({ level: 'warning', text: 'Geometry is visual reference only — not verified' });
    if (profile.geometry_status === 'Measurement Required') issues.push({ level: 'warning', text: 'Measurements still required' });

    const target = (profile.attaches_to_component_label || '').toLowerCase();
    if (target.includes('implant')) issues.push({ level: 'blocked', text: 'No implant attachment — Ossiguard must not attach to osseointegration implant' });
    if (target.includes('abutment')) issues.push({ level: 'blocked', text: 'No abutment attachment' });
    if (target.includes('stoma')) issues.push({ level: 'blocked', text: 'No stoma attachment' });
    if (target.includes('skin')) issues.push({ level: 'blocked', text: 'No skin contact' });

    const hasCad = profile.step_file_url || profile.stl_file_url || profile.three_mf_file_url;
    if (!hasCad && profile.approval_status === 'Approved Connector Revision') issues.push({ level: 'blocked', text: 'Approved profile has no CAD file attached' });

    if (project && project.ossiguard_revision && profile.connector_revision && project.ossiguard_revision !== profile.connector_revision) {
      issues.push({ level: 'warning', text: 'Connector CAD revision does not match project revision' });
    }

    const hasBlocked = issues.some((i) => i.level === 'blocked');
    const hasWarning = issues.some((i) => i.level === 'warning');
    const status = hasBlocked ? 'Blocked' : hasWarning ? 'Warning' : 'Pass';
    return { status, issues: issues.map((i) => i.text), level: hasBlocked ? 'blocked' : hasWarning ? 'warning' : 'pass', issueObjects: issues };
  },

  validateProject(project, profile, limb) {
    const base = ossiguardService.validate(profile, project);
    const issues = [...(base.issueObjects || [])];

    if (limb && limb.interface_type === 'Osseointegration') {
      issues.push({ level: 'pass', text: 'Osseointegration detected — stoma and surrounding area are permanent no-contact, no-cover, no-attachment zones' });
      const target = (profile && profile.attaches_to_component_label || '').toLowerCase();
      if (target.includes('implant') || target.includes('abutment') || target.includes('stoma')) {
        issues.push({ level: 'blocked', text: 'Ossiguard must not attach to implant, abutment or stoma for osseointegration projects' });
      }
    }

    if (project && project.sensitive_area_summary && profile && profile.emergency_release_clearance_mm == null) {
      issues.push({ level: 'warning', text: 'Emergency-release clearance not recorded — verify no safety-release obstruction' });
    }

    const hasBlocked = issues.some((i) => i.level === 'blocked');
    const hasWarning = issues.some((i) => i.level === 'warning');
    const status = hasBlocked ? 'Blocked' : hasWarning ? 'Warning' : 'Pass';
    return { status, issues: issues.map((i) => i.text), level: hasBlocked ? 'blocked' : hasWarning ? 'warning' : 'pass', issueObjects: issues };
  },

  canProceedToCAD(project, profile, limb) {
    const v = ossiguardService.validateProject(project, profile, limb);
    return v.level !== 'blocked';
  },

  status: () => ({ implemented: true, label: 'Ossiguard Connector System active', boundary: SAFETY_BANNER }),
};