"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.getDefaultMic = getDefaultMic;
exports.setDefaultMic = setDefaultMic;
exports.getMicCommand = getMicCommand;
exports.setMicCommand = setMicCommand;
exports.listMicrophones = listMicrophones;
exports.recordAudio = recordAudio;
exports.voiceToText = voiceToText;
const child_process_1 = require("child_process");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const utils_1 = require("./utils");
const conversion_1 = require("./conversion");
const CONFIG_DIR = ".knowhow/tools/microphone";
const CONFIG_FILE = "config.json";
const CONFIG_PATH = path.join(CONFIG_DIR, CONFIG_FILE);
function ensureConfigDirectoryExists() {
    if (!fs.existsSync(CONFIG_DIR)) {
        fs.mkdirSync(CONFIG_DIR, { recursive: true });
    }
}
function readMicrophoneConfig() {
    ensureConfigDirectoryExists();
    if (!fs.existsSync(CONFIG_PATH)) {
        const defaultConfig = { defaultMic: null };
        fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaultConfig, null, 2));
        return defaultConfig;
    }
    const configContent = fs.readFileSync(CONFIG_PATH, "utf-8");
    return JSON.parse(configContent);
}
function writeMicrophoneConfig(config) {
    ensureConfigDirectoryExists();
    fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));
}
function getDefaultMic() {
    const config = readMicrophoneConfig();
    return config.defaultMic;
}
function setDefaultMic(micName) {
    const config = readMicrophoneConfig();
    config.defaultMic = micName;
    writeMicrophoneConfig(config);
}
function getMicCommand() {
    const config = readMicrophoneConfig();
    return config.micCommand;
}
function setMicCommand(command) {
    const config = readMicrophoneConfig();
    config.micCommand = command;
    writeMicrophoneConfig(config);
}
async function listMicrophones() {
    const regex = /\n\s{8}(\w.*):\n\n/gm;
    const output = await (0, utils_1.execAsync)(`system_profiler SPAudioDataType | grep "Input Source: " -B 7 -A 1`);
    const matches = output.stdout.match(regex) || [];
    const options = matches.map((m) => m.trim().slice(0, -1));
    console.log({ options });
    return options;
}
async function recordAudio() {
    const filePath = "/tmp/knowhow.wav";
    const audioFile = fs.createWriteStream(filePath, { encoding: "binary" });
    const defaultMic = getDefaultMic();
    const hasSox = await (0, utils_1.execAsync)("which sox").catch(() => false);
    if (!hasSox && !defaultMic) {
        console.error("Sox is required to record audio");
        console.log(`
For Mac OS
brew install sox

For most linux disto's
sudo apt-get install sox libsox-fmt-all
`);
        process.exit(1);
    }
    if (!defaultMic) {
        const options = await listMicrophones();
        const mic = await (0, utils_1.ask)(`Select a microphone (${options.join()})  : `, options);
        setDefaultMic(mic);
    }
    const currentDefaultMic = getDefaultMic();
    const defaultCommand = `sox -t coreaudio "$1" -r 16000 -c 1 /tmp/knowhow.wav`;
    const micCommand = getMicCommand();
    const defaulted = micCommand || defaultCommand;
    const recordCommand = defaulted.replace("$1", currentDefaultMic);
    if (!micCommand) {
        setMicCommand(defaultCommand);
    }
    const task = (0, child_process_1.exec)(recordCommand);
    return { stop: () => task.kill() };
}
async function voiceToText() {
    const startInput = await (0, utils_1.ask)("Press Enter to Start Recording (or type a command to exit): ", []);
    if (startInput.trim() !== "") {
        return startInput;
    }
    const recording = await recordAudio();
    console.log("Recording audio...");
    const stopInput = await (0, utils_1.ask)("Press Enter to Stop Recording (or type a command to cancel): ", []);
    recording.stop();
    console.log("Stopped recording");
    if (stopInput.trim() !== "") {
        return stopInput;
    }
    return (0, conversion_1.convertAudioToText)("/tmp/knowhow.wav", false);
}
//# sourceMappingURL=microphone.js.map