/**
 * 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 SessionManagerInterface {
  init(workdir: string): Promise<SessionData>;
  getSession(): SessionData | null;
  getProject(): ProjectMetadata | null;
  listSessions(): Promise<SessionSummary[]>;
  listAllSessions(): Promise<SessionSummary[]>;
  deleteSession(sessionId: string): Promise<boolean>;
  newSession(workdir?: string): Promise<SessionData>;
  restoreSession(sessionId: string): Promise<SessionData | null>;
  getSessionId(): string | undefined;
}

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

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

  /**
   * 获取 Core SessionManager 实例（供外部使用）
   */
  getCoreManager(): SessionManagerInterface | null {
    return this.coreManager;
  }

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

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

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

      this.coreManager = new core.SessionManager();
      await this.coreManager.init(process.cwd());

      this.currentProject = this.coreManager.getProject();

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

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

        this.sessions.set(session.id, session);
        // 假设所有会话都属于当前项目（简化处理）
        if (this.currentProject) {
          this.sessionProjects.set(session.id, this.currentProject.id);
        }
      }

      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;
  }

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

    let sessionId: string;
    let projectId = this.currentProject?.id || 'default';

    if (this.coreManager) {
      // 使用 Core SessionManager 创建会话
      const sessionData = await this.coreManager.newSession(workdir);
      sessionId = sessionData.id;
      projectId = sessionData.projectId;
    } else {
      sessionId = uuidv4();
    }

    const session: Session = {
      id: sessionId,
      name: input.name,
      workdir,
      createdAt: now,
      updatedAt: now,
      status: 'idle',
      messageCount: 0,
    };

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

    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.coreManager) {
      await this.coreManager.deleteSession(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();

    return session;
  }

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

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

  /**
   * 加载会话数据（从 Core 存储）
   */
  async loadSessionData(sessionId: string): Promise<SessionData | null> {
    if (!this.coreManager) return null;

    // 先恢复会话
    const data = await this.coreManager.restoreSession(sessionId);
    return data;
  }
}

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

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