"use strict";
// =============================================================================
// Pure Agent - Audio Analyze Tool
// Ported from server.js audio_analyze implementation
// =============================================================================
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 });
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const tool_registry_1 = require("../tool-registry");
const result_types_1 = require("../result-types");
const utils_1 = require("../utils");
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const AUDIO_EXTENSIONS = new Set(['.mp3', '.wav', '.m4a', '.ogg', '.flac', '.aac', '.wma', '.opus']);
const MAX_AUDIO_BYTES = 25 * 1024 * 1024;
// ---------------------------------------------------------------------------
// Handler
// ---------------------------------------------------------------------------
async function audioAnalyzeHandler(args, context) {
    const { path: filepath, task = 'transcribe' } = args;
    if (!filepath)
        return (0, result_types_1.toolError)('Missing required parameter: path');
    const resolved = (0, utils_1.resolvePath)(filepath, context.workingDir);
    if (!fs.existsSync(resolved)) {
        return (0, result_types_1.toolError)(`File not found: ${resolved}`);
    }
    const stat = fs.statSync(resolved);
    if (stat.size > MAX_AUDIO_BYTES) {
        return (0, result_types_1.toolError)(`Audio file too large: ${stat.size} bytes (max ${MAX_AUDIO_BYTES})`);
    }
    const ext = path.extname(resolved).toLowerCase();
    const baseName = path.basename(resolved);
    if (task === 'analyze') {
        // Return metadata only
        return (0, result_types_1.toolResult)({
            success: true,
            file: baseName,
            size: stat.size,
            size_human: `${Math.round(stat.size / 1024)} KB`,
            format: ext.replace('.', ''),
            modified: stat.mtime.toISOString(),
            hint: 'For detailed audio analysis, use execute_code with librosa or similar library.',
        });
    }
    // Transcribe mode - load audio as multimodal content for the model
    // The model can then transcribe or analyze it
    try {
        const data = fs.readFileSync(resolved);
        const mimeMap = {
            '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.m4a': 'audio/mp4',
            '.ogg': 'audio/ogg', '.flac': 'audio/flac', '.aac': 'audio/aac',
        };
        const mime = mimeMap[ext] || 'audio/mpeg';
        const format = ext.replace('.', '');
        return JSON.stringify({
            _multimodal: true,
            content: [
                { type: 'text', text: `Audio file loaded for transcription: ${baseName}\nPlease transcribe or analyze this audio.` },
                { type: 'input_audio', input_audio: { data: data.toString('base64'), format } },
            ],
            text_summary: `Audio loaded: ${baseName} (${Math.round(stat.size / 1024)} KB) for transcription`,
        });
    }
    catch (err) {
        return (0, result_types_1.toolError)(`Failed to load audio: ${err.message}`);
    }
}
// ---------------------------------------------------------------------------
// Registration
// ---------------------------------------------------------------------------
tool_registry_1.registry.register({
    name: 'audio_analyze',
    toolset: 'vision',
    schema: {
        description: 'Analyze or transcribe an audio file. The audio is loaded into the model context for direct analysis.',
        parameters: {
            type: 'object',
            properties: {
                path: {
                    type: 'string',
                    description: 'Path to the audio file',
                },
                task: {
                    type: 'string',
                    enum: ['transcribe', 'analyze'],
                    description: 'Task type: "transcribe" loads audio for transcription, "analyze" returns metadata only. Default: transcribe',
                    default: 'transcribe',
                },
            },
            required: ['path'],
        },
    },
    handler: audioAnalyzeHandler,
    isAsync: true,
    description: 'Analyze/transcribe audio',
    emoji: '🎤',
});
//# sourceMappingURL=audio-analyze.js.map