// talkduck: calmer audio on a Mac while you talk to a voice assistant.
//
// 1. Keeps Bluetooth headphones (AirPods and the like) from being used as the microphone.
//    As soon as they become the input, talkduck switches to another mic (USB, display or built-in),
//    so the headphones stay in high-quality stereo instead of dropping to the headset profile.
// 2. While any microphone is in use and something is playing, it fades the system volume down a bit,
//    and fades it back up once you've stopped talking.
// 3. Push to talk: hold Right Option anywhere to talk to Claude or Grok Bot, let go to stop.
//    It goes to whichever of the two you used last. Tap Right Option twice to switch.
//
// Settings (environment variables):
//   DUCK_PCT         how much quieter, in percent               (default 45)
//   DUCK_FADE_SEC    how long the fade down takes               (default 0.6)
//   FADE_SEC         how long the fade back up takes            (default 1.2)
//   RELEASE_SEC      wait after the mic stops before fading up  (default 1.5)
//   PREFERRED_MIC    part of the name of the mic to switch to   (default: first USB, then built-in)
//   MIC_GUARD=0      turn off the microphone switch
//   DUCK=0           turn off the fade
//   PTT=0            turn off push to talk
//   PTT_HOLD_SEC     how long you hold Right Option before it counts as talking (default 0.25)
//   PTT_DEFAULT      claude or grok: where talking goes before you've used either (default claude)
//
// Push to talk needs two things once:
//   - System Settings › Privacy & Security › Accessibility: allow talkduck.
//   - In Claude: Settings › Quick entry dictation shortcut set to ⌃⌥⇧⌘F18
//     (or in claude_desktop_config.json: "quickEntryDictationShortcut": {"accelerator": "Control+Alt+Shift+Command+F18"}).
//
// Build: swiftc -O talkduck.swift -o talkduck   (needs the Xcode command line tools)
// https://frankspin.com/en/lab/talkduck/
import AppKit
import ApplicationServices
import AudioToolbox
import CoreAudio
import Foundation

let env = ProcessInfo.processInfo.environment
func num(_ k: String, _ d: Double) -> Double { Double(env[k] ?? "") ?? d }
let duckPct = num("DUCK_PCT", 45)
let duckFadeSec = num("DUCK_FADE_SEC", 0.6)
let fadeSec = num("FADE_SEC", 1.2)
let releaseSec = num("RELEASE_SEC", 1.5)
let preferredMic = env["PREFERRED_MIC"]?.lowercased()
let guardOn = env["MIC_GUARD"] != "0"
let duckOn = env["DUCK"] != "0"
let pttOn = env["PTT"] != "0"
let pttHoldSec = num("PTT_HOLD_SEC", 0.25)

func log(_ s: String) { FileHandle.standardError.write("\(Date()) \(s)\n".data(using: .utf8)!) }

let system = AudioObjectID(kAudioObjectSystemObject)
func addr(_ sel: AudioObjectPropertySelector, _ scope: AudioObjectPropertyScope = kAudioObjectPropertyScopeGlobal) -> AudioObjectPropertyAddress {
    AudioObjectPropertyAddress(mSelector: sel, mScope: scope, mElement: kAudioObjectPropertyElementMain)
}
func getU32(_ id: AudioObjectID, _ sel: AudioObjectPropertySelector) -> UInt32? {
    var a = addr(sel); var v: UInt32 = 0; var size = UInt32(MemoryLayout<UInt32>.size)
    return AudioObjectGetPropertyData(id, &a, 0, nil, &size, &v) == noErr ? v : nil
}
func name(_ id: AudioDeviceID) -> String {
    var a = addr(kAudioObjectPropertyName); var n: Unmanaged<CFString>?; var size = UInt32(MemoryLayout<Unmanaged<CFString>?>.size)
    guard AudioObjectGetPropertyData(id, &a, 0, nil, &size, &n) == noErr, let s = n?.takeRetainedValue() else { return "?" }
    return s as String
}

func devices(scope: AudioObjectPropertyScope) -> [AudioDeviceID] {
    var a = addr(kAudioHardwarePropertyDevices); var size: UInt32 = 0
    guard AudioObjectGetPropertyDataSize(system, &a, 0, nil, &size) == noErr else { return [] }
    var ids = [AudioDeviceID](repeating: 0, count: Int(size) / MemoryLayout<AudioDeviceID>.size)
    guard AudioObjectGetPropertyData(system, &a, 0, nil, &size, &ids) == noErr else { return [] }
    return ids.filter { id in
        var s = addr(kAudioDevicePropertyStreams, scope); var n: UInt32 = 0
        return AudioObjectGetPropertyDataSize(id, &s, 0, nil, &n) == noErr && n > 0
    }
}

func isRunning(_ id: AudioDeviceID) -> Bool { (getU32(id, kAudioDevicePropertyDeviceIsRunningSomewhere) ?? 0) != 0 }
func defaultDevice(_ sel: AudioObjectPropertySelector) -> AudioDeviceID? { getU32(system, sel) }

// --- 1. Microphone switch ---------------------------------------------------------------

let bluetooth: Set<UInt32> = [kAudioDeviceTransportTypeBluetooth, kAudioDeviceTransportTypeBluetoothLE]
// Rather not: phones (Continuity), aggregate and virtual devices.
let avoid: Set<UInt32> = [kAudioDeviceTransportTypeAggregate, kAudioDeviceTransportTypeVirtual,
                          kAudioDeviceTransportTypeAutoAggregate, kAudioDeviceTransportTypeContinuityCaptureWired,
                          kAudioDeviceTransportTypeContinuityCaptureWireless, kAudioDeviceTransportTypeUnknown]

func replacementMic() -> AudioDeviceID? {
    let mics = devices(scope: kAudioObjectPropertyScopeInput).filter {
        let t = getU32($0, kAudioDevicePropertyTransportType) ?? 0
        return !bluetooth.contains(t) && !avoid.contains(t)
    }
    if let p = preferredMic, let m = mics.first(where: { name($0).lowercased().contains(p) }) { return m }
    let rank: (AudioDeviceID) -> Int = {
        switch getU32($0, kAudioDevicePropertyTransportType) ?? 0 {
        case kAudioDeviceTransportTypeUSB, kAudioDeviceTransportTypeThunderbolt, kAudioDeviceTransportTypeDisplayPort: return 0
        case kAudioDeviceTransportTypeBuiltIn: return 1
        default: return 2
        }
    }
    return mics.min { rank($0) < rank($1) }
}

func guardMic() {
    guard let cur = defaultDevice(kAudioHardwarePropertyDefaultInputDevice),
          bluetooth.contains(getU32(cur, kAudioDevicePropertyTransportType) ?? 0),
          var next = replacementMic() else { return }
    var a = addr(kAudioHardwarePropertyDefaultInputDevice)
    if AudioObjectSetPropertyData(system, &a, 0, nil, UInt32(MemoryLayout<AudioDeviceID>.size), &next) == noErr {
        log("microphone: \(name(cur)) → \(name(next))")
    }
}

// --- 2. Fade while you talk -------------------------------------------------------------

func micInUse() -> Bool { devices(scope: kAudioObjectPropertyScopeInput).contains(where: isRunning) }
func audioPlaying() -> Bool { defaultDevice(kAudioHardwarePropertyDefaultOutputDevice).map(isRunning) ?? false }

// System volume (0-100), the same one as the volume keys. Straight through CoreAudio,
// with AppleScript as a fallback for outputs that don't expose a main volume.
var volAddr = addr(kAudioHardwareServiceDeviceProperty_VirtualMainVolume, kAudioDevicePropertyScopeOutput)
func osa(_ src: String) -> String? {
    var err: NSDictionary?
    let r = NSAppleScript(source: src)?.executeAndReturnError(&err)
    if let err = err { log("applescript: \(err)"); return nil }
    return r?.stringValue
}
func getVol() -> Int? {
    if let out = defaultDevice(kAudioHardwarePropertyDefaultOutputDevice) {
        var v: Float32 = 0; var size = UInt32(MemoryLayout<Float32>.size)
        if AudioObjectGetPropertyData(out, &volAddr, 0, nil, &size, &v) == noErr { return Int((v * 100).rounded()) }
    }
    return osa("output volume of (get volume settings) as string").flatMap { Int($0) }
}
func setVol(_ v: Int) {
    let c = max(0, min(100, v))
    if let out = defaultDevice(kAudioHardwarePropertyDefaultOutputDevice) {
        var f = Float32(c) / 100
        if AudioObjectSetPropertyData(out, &volAddr, 0, nil, UInt32(MemoryLayout<Float32>.size), &f) == noErr { return }
    }
    _ = osa("set volume output volume \(c)")
}

func fade(from: Int, to: Int, sec: Double) {
    let steps = max(1, Int(sec * 20))
    for i in 1...steps {
        let t = Double(i) / Double(steps)
        let e = t < 0.5 ? 2 * t * t : 1 - pow(-2 * t + 2, 2) / 2 // ease in and out, no hard edges
        setVol(Int((Double(from) + Double(to - from) * e).rounded()))
        Thread.sleep(forTimeInterval: sec / Double(steps))
    }
}

func audioLoop() {
    var savedVol: Int? = nil   // volume before the fade down
    var duckedVol: Int? = nil  // volume talkduck set itself
    var lastActive = Date.distantPast
    var wasActive = false
    while true {
        if guardOn { guardMic() }
        if duckOn {
            let active = micInUse()
            if active != wasActive { log(active ? "mic in use" : "mic free"); wasActive = active }
            if active { lastActive = Date() }

            if active, savedVol == nil, audioPlaying(), let v = getVol(), v > 0 {
                let target = Int((Double(v) * (1 - duckPct / 100)).rounded())
                log("fade down \(v) → \(target)")
                fade(from: v, to: target, sec: duckFadeSec)
                savedVol = v; duckedVol = target
            } else if !active, let saved = savedVol, Date().timeIntervalSince(lastActive) >= releaseSec {
                // Changed the volume yourself in the meantime? Then talkduck leaves it alone.
                if let cur = getVol(), let d = duckedVol, abs(cur - d) <= 2 {
                    log("fade up \(cur) → \(saved)"); fade(from: cur, to: saved, sec: fadeSec)
                }
                savedVol = nil; duckedVol = nil
            }
        }
        Thread.sleep(forTimeInterval: 0.25)
    }
}

// --- 3. Push to talk on Right Option ----------------------------------------------------

enum Target: String { case claude, grok }
let bundleIDs: [Target: String] = [.claude: "com.anthropic.claudefordesktop", .grok: "com.anysphere.sand"]
var lastTarget = Target(rawValue: env["PTT_DEFAULT"] ?? "") ?? .claude

let kRightOption: Int64 = 61
let kF18: CGKeyCode = 79
let kD: CGKeyCode = 2
let rightAltBit: UInt64 = 0x40 // NX_DEVICERALTKEYMASK

func post(_ key: CGKeyCode, down: Bool, flags: CGEventFlags) {
    let src = CGEventSource(stateID: .privateState)
    guard let e = CGEvent(keyboardEventSource: src, virtualKey: key, keyDown: down) else { return }
    e.flags = flags
    e.post(tap: .cghidEventTap)
}
// Claude's quick-entry dictation is a toggle on ⌃⌥⇧⌘F18: one press starts, the next one stops.
func pressClaudeShortcut() {
    let f: CGEventFlags = [.maskControl, .maskAlternate, .maskShift, .maskCommand]
    post(kF18, down: true, flags: f); post(kF18, down: false, flags: f)
}

func app(_ t: Target) -> NSRunningApplication? {
    NSRunningApplication.runningApplications(withBundleIdentifier: bundleIDs[t]!).first
}
func currentTarget() -> Target {
    if let front = NSWorkspace.shared.frontmostApplication?.bundleIdentifier,
       let t = bundleIDs.first(where: { $0.value == front })?.key { return t }
    return lastTarget
}

var rDown = false, otherKey = false, talking = false
var downAt = Date.distantPast, lastTap = Date.distantPast
var talkTarget = Target.claude

func startTalking() {
    talkTarget = currentTarget()
    guard app(talkTarget) != nil else { log("push to talk: \(talkTarget.rawValue) isn't running"); NSSound.beep(); return }
    talking = true
    log("push to talk → \(talkTarget.rawValue)")
    switch talkTarget {
    case .claude:
        pressClaudeShortcut()
    case .grok:
        // Grok Bot's hold-to-talk (⌘D) only works in its own window, so bring it forward first.
        app(.grok)?.activate()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.18) {
            if talking { post(kD, down: true, flags: .maskCommand) }
        }
    }
}
func stopTalking() {
    guard talking else { return }
    talking = false
    switch talkTarget {
    case .claude: pressClaudeShortcut()
    case .grok: post(kD, down: false, flags: .maskCommand)
    }
}
func switchTarget() {
    lastTarget = lastTarget == .claude ? .grok : .claude
    log("push to talk now goes to \(lastTarget.rawValue)")
    NSSound(named: lastTarget == .claude ? "Tink" : "Pop")?.play()
}

var tap: CFMachPort?
func handle(_ type: CGEventType, _ event: CGEvent) {
    if type == .tapDisabledByTimeout || type == .tapDisabledByUserInput {
        if let tap = tap { CGEvent.tapEnable(tap: tap, enable: true) }
        return
    }
    let code = event.getIntegerValueField(.keyboardEventKeycode)
    if type == .flagsChanged && code == kRightOption {
        let isDown = event.flags.rawValue & rightAltBit != 0
        if isDown && !rDown {
            rDown = true; otherKey = false; downAt = Date()
            DispatchQueue.main.asyncAfter(deadline: .now() + pttHoldSec) {
                if rDown && !otherKey && !talking { startTalking() }
            }
        } else if !isDown && rDown {
            rDown = false
            if talking { stopTalking(); return }
            // A short tap on its own: two of those in a row switch between Claude and Grok Bot.
            if !otherKey && Date().timeIntervalSince(downAt) < pttHoldSec {
                if Date().timeIntervalSince(lastTap) < 0.4 { switchTarget(); lastTap = .distantPast } else { lastTap = Date() }
            }
        }
    } else if rDown && !talking && (type == .keyDown || type == .flagsChanged) {
        otherKey = true // Right Option used for a key combo (like ⌥E for é): not push to talk.
    }
}

func startPushToTalk() {
    let opts = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
    if !AXIsProcessTrustedWithOptions(opts) {
        log("push to talk: allow talkduck under System Settings › Privacy & Security › Accessibility, then it starts by itself")
    }
    NSWorkspace.shared.notificationCenter.addObserver(forName: NSWorkspace.didActivateApplicationNotification, object: nil, queue: .main) { n in
        guard let id = (n.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication)?.bundleIdentifier,
              let t = bundleIDs.first(where: { $0.value == id })?.key, t != lastTarget else { return }
        lastTarget = t
    }
    // Wait for the permission, then listen to the keyboard.
    Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { timer in
        guard AXIsProcessTrusted() else { return }
        timer.invalidate()
        let mask = (1 << CGEventType.flagsChanged.rawValue) | (1 << CGEventType.keyDown.rawValue)
        tap = CGEvent.tapCreate(tap: .cgSessionEventTap, place: .headInsertEventTap, options: .listenOnly,
                                eventsOfInterest: CGEventMask(mask),
                                callback: { _, type, event, _ in handle(type, event); return Unmanaged.passUnretained(event) },
                                userInfo: nil)
        guard let tap = tap else { log("push to talk: couldn't listen to the keyboard"); return }
        CFRunLoopAddSource(CFRunLoopGetMain(), CFMachPortCreateRunLoopSource(nil, tap, 0), .commonModes)
        CGEvent.tapEnable(tap: tap, enable: true)
        log("push to talk: hold Right Option (now → \(lastTarget.rawValue))")
    }.fire()
}

log("talkduck started: mic switch \(guardOn ? "on" : "off"), fade \(duckOn ? "\(Int(duckPct))% down in \(duckFadeSec)s, up in \(fadeSec)s" : "off"), push to talk \(pttOn ? "on" : "off")")
Thread.detachNewThread(audioLoop)
if pttOn { startPushToTalk() }
RunLoop.main.run()
