/**
 * Session Manager
 *
 * 管理所有活跃的会话元数据（不存储消息，消息由 Core 负责）
 */

import { v4 as uuidv4 } from 'uuid';
import type { Session, CreateSessionInput, SessionStatus } from '../types.js';

// ============================================================================
// Core 模块接口定义（避免构建时依赖）
// ============================================================================

interface SessionSummary {
  id: string;
  title: string;
  workdir: string;
  messageCount: number;
  createdAt: string;
  updatedAt: string;
}

interface ProjectMetadata {
  id: string;
  workdir: string;
  createdAt: string;
  isGitRepo: boolean;
}

interface SessionData {
  id: string;
  projectId: string;
  parentId?: string;
  agentName?: string;
  createdAt: string;
  updatedAt: string;
  workdir: string;
  title?: string;
  messages: Array<{ role: string; content: unknown }>;
  discoveredTools: string[];
  todos: unknown[];
}

interface SessionStorageInterface {
  ensureDir(): Promise<void>;
  generateSessionId(): string;
  getOrCreateProject(workdir: string): Promise<ProjectMetadata>;
  listAllSessions(): Promise<SessionSummary[]>;
  listSessionsByProject(projectId: string): Promise<SessionSummary[]>;
  loadSession(projectId: string, sessionId: string): Promise<SessionData | null>;
  saveSession(session: SessionData, lastSyncedCount?: number): Promise<void>;
  deleteSession(projectId: string, sessionId: string): Promise<boolean>;
}

// ============================================================================
// SessionManager 类
// ============================================================================

export class SessionManager {
  private sessions: Map<string, Session> = new Map();
  private sessionProjects: Map<string, string> = new Map(); // sessionId -> projectId
  private storage: SessionStorageInterface | null = null;
  private currentProject: ProjectMetadata | null = null;
  private initialized = false;

  /**
   * 获取 storage 实例（供外部使用）
   */
  getStorage(): SessionStorageInterface | null {
    return this.storage;
  }

  /**
   * 获取 session 所属的 projectId
   */
  getProjectId(sessionId: string): string {
    return this.sessionProjects.get(sessionId) || this.currentProject?.id || 'default';
  }

  /**
   * 初始化：加载 Core 模块的 SessionStorage 并恢复已有 sessions
   */
  async init(): Promise<void> {
    if (this.initialized) return;

    try {
      // 动态导入 Core 模块，避免构建时依赖
      const corePath = '@ai-assistant/core';
      const core = (await import(/* webpackIgnore: true */ corePath)) as {
        SessionStorage: new () => SessionStorageInterface;
      };

      this.storage = new core.SessionStorage();
      await this.storage.ensureDir();

      // 获取当前工作目录的项目
      this.currentProject = await this.storage.getOrCreateProject(process.cwd());

      // 加载已持久化的 sessions（所有项目）
      const summaries = await this.storage.listAllSessions();
      console.log(`[SessionManager] Found ${summaries.length} persisted sessions`);

      for (const summary of summaries) {
        // 需要找到 session 所属的项目，这里简化处理：加载当前项目的会话
        const sessionData = await this.storage.loadSession(this.currentProject.id, summary.id);
        if (!sessionData) continue;

        // 记录 session -> project 映射
        this.sessionProjects.set(sessionData.id, sessionData.projectId);

        // 转换为 Server Session 格式（只保存元数据，不存储消息）
        const session: Session = {
          id: sessionData.id,
          name: sessionData.title,
          workdir: sessionData.workdir,
          createdAt: sessionData.createdAt,
          updatedAt: sessionData.updatedAt,
          status: 'idle',
          messageCount: sessionData.messages.length,
        };

        this.sessions.set(session.id, session);
      }

      console.log(`[SessionManager] Loaded ${this.sessions.size} sessions from storage`);
    } catch (error) {
      console.warn('[SessionManager] Storage not available, using memory only:', error);
    }

    this.initialized = true;
  }

  /**
   * 持久化单个 session 的元数据
   * 注意：消息存储由 Core Agent 负责，这里只更新会话元数据
   */
  private async persistMetadata(sessionId: string): Promise<void> {
    if (!this.storage) return;

    const session = this.sessions.get(sessionId);
    if (!session) return;

    const projectId = this.sessionProjects.get(sessionId) || this.currentProject?.id || 'default';

    // 先加载现有的 session 数据（保留消息）
    const existingData = await this.storage.loadSession(projectId, sessionId);

    const sessionData: SessionData = {
      id: session.id,
      projectId,
      createdAt: session.createdAt,
      updatedAt: session.updatedAt,
      workdir: session.workdir,
      title: session.name,
      messages: existingData?.messages || [],
      discoveredTools: existingData?.discoveredTools || [],
      todos: existingData?.todos || [],
    };

    await this.storage.saveSession(sessionData);
  }

  /**
   * 创建新会话
   */
  async create(input: CreateSessionInput = {}): Promise<Session> {
    const now = new Date().toISOString();
    const workdir = input.workdir || process.cwd();

    // 如果指定了不同的工作目录，获取对应项目
    let projectId = this.currentProject?.id || 'default';
    if (this.storage && workdir !== this.currentProject?.workdir) {
      const project = await this.storage.getOrCreateProject(workdir);
      projectId = project.id;
    }

    const session: Session = {
      id: this.storage?.generateSessionId() || uuidv4(),
      name: input.name,
      workdir,
      createdAt: now,
      updatedAt: now,
      status: 'idle',
      messageCount: 0,
    };

    this.sessions.set(session.id, session);
    this.sessionProjects.set(session.id, projectId);

    // 持久化空会话
    await this.persistMetadata(session.id);

    return session;
  }

  /**
   * 获取所有会话
   */
  list(): Session[] {
    return Array.from(this.sessions.values()).sort(
      (a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
    );
  }

  /**
   * 获取单个会话
   */
  get(id: string): Session | undefined {
    return this.sessions.get(id);
  }

  /**
   * 删除会话
   */
  async delete(id: string): Promise<boolean> {
    const deleted = this.sessions.delete(id);

    // 从存储中删除
    if (deleted && this.storage) {
      const projectId = this.sessionProjects.get(id) || this.currentProject?.id || 'default';
      await this.storage.deleteSession(projectId, id);
      this.sessionProjects.delete(id);
    }

    return deleted;
  }

  /**
   * 更新会话状态
   */
  updateStatus(id: string, status: SessionStatus): Session | undefined {
    const session = this.sessions.get(id);
    if (!session) return undefined;

    session.status = status;
    session.updatedAt = new Date().toISOString();
    return session;
  }

  /**
   * 更新会话消息计数（由 Agent 调用）
   */
  updateMessageCount(id: string, count: number): Session | undefined {
    const session = this.sessions.get(id);
    if (!session) return undefined;

    session.messageCount = count;
    session.updatedAt = new Date().toISOString();
    return session;
  }

  /**
   * 更新会话名称/标题
   */
  async updateSessionName(sessionId: string, name: string): Promise<Session | undefined> {
    const session = this.sessions.get(sessionId);
    if (!session) return undefined;

    session.name = name;
    session.updatedAt = new Date().toISOString();

    // 持久化元数据
    await this.persistMetadata(sessionId);

    return session;
  }

  /**
   * 获取会话数量
   */
  count(): number {
    return this.sessions.size;
  }

  /**
   * 检查会话是否存在
   */
  exists(id: string): boolean {
    return this.sessions.has(id);
  }
}

// 单例
let instance: SessionManager | null = null;

export function getSessionManager(): SessionManager {
  if (!instance) {
    instance = new SessionManager();
  }
  return instance;
}
