// @ts-nocheck
import { debugLog } from './common';

const normalizeTrackingMode = (value: any): 'workspace_and_conversation' | 'conversation_only' => {
  return String(value || '').toLowerCase() === 'conversation_only'
    ? 'conversation_only'
    : 'workspace_and_conversation';
};

export const versioningMethods = {
  async fetchVersioningStatus(conversationId = null, options = {}) {
    const targetId = conversationId || this.currentConversationId;
    const { silent = false } = options as { silent?: boolean };
    if (!targetId) return null;
    try {
      const resp = await fetch(`/api/conversations/${targetId}/versioning`);
      const data = await resp.json().catch(() => ({}));
      if (!resp.ok || !data?.success) {
        if (!silent) {
          throw new Error(data?.error || '获取版本状态失败');
        }
        return null;
      }
      const payload = data.data || {};
      this.versioningHostMode = !!payload.host_mode;
      this.versioningEnabled = !!payload.enabled;
      const resolvedTrackingMode = normalizeTrackingMode(payload.tracking_mode);
      this.versioningTrackingMode = !this.versioningHostMode &&
        resolvedTrackingMode !== 'conversation_only'
        ? 'conversation_only'
        : resolvedTrackingMode;
      if (!this.versioningHostMode) {
        this.newConversationVersioningTrackingMode = 'conversation_only';
      }
      this.versioningMode = 'overwrite';
      this.versioningRestoreMode = 'overwrite';
      this.versioningMismatch = !!payload.mismatch;
      this.versioningWorkspaceMatched = payload.workspace_matched !== false;
      return payload;
    } catch (error) {
      if (!silent) {
        this.uiPushToast({
          title: '版本管理',
          message: error?.message || '获取版本状态失败',
          type: 'error'
        });
      }
      return null;
    }
  },

  async fetchVersioningCheckpoints(conversationId = null) {
    const targetId = conversationId || this.currentConversationId;
    if (!targetId) return [];
    this.versioningLoading = true;
    try {
      const resp = await fetch(`/api/conversations/${targetId}/versioning/checkpoints`);
      const data = await resp.json().catch(() => ({}));
      if (!resp.ok || !data?.success) {
        throw new Error(data?.error || '加载版本点失败');
      }
      if (data?.data?.tracking_mode) {
        this.versioningTrackingMode = normalizeTrackingMode(data.data.tracking_mode);
      }
      const items = Array.isArray(data?.data?.items) ? data.data.items : [];
      this.versioningCheckpoints = items;
      if (!items.length) {
        this.versioningSelectedSeq = null;
        this.versioningSelectedDetail = null;
      }
      return items;
    } catch (error) {
      this.uiPushToast({
        title: '版本管理',
        message: error?.message || '加载版本点失败',
        type: 'error'
      });
      return [];
    } finally {
      this.versioningLoading = false;
    }
  },

  async openVersioningDialog() {
    if (!this.currentConversationId) {
      this.versioningEnabled = !!this.newConversationVersioningEnabled;
      this.versioningTrackingMode = normalizeTrackingMode(
        this.newConversationVersioningTrackingMode
      );
      if (!this.versioningHostMode && this.versioningTrackingMode !== 'conversation_only') {
        this.versioningTrackingMode = 'conversation_only';
      }
      this.versioningWorkspaceMatched = true;
      this.versioningCheckpoints = [];
      this.versioningSelectedSeq = null;
      this.versioningSelectedDetail = null;
      this.versioningDialogOpen = true;
      return;
    }
    await this.fetchVersioningStatus(this.currentConversationId);
    this.versioningRestoreMode = 'overwrite';
    this.versioningDialogOpen = true;
    this.versioningSelectedSeq = null;
    this.versioningSelectedDetail = null;
    await this.fetchVersioningCheckpoints(this.currentConversationId);
  },

  async refreshVersioningDialog() {
    await this.fetchVersioningStatus(this.currentConversationId);
    await this.fetchVersioningCheckpoints(this.currentConversationId);
  },

  async handleVersioningTrackingModeChange(mode: string) {
    await this.updateVersioningTrackingMode(mode);
  },

  async toggleConversationVersioning(enabled: boolean) {
    if (!this.currentConversationId) {
      this.newConversationVersioningEnabled = !!enabled;
      this.versioningEnabled = !!enabled;
      if (enabled) {
        if (!this.versioningHostMode) {
          this.versioningTrackingMode = 'conversation_only';
        }
        this.newConversationVersioningTrackingMode = normalizeTrackingMode(
          this.versioningTrackingMode
        );
      }
      this.uiPushToast({
        title: '版本管理',
        message: enabled ? '已为下一次新对话开启版本管理' : '已取消下一次新对话的版本管理',
        type: 'success'
      });
      return;
    }
    this.versioningLoading = true;
    try {
      let trackingMode = normalizeTrackingMode(this.versioningTrackingMode);
      if (!this.versioningHostMode && trackingMode !== 'conversation_only') {
        trackingMode = 'conversation_only';
        this.versioningTrackingMode = trackingMode;
      }
      const resp = await fetch(`/api/conversations/${this.currentConversationId}/versioning`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          enabled: !!enabled,
          mode: 'overwrite',
          tracking_mode: trackingMode
        })
      });
      const data = await resp.json().catch(() => ({}));
      if (!resp.ok || !data?.success) {
        throw new Error(data?.error || '切换版本管理失败');
      }
      this.versioningEnabled = !!data?.data?.enabled;
      this.versioningTrackingMode = normalizeTrackingMode(
        data?.data?.tracking_mode || this.versioningTrackingMode
      );
      this.versioningMode = 'overwrite';
      this.versioningRestoreMode = 'overwrite';
      this.uiPushToast({
        title: '版本管理',
        message: this.versioningEnabled ? '已开启' : '已关闭',
        type: 'success'
      });
      if (this.versioningEnabled) {
        await this.fetchVersioningCheckpoints(this.currentConversationId);
      } else {
        this.versioningCheckpoints = [];
        this.versioningSelectedSeq = null;
        this.versioningSelectedDetail = null;
      }
    } catch (error) {
      this.uiPushToast({
        title: '版本管理',
        message: error?.message || '切换失败',
        type: 'error'
      });
    } finally {
      this.versioningLoading = false;
    }
  },

  async selectVersioningCheckpoint(seq: number) {
    if (!this.currentConversationId || seq === null || seq === undefined) return;
    this.versioningSelectedSeq = Number(seq);
    this.versioningDetailLoading = true;
    try {
      const resp = await fetch(
        `/api/conversations/${this.currentConversationId}/versioning/checkpoints/${encodeURIComponent(String(seq))}`
      );
      const data = await resp.json().catch(() => ({}));
      if (!resp.ok || !data?.success) {
        throw new Error(data?.error || '加载详情失败');
      }
      this.versioningSelectedDetail = data.data || null;
    } catch (error) {
      this.uiPushToast({
        title: '版本管理',
        message: error?.message || '加载详情失败',
        type: 'error'
      });
    } finally {
      this.versioningDetailLoading = false;
    }
  },

  async confirmVersioningRestore() {
    if (
      !this.currentConversationId ||
      this.versioningSelectedSeq === null ||
      this.versioningSelectedSeq === undefined
    ) return;
    const confirmed = await this.confirmAction({
      title: '确认回溯',
      message: `将回溯到输入 #${this.versioningSelectedSeq} 对应的状态，是否继续？`,
      confirmText: '回溯',
      cancelText: '取消'
    });
    if (!confirmed) return;
    this.versioningRestoring = true;
    try {
      const resp = await fetch(`/api/conversations/${this.currentConversationId}/versioning/restore`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          seq: this.versioningSelectedSeq,
          mode: 'overwrite'
        })
      });
      const data = await resp.json().catch(() => ({}));
      if (!resp.ok || !data?.success) {
        throw new Error(data?.error || '回溯失败');
      }
      const targetConversationId = data?.data?.conversation_id || this.currentConversationId;
      this.versioningDialogOpen = false;
      await this.loadConversation(targetConversationId, { force: true });
      this.uiPushToast({
        title: '版本管理',
        message: '回溯完成',
        type: 'success'
      });
    } catch (error) {
      this.uiPushToast({
        title: '版本管理',
        message: error?.message || '回溯失败',
        type: 'error'
      });
    } finally {
      this.versioningRestoring = false;
    }
  },

  async maybePromptVersioningMismatch(versioningPayload: any) {
    if (!versioningPayload || !versioningPayload.enabled || !versioningPayload.mismatch) {
      return;
    }
    const latestSeq = versioningPayload.latest_seq;
    if (!latestSeq) return;
    const confirmed = await this.confirmAction({
      title: '版本状态不一致',
      message: '当前工作区与该对话最新版本不一致，是否恢复到最新一次提交？',
      confirmText: '恢复',
      cancelText: '保持当前',
      warningText: '警告：恢复操作会导致当前工作区内容被重置为当前对话的最新一次提交备份。',
      closeOnBackdrop: false,
      confirmVariant: 'danger',
      confirmOnLeft: true
    });
    if (!confirmed) return;
    try {
      const resp = await fetch(`/api/conversations/${this.currentConversationId}/versioning/restore`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          seq: latestSeq,
          mode: 'overwrite'
        })
      });
      const data = await resp.json().catch(() => ({}));
      if (!resp.ok || !data?.success) {
        throw new Error(data?.error || '恢复失败');
      }
      await this.loadConversation(this.currentConversationId, { force: true });
      this.uiPushToast({
        title: '版本管理',
        message: '已恢复到最新版本提交',
        type: 'success'
      });
    } catch (error) {
      debugLog('[Versioning] mismatch restore failed', error);
      this.uiPushToast({
        title: '版本管理',
        message: error?.message || '恢复失败',
        type: 'error'
      });
    }
  },
  async applyPendingVersioningToConversation(conversationId: string) {
    const targetId = conversationId || this.currentConversationId;
    if (!targetId) return;
    if (!this.newConversationVersioningEnabled) return;
    try {
      const trackingMode = normalizeTrackingMode(
        !this.versioningHostMode
          ? 'conversation_only'
          : (this.newConversationVersioningTrackingMode || this.versioningTrackingMode)
      );
      const resp = await fetch(`/api/conversations/${targetId}/versioning`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          enabled: true,
          mode: 'overwrite',
          tracking_mode: trackingMode
        })
      });
      const data = await resp.json().catch(() => ({}));
      if (!resp.ok || !data?.success) {
        throw new Error(data?.error || '新对话开启版本管理失败');
      }
      this.newConversationVersioningEnabled = false;
      this.versioningEnabled = true;
      this.versioningTrackingMode = normalizeTrackingMode(
        data?.data?.tracking_mode || trackingMode
      );
    } catch (error) {
      this.uiPushToast({
        title: '版本管理',
        message: error?.message || '新对话开启版本管理失败',
        type: 'error'
      });
    }
  },

  async updateVersioningTrackingMode(mode: string) {
    const normalizedMode = normalizeTrackingMode(mode);
    if (!this.versioningHostMode && normalizedMode === 'workspace_and_conversation') {
      this.uiPushToast({
        title: '版本管理',
        message: '当前模式仅支持“仅管理对话”',
        type: 'warning'
      });
      this.versioningTrackingMode = 'conversation_only';
      this.newConversationVersioningTrackingMode = 'conversation_only';
      return false;
    }
    this.versioningTrackingMode = normalizedMode;
    if (!this.currentConversationId) {
      this.newConversationVersioningTrackingMode = normalizedMode;
      return true;
    }
    if (!this.versioningEnabled) {
      return true;
    }
    this.versioningLoading = true;
    try {
      const resp = await fetch(`/api/conversations/${this.currentConversationId}/versioning`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          enabled: true,
          mode: 'overwrite',
          tracking_mode: normalizedMode
        })
      });
      const data = await resp.json().catch(() => ({}));
      if (!resp.ok || !data?.success) {
        throw new Error(data?.error || '更新版本管理范围失败');
      }
      this.versioningTrackingMode = normalizeTrackingMode(
        data?.data?.tracking_mode || normalizedMode
      );
      this.uiPushToast({
        title: '版本管理',
        message:
          this.versioningTrackingMode === 'conversation_only'
            ? '已切换为仅管理对话'
            : '已切换为管理工作区和对话',
        type: 'success'
      });
      return true;
    } catch (error) {
      this.uiPushToast({
        title: '版本管理',
        message: error?.message || '更新版本管理范围失败',
        type: 'error'
      });
      return false;
    } finally {
      this.versioningLoading = false;
    }
  }
};
