import { Body, Controller, Get, Inject, Post, Provide, Query } from '@midwayjs/core';
import { NetaClawAgentService } from '../../service/agent.js';
import { NetaClawToolResolverService } from '../../service/tool_resolver.js';
import type { ModelCapability } from '../../entity/model_channel.js';
import { NetaClawToolRegistryService } from '../../service/tool_registry.js';

@Provide()
@Controller('/admin/netaclaw/tool')
export class NetaClawToolAdminController {
  @Inject()
  toolRegistry: NetaClawToolRegistryService;

  @Inject()
  toolResolver: NetaClawToolResolverService;

  @Inject()
  agentService: NetaClawAgentService;

  @Post('/page')
  async page(@Body() body: {
    page?: number;
    size?: number;
    keyWord?: string;
    toolset?: string;
    capability?: string;
    status?: number;
    requiresModel?: number;
  }) {
    return { code: 1000, data: await this.toolRegistry.page(body) };
  }

  @Get('/info')
  async info(@Query('id') id: number) {
    return { code: 1000, data: await this.toolRegistry.info(id) };
  }

  @Post('/update')
  async update(@Body() body: any) {
    await this.toolRegistry.update(body);
    return { code: 1000, message: 'success' };
  }

  @Get('/all')
  async all() {
    return { code: 1000, data: await this.toolRegistry.all() };
  }

  @Post('/sync')
  async sync() {
    return { code: 1000, data: await this.toolRegistry.syncCatalogToDb() };
  }

  @Get('/forAgent')
  async forAgent() {
    return { code: 1000, data: await this.toolRegistry.listForAgentConfig() };
  }

  @Post('/runtimeDiagnostic')
  async runtimeDiagnostic(@Body() body: {
    agentId?: number;
    capability?: ModelCapability;
    sessionCwd?: string;
    workspaceRoots?: string[];
    allowShell?: boolean;
    readonly?: boolean;
    draftToolOverride?: {
      name: string;
      enabled?: boolean;
      status?: number;
      promptHint?: string | null;
      allowInSubagent?: boolean;
      workerRoutingStrategy?: 'auto' | 'force-local' | 'force-main-process-proxy' | 'force-disabled';
    };
    draftAgentTools?: {
      inheritCoreTools?: boolean;
      enabled?: string[];
      disabled?: string[];
      perTool?: Record<string, {
        enabled?: boolean;
        promptHint?: string;
        allowInSubagent?: boolean;
        workerRoutingStrategy?: 'auto' | 'force-local' | 'force-main-process-proxy' | 'force-disabled';
      }>;
    };
  }) {
    const agent = body.agentId ? await this.agentService.info(body.agentId) : null;
    const data = await this.toolResolver.diagnoseRuntime({
      agent,
      modelCapability: body.capability ?? 'text',
      memoryEnabled: !!agent?.config?.memory?.enabled,
      hasSkills: !!agent?.skills?.length,
      sessionCwd: body.sessionCwd,
      workspaceRoots: body.workspaceRoots,
      allowShell: body.allowShell,
      readonly: body.readonly,
      draftToolOverride: body.draftToolOverride,
      draftAgentTools: body.draftAgentTools,
    });
    return { code: 1000, data };
  }
}
