import { StateMachine } from 'xstate';

// 数据状态定义
export type DataState = 'raw' | 'validating' | 'valid' | 'invalid' | 'processing' | 'processed' | 'error';

// 数据状态事件
export type DataEvent = 
  | { type: 'VALIDATE' }
  | { type: 'VALID' }
  | { type: 'INVALID' }
  | { type: 'PROCESS' }
  | { type: 'PROCESS_SUCCESS' }
  | { type: 'PROCESS_ERROR' }
  | { type: 'RETRY' };

// 数据状态上下文
export interface DataContext {
  dataId: string;
  tenantId: string;
  shopId: string;
  taskId: string;
  traceId: string;
  businessType: 'TOC' | 'TOB';
  lastUpdated: string;
  updatedBy: string;
  dataType: string;
  source: string;
}

// 数据状态机
export const dataStateMachine = StateMachine<DataContext, DataState, DataEvent>({
  id: 'data',
  initial: 'raw',
  states: {
    raw: {
      on: {
        VALIDATE: 'validating'
      }
    },
    validating: {
      on: {
        VALID: 'valid',
        INVALID: 'invalid'
      }
    },
    valid: {
      on: {
        PROCESS: 'processing'
      }
    },
    invalid: {
      on: {
        VALIDATE: 'validating'
      }
    },
    processing: {
      on: {
        PROCESS_SUCCESS: 'processed',
        PROCESS_ERROR: 'error'
      }
    },
    processed: {
      type: 'final'
    },
    error: {
      on: {
        RETRY: 'processing'
      }
    }
  }
});

// 状态变更服务
export class DataStateMachineService {
  private static instance: DataStateMachineService;

  static getInstance(): DataStateMachineService {
    if (!DataStateMachineService.instance) {
      DataStateMachineService.instance = new DataStateMachineService();
    }
    return DataStateMachineService.instance;
  }

  async transition(
    currentState: DataState,
    event: DataEvent,
    context: DataContext
  ): Promise<{
    newState: DataState;
    context: DataContext;
  }> {
    const state = dataStateMachine.transition(currentState, event);
    
    // 更新上下文
    const updatedContext = {
      ...context,
      lastUpdated: new Date().toISOString(),
    };

    // 记录状态变更日志
    this.logStateChange(updatedContext, currentState, state.value);

    return {
      newState: state.value,
      context: updatedContext
    };
  }

  private logStateChange(
    context: DataContext,
    fromState: DataState,
    toState: DataState
  ): void {
    console.log(`[DataStateMachine] Data ${context.dataId} transitioned from ${fromState} to ${toState}`, {
      ...context,
      fromState,
      toState,
      timestamp: new Date().toISOString()
    });
  }

  // 验证状态变更是否有效
  isValidTransition(fromState: DataState, event: DataEvent): boolean {
    const state = dataStateMachine.transition(fromState, event);
    return state.value !== fromState || state.matches(fromState);
  }

  // 获取当前状态下可执行的事件
  getAvailableEvents(state: DataState): DataEvent['type'][] {
    const stateNode = dataStateMachine.getStateNode(state);
    return Object.keys(stateNode.on || {});
  }
}
