import { Body, Inject, Post, Provide } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { CrewOrchestratorService } from '../../service/crew_orchestrator.js';
import { escalateResolvers } from '../../tools/builtin/escalate.js';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { NetaClawCrewRunEntity } from '../../entity/crew_run.js';
import { NetaClawCrewTaskEntity } from '../../entity/crew_task.js';

@Provide()
@CoolController()
export class AdminCrewTriggerController extends BaseController {
  @Inject()
  orchestrator: CrewOrchestratorService;

  @InjectEntityModel(NetaClawCrewRunEntity)
  crewRunRepo: Repository<NetaClawCrewRunEntity>;

  @InjectEntityModel(NetaClawCrewTaskEntity)
  crewTaskRepo: Repository<NetaClawCrewTaskEntity>;

  @Post('/start')
  async start(@Body() body: { crewId: number; triggerInput?: string }) {
    const { crewId, triggerInput = '' } = body;
    const callbacks = this.createNoopCallbacks();
    const runId = await this.orchestrator.start(crewId, 'manual', triggerInput, callbacks);
    return this.ok({ runId });
  }

  @Post('/stop')
  async stop(@Body() body: { runId: number }) {
    await this.orchestrator.stop(body.runId);
    return this.ok();
  }

  @Post('/resume')
  async resume(@Body() body: { runId: number; userMessage: string }) {
    const { runId, userMessage } = body;
    const resolver = escalateResolvers.get(runId);
    if (resolver) {
      resolver(userMessage);
      escalateResolvers.delete(runId);
      await this.crewRunRepo.update(runId, { status: 'running' } as any);
      return this.ok();
    }
    const run = await this.crewRunRepo.findOne({ where: { id: runId } });
    if (run?.pausedState) {
      const history = JSON.parse(run.pausedState as string);
      const callbacks = this.createNoopCallbacks();
      await this.orchestrator.resumeFromPausedState(runId, history, userMessage, callbacks);
      return this.ok();
    }
    return this.fail('运行已过期或无暂停状态');
  }

  @Post('/runDetail')
  async runDetail(@Body() body: { runId: number }) {
    const run = await this.crewRunRepo.findOne({ where: { id: body.runId } });
    if (!run) return this.fail('运行记录不存在');
    const tasks = await this.crewTaskRepo.find({ where: { runId: body.runId }, order: { startTime: 'ASC' } });
    return this.ok({ ...run, tasks });
  }

  private createNoopCallbacks() {
    return {
      onLog: () => {},
      onTaskStatus: () => {},
      onRunStatus: () => {},
      onEscalation: () => {},
    };
  }
}
