import { Provide, Inject, Post, Body, Controller } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { NetaClawSessionService } from '../gateway/session.js';
import { estimateHistoryTokens } from '../runtime/token_utils.js';

@Provide()
@Controller('/open/netaclaw/session')
export class NetaClawSessionController {
  @Inject()
  ctx: Context;

  @Inject()
  sessionService: NetaClawSessionService;

  @Post('/list')
  async list(@Body() body: { userId?: string; agentId?: number }) {
    return { code: 1000, data: await this.sessionService.listSessions(body.userId, body.agentId) };
  }

  @Post('/tree/list')
  async treeList(@Body() body: { agentId?: number }) {
    return { code: 1000, data: await this.sessionService.listSessionTreeSessions(body.agentId) };
  }

  @Post('/tree/snapshot')
  async treeSnapshot(@Body() body: { sessionId: string; agentId?: number }) {
    return { code: 1000, data: await this.sessionService.getSessionTreeSnapshot(body.sessionId, body.agentId) };
  }

  @Post('/messages')
  async messages(@Body() body: { sessionId: string; view?: 'compacted' | 'full' }) {
    return { code: 1000, data: await this.sessionService.getMessages(body.sessionId, body.view) };
  }

  @Post('/contextTokens')
  async contextTokens(@Body() body: { sessionId: string }) {
    const history = await this.sessionService.loadHistory(body.sessionId);
    return { code: 1000, data: { tokens: estimateHistoryTokens(history) } };
  }

  @Post('/delete')
  async delete(@Body() body: { sessionId: string; agentId?: number }) {
    await this.sessionService.deleteSession(body.sessionId, body.agentId);
    return { code: 1000, message: 'success' };
  }

  @Post('/deleteAll')
  async deleteAll(@Body() body: { userId?: string }) {
    await this.sessionService.deleteAllSessions(body.userId);
    return { code: 1000, message: 'success' };
  }
}
