/**
 * Sessions API Routes
 *
 * 会话管理相关的 REST API
 */

import { Hono } from 'hono';
import { getSessionManager } from '../session/manager.js';
import { CreateSessionInputSchema } from '../types.js';

export const sessionsRouter = new Hono();

const sessionManager = getSessionManager();

/**
 * GET /sessions - 列出所有会话
 */
sessionsRouter.get('/', (c) => {
  const sessions = sessionManager.list();
  return c.json({
    success: true,
    data: sessions,
  });
});

/**
 * POST /sessions - 创建新会话
 */
sessionsRouter.post('/', async (c) => {
  try {
    const body = await c.req.json();
    const input = CreateSessionInputSchema.parse(body);
    const session = await sessionManager.create(input);

    return c.json(
      {
        success: true,
        data: session,
      },
      201
    );
  } catch (error) {
    return c.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Invalid input',
      },
      400
    );
  }
});

/**
 * GET /sessions/:id - 获取单个会话
 */
sessionsRouter.get('/:id', (c) => {
  const id = c.req.param('id');
  const session = sessionManager.get(id);

  if (!session) {
    return c.json(
      {
        success: false,
        error: 'Session not found',
      },
      404
    );
  }

  return c.json({
    success: true,
    data: session,
  });
});

/**
 * DELETE /sessions/:id - 删除会话
 */
sessionsRouter.delete('/:id', async (c) => {
  const id = c.req.param('id');

  if (!sessionManager.exists(id)) {
    return c.json(
      {
        success: false,
        error: 'Session not found',
      },
      404
    );
  }

  await sessionManager.delete(id);

  return c.json({
    success: true,
    message: 'Session deleted',
  });
});

/**
 * GET /sessions/:id/messages - 获取会话消息
 *
 * 从 Core 存储读取完整的消息历史（包含 tool-call 和 tool-result）
 */
sessionsRouter.get('/:id/messages', async (c) => {
  const id = c.req.param('id');

  if (!sessionManager.exists(id)) {
    return c.json(
      {
        success: false,
        error: 'Session not found',
      },
      404
    );
  }

  // 从 Core 存储读取消息
  const sessionData = await sessionManager.loadSessionData(id);

  if (!sessionData) {
    return c.json({
      success: true,
      data: [],
    });
  }

  // 为消息添加 ID 并转换内容格式（AI SDK 格式 -> 字符串）
  const messagesWithId = sessionData.messages.map(
    (msg: { role: string; content: unknown }, index: number) => {
      // 转换 AI SDK 内容格式为字符串
      let content: string;
      if (typeof msg.content === 'string') {
        content = msg.content;
      } else if (Array.isArray(msg.content)) {
        // AI SDK 格式: [{type: "text", text: "..."}, ...]
        content = msg.content
          .filter((block: { type?: string }) => block.type === 'text')
          .map((block: { text?: string }) => block.text || '')
          .join('');
      } else {
        content = String(msg.content);
      }

      return {
        id: `${msg.role}-${id}-${index}`,
        role: msg.role,
        content,
        timestamp: new Date().toISOString(),
      };
    }
  );

  return c.json({
    success: true,
    data: messagesWithId,
  });
});
