import { appConfig } from '@/lib/appConfig';

function normaliseProjects(payload) {
  if (Array.isArray(payload)) return payload;
  if (Array.isArray(payload?.projects)) return payload.projects;
  if (Array.isArray(payload?.items)) return payload.items;
  return [];
}

export async function listProjects({ shireClient, limit = 50 }) {
  if (appConfig.mode === 'SHIRE_MODULE') {
    const result = await shireClient.listProjects();
    return normaliseProjects(result).slice(0, limit);
  }
  const { base44 } = await import('@/api/base44Client');
  return base44.entities.ScanProject.list('-updated_date', limit);
}

export async function createProject({ shireClient, project, safetyStatements }) {
  if (appConfig.mode === 'SHIRE_MODULE') {
    const result = await shireClient.performAction({
      actionId: crypto.randomUUID(),
      action: 'new_scan',
      parameters: {
        project: {
          ...project,
          scale_status: 'unscaled',
          workflow_stage: 'setup'
        },
        safetyConfirmation: {
          confirmation_type: 'pre_capture',
          confirmed: true,
          confirmed_at: new Date().toISOString(),
          statements: safetyStatements
        }
      },
      requiresConfirmation: true
    });
    const created = result?.project || result;
    if (!created?.id && !created?.projectId) throw new Error('SHIRE_AGENT_DID_NOT_RETURN_PROJECT_ID');
    return { ...created, id: created.id || created.projectId };
  }

  const { base44 } = await import('@/api/base44Client');
  const created = await base44.entities.ScanProject.create({
    ...project,
    scale_status: 'unscaled',
    workflow_stage: 'setup'
  });
  await base44.entities.SafetyConfirmation.create({
    project_id: created.id,
    confirmation_type: 'pre_capture',
    confirmed: true,
    confirmed_at: new Date().toISOString(),
    statements: safetyStatements
  });
  return created;
}
