import { ChatEventType } from "@coze/api";

/** 文件解析状态枚举 */
export type FileParseStatus = -1 | 0 | 1 | 2;

/** 状态接口 */
export interface IFileParseState {
  status: FileParseStatus;
  handleEvent(eventType: string, event: any): void;
}

/**
 * 文件解析器：状态模式 + 回调（观察者）
 */
export class FileParser {
  private state: IFileParseState|null=null;

  constructor(
    /** 状态变更时回调，更新 UI 或者其他逻辑 */
    private onStatusChange: (newStatus: FileParseStatus) => void
  ) {
    this.transitionTo(new UninitializedState(this));
  }

  get status() {
    return this.state?.status;
  }

  /** 外部事件统一入口，交由当前状态去处理 */
  handleEvent(eventType: string, event: any) {
    this.state?.handleEvent(eventType, event);
  }

  /** 切换状态并触发回调 */
  transitionTo(state: IFileParseState) {
    this.state = state;
    this.onStatusChange(state.status);
  }
}

/** 初始状态：-1，等待 bot.join 且带 fileInfo */
class UninitializedState implements IFileParseState {
  status: FileParseStatus = -1;
  constructor(private ctx: FileParser) {}

  handleEvent(eventType: string, event: any) {
    if (eventType === "server.bot.join" && event.fileInfo) {
      this.ctx.transitionTo(new WaitingState(this.ctx));
    }
  }
}

/** 等待发送解析请求：0 */
class WaitingState implements IFileParseState {
  status: FileParseStatus = 0;
  constructor(private ctx: FileParser) {}

  handleEvent(_eventType: string, event: any) {
    if (
      event.event_type === ChatEventType.CONVERSATION_MESSAGE_DELTA &&
      event.data.type === "function_call" &&
      JSON.parse(event.data.content).name === "doc_reader-PDF_reader"
    ) {
      this.ctx.transitionTo(new ParsingState(this.ctx));
    }
  }
}

/** 正在调用插件解析：1 */
class ParsingState implements IFileParseState {
  status: FileParseStatus = 1;
  constructor(private ctx: FileParser) {}

  handleEvent(_eventType: string, event: any) {
    if (
      event.event_type === ChatEventType.CONVERSATION_MESSAGE_COMPLETED &&
      event.data.type === "tool_response"
    ) {
      this.ctx.transitionTo(new CompletedState());
    }
  }
}

/** 解析完成：2 */
class CompletedState implements IFileParseState {
  status: FileParseStatus = 2;
  constructor() {}

  handleEvent(_eventType: string, _event: any) {
    // 如需重置或其他后续逻辑，可在此处理
  }
}

