/**
 * Orchestrator Service API Client
 * Handles coordinated workflows across Forecasting, Production, and Procurement services
 *
 * NEW in Sprint 2: Orchestrator Service coordinates the daily workflow:
 * 1. Forecasting Service → Get demand forecasts
 * 2. Production Service → Generate production schedule from forecast
 * 3. Procurement Service → Generate procurement plan from forecast + schedule
 */

import { apiClient } from '../client';
import {
  OrchestratorWorkflowRequest,
  OrchestratorWorkflowResponse,
  WorkflowExecutionSummary,
  WorkflowExecutionDetail,
  OrchestratorStatus,
  OrchestratorConfig,
  WorkflowStepResult
} from '../types/orchestrator';

// Re-export types for backward compatibility
export type {
  OrchestratorWorkflowRequest,
  OrchestratorWorkflowResponse,
  WorkflowExecutionSummary,
  WorkflowExecutionDetail,
  OrchestratorStatus,
  OrchestratorConfig,
  WorkflowStepResult
};

// ============================================================================
// ORCHESTRATOR WORKFLOW API FUNCTIONS
// ============================================================================

/**
 * Run the daily orchestrated workflow
 * This is the main entry point for coordinated planning
 *
 * Workflow:
 * 1. Forecasting Service: Get demand forecasts for target date
 * 2. Production Service: Generate production schedule from forecast
 * 3. Procurement Service: Generate procurement plan from forecast + schedule
 *
 * NEW in Sprint 2: Replaces autonomous schedulers with centralized orchestration
 */
export async function runDailyWorkflow(
  tenantId: string,
  request?: OrchestratorWorkflowRequest
): Promise<OrchestratorWorkflowResponse> {
  return apiClient.post<OrchestratorWorkflowResponse>(
    `/tenants/${tenantId}/orchestrator/run-daily-workflow`,
    request || {}
  );
}

/**
 * Run workflow for a specific date
 */
export async function runWorkflowForDate(
  tenantId: string,
  targetDate: string,
  options?: Omit<OrchestratorWorkflowRequest, 'target_date'>
): Promise<OrchestratorWorkflowResponse> {
  return runDailyWorkflow(tenantId, {
    ...options,
    target_date: targetDate
  });
}

/**
 * Test workflow with sample data (for development/testing)
 */
export async function testWorkflow(
  tenantId: string
): Promise<OrchestratorWorkflowResponse> {
  return apiClient.post<OrchestratorWorkflowResponse>(
    `/tenants/${tenantId}/orchestrator/test-workflow`,
    {}
  );
}

/**
 * Get list of workflow executions
 */
export async function listWorkflowExecutions(
  tenantId: string,
  params?: {
    status?: WorkflowExecutionSummary['status'];
    date_from?: string;
    date_to?: string;
    limit?: number;
    offset?: number;
  }
): Promise<WorkflowExecutionSummary[]> {
  return apiClient.get<WorkflowExecutionSummary[]>(
    `/tenants/${tenantId}/orchestrator/executions`,
    { params }
  );
}

/**
 * Get a single workflow execution by ID with full details
 */
export async function getWorkflowExecution(
  tenantId: string,
  executionId: string
): Promise<WorkflowExecutionDetail> {
  return apiClient.get<WorkflowExecutionDetail>(
    `/tenants/${tenantId}/orchestrator/executions/${executionId}`
  );
}

/**
 * Get latest workflow execution
 */
export async function getLatestWorkflowExecution(
  tenantId: string
): Promise<WorkflowExecutionDetail | null> {
  const executions = await listWorkflowExecutions(tenantId, {
    limit: 1
  });

  if (executions.length === 0) {
    return null;
  }

  return getWorkflowExecution(tenantId, executions[0].id);
}

/**
 * Cancel a running workflow execution
 */
export async function cancelWorkflowExecution(
  tenantId: string,
  executionId: string
): Promise<{ message: string }> {
  return apiClient.post<{ message: string }>(
    `/tenants/${tenantId}/orchestrator/executions/${executionId}/cancel`,
    {}
  );
}

/**
 * Retry a failed workflow execution
 */
export async function retryWorkflowExecution(
  tenantId: string,
  executionId: string
): Promise<OrchestratorWorkflowResponse> {
  return apiClient.post<OrchestratorWorkflowResponse>(
    `/tenants/${tenantId}/orchestrator/executions/${executionId}/retry`,
    {}
  );
}

// ============================================================================
// ORCHESTRATOR STATUS & HEALTH
// ============================================================================

/**
 * Get orchestrator service status
 */
export async function getOrchestratorStatus(
  tenantId: string
): Promise<OrchestratorStatus> {
  return apiClient.get<OrchestratorStatus>(
    `/tenants/${tenantId}/orchestrator/status`
  );
}

/**
 * Get timestamp of last orchestration run
 */
export async function getLastOrchestrationRun(
  tenantId: string
): Promise<{ timestamp: string | null; runNumber: number | null }> {
  return apiClient.get<{ timestamp: string | null; runNumber: number | null }>(
    `/tenants/${tenantId}/orchestrator/last-run`
  );
}

// ============================================================================
// ORCHESTRATOR CONFIGURATION
// ============================================================================

/**
 * Get orchestrator configuration for tenant
 */
export async function getOrchestratorConfig(
  tenantId: string
): Promise<OrchestratorConfig> {
  return apiClient.get<OrchestratorConfig>(
    `/tenants/${tenantId}/orchestrator/config`
  );
}

/**
 * Update orchestrator configuration
 */
export async function updateOrchestratorConfig(
  tenantId: string,
  config: Partial<OrchestratorConfig>
): Promise<OrchestratorConfig> {
  return apiClient.put<OrchestratorConfig>(
    `/tenants/${tenantId}/orchestrator/config`,
    config
  );
}

// ============================================================================
// HELPER FUNCTIONS
// ============================================================================

/**
 * Format workflow duration for display
 */
export function formatWorkflowDuration(durationMs: number): string {
  if (durationMs < 1000) {
    return `${durationMs}ms`;
  } else if (durationMs < 60000) {
    return `${(durationMs / 1000).toFixed(1)}s`;
  } else {
    const minutes = Math.floor(durationMs / 60000);
    const seconds = Math.floor((durationMs % 60000) / 1000);
    return `${minutes}m ${seconds}s`;
  }
}

/**
 * Get workflow step status icon
 */
export function getWorkflowStepStatusIcon(status: WorkflowStepResult['status']): string {
  switch (status) {
    case 'success': return '✅';
    case 'failed': return '❌';
    case 'skipped': return '⏭️';
    default: return '❓';
  }
}

/**
 * Get workflow overall status color
 */
export function getWorkflowStatusColor(status: WorkflowExecutionSummary['status']): string {
  switch (status) {
    case 'completed': return 'green';
    case 'running': return 'blue';
    case 'failed': return 'red';
    case 'cancelled': return 'gray';
    default: return 'gray';
  }
}
