"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateAiToolsService = generateAiToolsService;
const Generator = __importStar(require("@postxl/generator"));
function generateAiToolsService({ context }) {
    const imports = Generator.ImportGenerator.from(Generator.toFilePath('./ai-tools.service.ts')).addImport({
        from: context.types.location,
        items: [Generator.toTypeName('ToolDefinition')],
    });
    return /* ts */ `
import { Injectable } from '@nestjs/common'

${imports.generate()}

import type { OpenAITool } from './model-provider/model-provider.interface'

export type BackendToolContext = {
  actorKey: string
}

export type BackendToolExecutionLog = {
  toolKey: string
  text: string
  status: 'done' | 'error'
}

export type BackendTool = {
  definition: ToolDefinition
  execute: (
    input: Record<string, unknown>,
    context: BackendToolContext,
  ) => Record<string, unknown> | undefined | Promise<Record<string, unknown> | undefined>
}

@Injectable()
export class AiToolsService {
  private readonly backendTools = this.createBackendTools()
  private readonly backendToolByKey = new Map<string, BackendTool>()

  constructor() {
    for (const tool of this.backendTools) {
      const existing = this.backendToolByKey.get(tool.definition.key)
      if (existing) {
        throw new Error('Duplicate backend AI tool key: ' + tool.definition.key)
      }

      this.backendToolByKey.set(tool.definition.key, {
        ...tool,
        definition: {
          ...tool.definition,
          target: 'backend',
        },
      })
    }
  }

  public normalizeFrontendTools(tools: ToolDefinition[]): ToolDefinition[] {
    const seen = new Set<string>()
    const normalized: ToolDefinition[] = []

    for (const tool of tools) {
      if (!this.isValidToolName(tool.key)) {
        throw new Error('Invalid tool key: ' + tool.key)
      }
      if (typeof tool.label !== 'string' || tool.label.trim().length === 0) {
        throw new Error('Invalid tool label for key: ' + tool.key)
      }
      if (tool.key === 'done') {
        continue
      }

      if (seen.has(tool.key)) {
        continue
      }

      seen.add(tool.key)
      normalized.push({
        ...tool,
        target: 'frontend',
      })
    }

    return normalized
  }

  public assertNoToolKeyCollision(frontendTools: ToolDefinition[]) {
    for (const tool of frontendTools) {
      if (this.backendToolByKey.has(tool.key)) {
        throw new Error('Tool key collision between frontend and backend tools: ' + tool.key)
      }
    }
  }

  public getBackendTool(toolKey: string): BackendTool | undefined {
    return this.backendToolByKey.get(toolKey)
  }

  public buildTools(frontendTools: ToolDefinition[]): OpenAITool[] {
    const doneTool: OpenAITool = {
      type: 'function',
      function: {
        name: 'done',
        description: 'Finish the task and optionally provide a summary',
        parameters: {
          type: 'object',
          properties: {
            summary: { type: 'string' },
          },
        },
      },
    }

    const frontendToolDefinitions = frontendTools.map((tool) => ({
      ...tool,
      target: 'frontend' as const,
    }))

    const toolDefinitions = [...frontendToolDefinitions, ...this.backendTools.map((tool) => tool.definition)]

    const actionTools = toolDefinitions.map((tool) => ({
      type: 'function' as const,
      function: {
        name: tool.key,
        description: tool.label,
        parameters:
          tool.inputSchema ??
          (tool.kind === 'input'
            ? {
                type: 'object',
                properties: {
                  query: { type: 'string' },
                },
                required: ['query'],
              }
            : {
                type: 'object',
                properties: {},
              }),
      },
    }))

    return [doneTool, ...actionTools]
  }

  private isValidToolName(name: string): boolean {
    return /^[a-z][a-z0-9-]{1,127}$/.test(name)
  }

  private createBackendTools(): BackendTool[] {
    const tools: BackendTool[] = [
      {
        definition: {
          key: 'backend-get-current-time',
          kind: 'command',
          label: 'Get current server time',
          target: 'backend',
        },
        execute: () => ({
          now: new Date().toISOString(),
        }),
      },
      {
        definition: {
          key: 'backend-get-current-user',
          kind: 'command',
          label: 'Get current user identifier',
          target: 'backend',
        },
        execute: (_input, context) => ({
          actorKey: context.actorKey,
        }),
      },
    ]

    // @custom-start:backendAiTools
    // @custom-end:backendAiTools

    return tools.map((tool) => ({
      ...tool,
      definition: {
        ...tool.definition,
        target: 'backend',
      },
    }))
  }
}
`;
}
//# sourceMappingURL=ai-tools-service.generator.js.map