import type { ModelMessage } from 'ai';
import type { SessionData, Todo, SessionSummary, ProjectMetadata } from './types.js';
import { SessionStorage, sessionStorage } from './storage.js';

/**
 * 会话管理器
 * 提供高级会话操作接口
 */
export class SessionManager {
  private storage: SessionStorage;
  private currentSession: SessionData | null = null;
  private currentProject: ProjectMetadata | null = null;
  private autoSaveInterval: ReturnType<typeof setInterval> | null = null;
  private lastSyncedCount: number = 0;

  constructor(storage?: SessionStorage) {
    this.storage = storage || sessionStorage;
  }

  /**
   * 初始化 - 尝试恢复或创建新会话
   */
  async init(workdir: string): Promise<SessionData> {
    // 获取或创建项目
    this.currentProject = await this.storage.getOrCreateProject(workdir);

    // 尝试加载当前会话
    const currentSessionId = await this.storage.getCurrentSessionId();

    if (currentSessionId) {
      // 尝试加载会话
      const existing = await this.storage.loadSession(this.currentProject.id, currentSessionId);

      if (existing && existing.workdir === workdir) {
        // 同一工作目录，恢复会话
        this.currentSession = existing;
        this.lastSyncedCount = existing.messages.length;
        this.startAutoSave();
        return this.currentSession;
      }
    }

    // 创建新会话
    this.currentSession = this.createNewSession(workdir);
    this.lastSyncedCount = 0;
    await this.save();

    // 启动自动保存
    this.startAutoSave();

    return this.currentSession;
  }

  /**
   * 创建新会话
   */
  private createNewSession(workdir: string): SessionData {
    if (!this.currentProject) {
      throw new Error('Project not initialized. Call init() first.');
    }

    return {
      id: this.storage.generateSessionId(),
      projectId: this.currentProject.id,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      workdir,
      messages: [],
      discoveredTools: [],
      todos: [],
    };
  }

  /**
   * 获取当前会话
   */
  getSession(): SessionData | null {
    return this.currentSession;
  }

  /**
   * 获取当前项目
   */
  getProject(): ProjectMetadata | null {
    return this.currentProject;
  }

  /**
   * 保存当前会话（增量保存消息）
   */
  async save(): Promise<void> {
    if (!this.currentSession) return;

    // 增量保存消息
    await this.storage.saveSession(this.currentSession, this.lastSyncedCount);

    // 更新当前会话指针
    await this.storage.setCurrentSession(this.currentSession.id);

    // 更新同步计数
    this.lastSyncedCount = this.currentSession.messages.length;
  }

  /**
   * 添加消息
   */
  async addMessage(message: ModelMessage): Promise<void> {
    if (!this.currentSession) return;
    this.currentSession.messages.push(message);
    await this.save();
  }

  /**
   * 批量设置消息（用于同步整个对话历史）
   */
  async setMessages(messages: ModelMessage[]): Promise<void> {
    if (!this.currentSession) return;
    this.currentSession.messages = messages;
    await this.save();
  }

  /**
   * 获取对话历史
   */
  getMessages(): ModelMessage[] {
    return this.currentSession?.messages || [];
  }

  /**
   * 设置已发现的工具
   */
  async setDiscoveredTools(tools: string[]): Promise<void> {
    if (!this.currentSession) return;
    this.currentSession.discoveredTools = tools;
    await this.save();
  }

  /**
   * 获取已发现的工具
   */
  getDiscoveredTools(): string[] {
    return this.currentSession?.discoveredTools || [];
  }

  /**
   * 更新待办事项
   */
  async setTodos(todos: Todo[]): Promise<void> {
    if (!this.currentSession) return;
    this.currentSession.todos = todos;
    await this.save();
  }

  /**
   * 获取待办事项
   */
  getTodos(): Todo[] {
    return this.currentSession?.todos || [];
  }

  /**
   * 清空当前会话并创建新会话
   */
  async newSession(workdir?: string): Promise<SessionData> {
    if (!this.currentProject) {
      throw new Error('Project not initialized. Call init() first.');
    }

    // 创建新会话
    const newWorkdir = workdir || this.currentSession?.workdir || process.cwd();

    // 如果工作目录变化，需要切换项目
    if (workdir && workdir !== this.currentProject.workdir) {
      this.currentProject = await this.storage.getOrCreateProject(workdir);
    }

    this.currentSession = this.createNewSession(newWorkdir);
    this.lastSyncedCount = 0;
    await this.save();

    return this.currentSession;
  }

  /**
   * 创建子会话（用于 Task 工具）
   * @param parentId 父会话 ID
   * @param agentName 关联的 Agent 名称
   * @param title 会话标题
   */
  createChildSession(parentId: string, agentName: string, title?: string): SessionData {
    if (!this.currentProject) {
      throw new Error('Project not initialized. Call init() first.');
    }

    const workdir = this.currentSession?.workdir || process.cwd();
    const childSession: SessionData = {
      id: this.storage.generateSessionId(),
      projectId: this.currentProject.id,
      parentId,
      agentName,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      workdir,
      title: title || `子任务 (@${agentName})`,
      messages: [],
      discoveredTools: [],
      todos: [],
    };
    return childSession;
  }

  /**
   * 保存子会话
   */
  async saveChildSession(session: SessionData): Promise<void> {
    await this.storage.saveSession(session, 0);
  }

  /**
   * 获取当前会话 ID
   */
  getSessionId(): string | undefined {
    return this.currentSession?.id;
  }

  /**
   * 恢复指定会话
   */
  async restoreSession(sessionId: string): Promise<SessionData | null> {
    if (!this.currentProject) {
      throw new Error('Project not initialized. Call init() first.');
    }

    const session = await this.storage.loadSession(this.currentProject.id, sessionId);
    if (!session) return null;

    this.currentSession = session;
    this.lastSyncedCount = session.messages.length;
    await this.storage.setCurrentSession(sessionId);

    return session;
  }

  /**
   * 列出当前项目的历史会话
   */
  async listSessions(): Promise<SessionSummary[]> {
    if (!this.currentProject) {
      return this.storage.listAllSessions();
    }
    return this.storage.listSessionsByProject(this.currentProject.id);
  }

  /**
   * 列出所有项目的会话
   */
  async listAllSessions(): Promise<SessionSummary[]> {
    return this.storage.listAllSessions();
  }

  /**
   * 删除历史会话
   */
  async deleteSession(sessionId: string): Promise<boolean> {
    if (!this.currentProject) {
      return false;
    }
    return this.storage.deleteSession(this.currentProject.id, sessionId);
  }

  /**
   * 启动自动保存（每 30 秒）
   */
  private startAutoSave(): void {
    if (this.autoSaveInterval) return;

    this.autoSaveInterval = setInterval(async () => {
      await this.save();
    }, 30000);
  }

  /**
   * 停止自动保存
   */
  stopAutoSave(): void {
    if (this.autoSaveInterval) {
      clearInterval(this.autoSaveInterval);
      this.autoSaveInterval = null;
    }
  }

  /**
   * 关闭管理器（保存并停止自动保存）
   */
  async close(): Promise<void> {
    this.stopAutoSave();
    await this.save();
  }

  /**
   * 清理旧会话
   */
  async cleanup(keepCount?: number): Promise<number> {
    return this.storage.cleanupOldSessions(keepCount);
  }
}

// 导出默认实例
export const sessionManager = new SessionManager();
