midi-daemon 0.9.2

A Lua-scriptable MIDI routing daemon
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
use anyhow::Result;
use serde::Deserialize;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// One named OBS websocket connection, declared as `[obs.<name>]` in config.toml.
#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct ObsConnCfg {
    pub host: String,
    pub port: u16,
    pub password: Option<String>,
}

/// Public config — fully resolved (no Option fields).
#[derive(Debug, Clone)]
#[allow(clippy::struct_field_names)] // `config_path` is clearer here than the alternatives
pub struct Config {
    pub routes_dir: PathBuf,
    pub default_bpm: f64,
    pub default_ppqn: u32,
    /// Per-route config sections, e.g. `[metronome]` in config.toml
    pub route_configs: HashMap<String, toml::Value>,
    /// Path to the config file that was loaded, or None if using built-in defaults.
    pub config_path: Option<PathBuf>,
    /// Regex applied to all route inputs when no per-route pattern is set.
    pub default_connect_input: Option<String>,
    /// Regex applied to all route outputs when no per-route pattern is set.
    pub default_connect_output: Option<String>,
    /// Single global UDP port to receive all OSC messages on. Incoming packets
    /// are dispatched to routes by address prefix: `/route-name/...`.
    pub osc_receive_port: Option<u16>,
    /// Global OSC send destination (`"host:port"`). Used by every route that
    /// does not declare its own `osc.send` target in `init()`.
    pub osc_send_addr: Option<String>,
    /// How often (in seconds) the daemon sends `/route/heartbeat` to OSC subscribers.
    pub osc_heartbeat_interval: f64,
    /// CLI --routes override; re-applied on reload so it always wins over config file.
    pub routes_dir_override: Option<PathBuf>,
    /// Server-wide root directory for Lua `on_startup`/`on_shutdown` JSON state files.
    /// Each route gets its own subdirectory named after the route. Defaults to
    /// `<cache_dir>/lua-state` when unset.
    pub state_dir: Option<PathBuf>,
    /// Named OBS websocket connections, declared as `[obs.<name>]` sections.
    /// Routes address them by name from `obs_call`/`obs_call_sync` and declare
    /// interest in a connection's events via `init()`'s `obs.connections`.
    pub obs: HashMap<String, ObsConnCfg>,
}

/// Internal deserialization target. `routes_dir` is optional so the caller
/// can supply the right default after knowing which config file was loaded.
#[derive(Deserialize)]
struct RawConfig {
    routes_dir: Option<PathBuf>,
    #[serde(default = "default_bpm")]
    default_bpm: f64,
    #[serde(default = "default_ppqn")]
    default_ppqn: u32,
    default_connect_input: Option<String>,
    default_connect_output: Option<String>,
    osc_receive_port: Option<u16>,
    osc_send_addr: Option<String>,
    #[serde(default = "default_osc_heartbeat_interval")]
    osc_heartbeat_interval: f64,
    state_dir: Option<PathBuf>,
    #[serde(default)]
    obs: HashMap<String, ObsConnCfg>,
    #[serde(flatten)]
    route_configs: HashMap<String, toml::Value>,
}

impl RawConfig {
    fn into_config(self, default_routes_dir: PathBuf, config_path: Option<PathBuf>) -> Config {
        Config {
            routes_dir: self.routes_dir.unwrap_or(default_routes_dir),
            default_bpm: self.default_bpm,
            default_ppqn: self.default_ppqn,
            route_configs: self.route_configs,
            config_path,
            default_connect_input: self.default_connect_input,
            default_connect_output: self.default_connect_output,
            osc_receive_port: self.osc_receive_port,
            osc_send_addr: self.osc_send_addr,
            osc_heartbeat_interval: self.osc_heartbeat_interval,
            routes_dir_override: None,
            state_dir: self.state_dir,
            obs: self.obs,
        }
    }
}

// ── Path helpers ─────────────────────────────────────────────────────────────

fn default_bpm() -> f64 {
    120.0
}

fn default_ppqn() -> u32 {
    24
}

fn default_osc_heartbeat_interval() -> f64 {
    5.0
}

fn default_config(routes_dir: PathBuf) -> Config {
    Config {
        routes_dir,
        default_bpm: default_bpm(),
        default_ppqn: default_ppqn(),
        route_configs: HashMap::new(),
        config_path: None,
        default_connect_input: None,
        default_connect_output: None,
        osc_receive_port: None,
        osc_send_addr: None,
        osc_heartbeat_interval: default_osc_heartbeat_interval(),
        routes_dir_override: None,
        state_dir: None,
        obs: HashMap::new(),
    }
}

fn user_config_dir() -> Option<PathBuf> {
    let home = dirs::home_dir()?;
    // System services run with home=/var/empty or /nonexistent; skip user dirs.
    if !home.exists() || home == std::path::Path::new("/var/empty") {
        return None;
    }
    dirs::config_dir().map(|d| d.join("midi-daemon"))
}

fn system_config_dir() -> PathBuf {
    PathBuf::from("/etc/midi-daemon")
}

fn system_cache_dir() -> PathBuf {
    PathBuf::from("/var/cache/midi-daemon")
}

#[allow(dead_code)]
pub fn default_config_path() -> PathBuf {
    user_config_dir()
        .unwrap_or_else(|| PathBuf::from("~/.config/midi-daemon"))
        .join("config.toml")
}

/// Path to the Unix control socket.
///
/// Resolution order:
///   1. `$RUNTIME_DIRECTORY` — set by systemd when `RuntimeDirectory=midi-daemon` is configured
///   2. `/run/midi-daemon/control.sock` — root, or client connecting to a running system service
///   3. `$XDG_RUNTIME_DIR/midi-daemon/control.sock` — user session
///   4. `~/.cache/midi-daemon/control.sock` — user with no XDG runtime
///   5. `/tmp/midi-daemon.sock` — last resort (e.g. system user with no usable home)
pub fn control_socket_path() -> PathBuf {
    // Systemd sets $RUNTIME_DIRECTORY when RuntimeDirectory= is configured.
    if let Ok(dir) = std::env::var("RUNTIME_DIRECTORY") {
        return PathBuf::from(dir).join("control.sock");
    }
    if unsafe { libc::getuid() } == 0 {
        return PathBuf::from("/run/midi-daemon/control.sock");
    }
    // Non-root client: if the system service socket already exists, use it.
    let system_sock = PathBuf::from("/run/midi-daemon/control.sock");
    if system_sock.exists() {
        return system_sock;
    }
    if let Ok(dir) = std::env::var("XDG_RUNTIME_DIR") {
        return PathBuf::from(dir).join("midi-daemon/control.sock");
    }
    // Only use the cache dir if the home directory actually exists and is usable.
    if let Some(cache) = dirs::cache_dir()
        && cache.parent().is_some_and(std::path::Path::exists) {
        return cache.join("midi-daemon/control.sock");
    }
    PathBuf::from("/tmp/midi-daemon.sock")
}

// ── Config impl ───────────────────────────────────────────────────────────────

impl Config {
    /// Returns the cache directory appropriate for this process.
    ///
    /// Resolution order:
    ///   1. `$CACHE_DIRECTORY` — set by systemd when `CacheDirectory=midi-daemon` is configured
    ///   2. `/var/cache/midi-daemon` — root, or system user with no usable home
    ///   3. `$XDG_CACHE_HOME/midi-daemon` / `~/.cache/midi-daemon` — interactive user session
    #[allow(clippy::unused_self)] // kept as an instance method for API consistency with lua_state_dir()
    pub fn cache_dir(&self) -> PathBuf {
        if let Ok(dir) = std::env::var("CACHE_DIRECTORY") {
            return PathBuf::from(dir);
        }
        if unsafe { libc::getuid() } == 0 {
            return system_cache_dir();
        }
        // System service users (e.g. `midi-daemon`) often have a non-existent home.
        // Fall back to the system cache dir rather than trying to write to /nonexistent.
        let home = dirs::home_dir();
        let home_usable = home
            .as_deref()
            .is_some_and(|h| h.exists() && h != std::path::Path::new("/var/empty"));
        if !home_usable {
            return system_cache_dir();
        }
        dirs::cache_dir().map_or_else(|| {
                home.unwrap().join(".cache/midi-daemon")
            }, |d| d.join("midi-daemon"))
    }

    /// Returns the root directory for Lua `on_startup`/`on_shutdown` JSON state.
    ///
    /// Resolution order:
    ///   1. `state_dir` in config.toml, if set
    ///   2. `<cache_dir>/lua-state`
    ///
    /// Each route gets its own subdirectory named after the route, e.g.
    /// `<state_dir>/<route-name>/state.json`.
    pub fn lua_state_dir(&self) -> PathBuf {
        self.state_dir
            .clone()
            .unwrap_or_else(|| self.cache_dir().join("lua-state"))
    }

    /// Returns the `[route_name]` section from config.toml, if present.
    pub fn route_config(&self, name: &str) -> Option<&toml::Table> {
        self.route_configs.get(name)?.as_table()
    }

    /// Like [`find_and_load`] but accepts explicit CLI overrides.
    ///
    /// - `config_override`: if Some, load this exact file (error if absent).
    /// - `routes_override`: if Some, replace `routes_dir` regardless of the config file.
    ///   The override is stored and re-applied on every hot-reload.
    pub fn find_and_load_with_overrides(
        config_override: Option<&Path>,
        routes_override: Option<&Path>,
    ) -> Result<Self> {
        let mut cfg = if let Some(path) = config_override {
            let default_routes = path.parent().unwrap_or(path).join("routes.d");
            tracing::info!("Loading config from --config: {}", path.display());
            Self::load_file(path, default_routes)?
        } else {
            Self::find_and_load()?
        };

        if let Some(dir) = routes_override {
            tracing::info!("Routes directory overridden by --routes: {}", dir.display());
            cfg.routes_dir = dir.to_path_buf();
            cfg.routes_dir_override = Some(dir.to_path_buf());
        }

        Ok(cfg)
    }

    /// Search for a config file and load it. Lookup order:
    ///   1. `$MIDI_DAEMON_CONFIG` environment variable
    ///   2. `~/.config/midi-daemon/config.toml`  (user)
    ///   3. `/etc/midi-daemon/config.toml`        (system)
    ///   4. Built-in defaults
    pub fn find_and_load() -> Result<Self> {
        // 1. Explicit override
        if let Ok(val) = std::env::var("MIDI_DAEMON_CONFIG") {
            let path = PathBuf::from(&val);
            let default_routes = path
                .parent()
                .unwrap_or(path.as_path())
                .join("routes.d");
            tracing::info!("Loading config from $MIDI_DAEMON_CONFIG: {}", path.display());
            return Self::load_file(&path, default_routes);
        }

        // 2. User config
        if let Some(dir) = user_config_dir() {
            let path = dir.join("config.toml");
            if path.exists() {
                tracing::info!("Loading user config: {}", path.display());
                return Self::load_file(&path, dir.join("routes.d"));
            }
        }

        // 3. System config
        {
            let dir = system_config_dir();
            let path = dir.join("config.toml");
            if path.exists() {
                tracing::info!("Loading system config: {}", path.display());
                return Self::load_file(&path, dir.join("routes.d"));
            }
        }

        // 4. No config found — fall back to built-in defaults
        let (routes_dir, scope) = user_config_dir().map_or_else(|| (system_config_dir().join("routes.d"), "system"), |d| (d.join("routes.d"), "user"));
        tracing::info!("No config file found, using {} defaults", scope);
        Ok(default_config(routes_dir))
    }

    /// Load from an explicit path. Useful for testing or when the caller
    /// already knows which file to use.
    /// Falls back to built-in defaults with `default_routes_dir` if the file
    /// is absent.
    #[allow(dead_code)]
    pub fn load(path: &Path) -> Result<Self> {
        let default_routes = path.parent().unwrap_or(path).join("routes.d");
        if path.exists() {
            Self::load_file(path, default_routes)
        } else {
            tracing::info!("No config found at {}, using defaults", path.display());
            let routes_dir = user_config_dir()
                .unwrap_or_else(|| PathBuf::from("~/.config/midi-daemon"))
                .join("routes.d");
            Ok(default_config(routes_dir))
        }
    }

    /// Re-read config from the same file it was originally loaded from.
    /// Falls back to returning a clone of self if no file path is known.
    /// CLI overrides (`--routes`) are re-applied after the file is re-read.
    pub fn reload(&self) -> Result<Self> {
        let default_routes = self.routes_dir_override
            .clone()
            .unwrap_or_else(|| self.routes_dir.clone());
        let mut new_cfg = match &self.config_path {
            Some(path) => Self::load_file(path, default_routes)?,
            None => return Ok(self.clone()),
        };
        if let Some(ref override_dir) = self.routes_dir_override {
            new_cfg.routes_dir.clone_from(override_dir);
            new_cfg.routes_dir_override = Some(override_dir.clone());
        }
        Ok(new_cfg)
    }

    fn load_file(path: &Path, default_routes_dir: PathBuf) -> Result<Self> {
        let text = std::fs::read_to_string(path)?;
        let raw: RawConfig = toml::from_str(&text)?;
        Ok(raw.into_config(default_routes_dir, Some(path.to_path_buf())))
    }
}

#[cfg(test)]
#[allow(clippy::float_cmp)] // exact round-trip checks of literal values, not computed results
mod tests {
    use super::*;
    use std::io::Write;

    fn write_tmp(name: &str, content: &str) -> PathBuf {
        let path = std::env::temp_dir().join(name);
        let mut f = std::fs::File::create(&path).unwrap();
        write!(f, "{content}").unwrap();
        path
    }

    #[test]
    fn default_bpm_is_120() {
        assert_eq!(default_bpm(), 120.0);
    }

    #[test]
    fn default_ppqn_is_24() {
        assert_eq!(default_ppqn(), 24);
    }

    #[test]
    fn missing_file_returns_defaults() {
        let path = PathBuf::from("/tmp/midi_daemon_nonexistent_config_abc123.toml");
        let _ = std::fs::remove_file(&path);
        let cfg = Config::load(&path).unwrap();
        assert_eq!(cfg.default_bpm, 120.0);
        assert_eq!(cfg.default_ppqn, 24);
    }

    #[test]
    fn load_full_config() {
        let path = write_tmp(
            "midi_daemon_test_full.toml",
            "default_bpm = 140.0\ndefault_ppqn = 48\n",
        );
        let cfg = Config::load(&path).unwrap();
        assert!((cfg.default_bpm - 140.0).abs() < 1e-9);
        assert_eq!(cfg.default_ppqn, 48);
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn load_partial_config_fills_defaults() {
        let path = write_tmp("midi_daemon_test_partial.toml", "default_bpm = 90.0\n");
        let cfg = Config::load(&path).unwrap();
        assert!((cfg.default_bpm - 90.0).abs() < 1e-9);
        assert_eq!(cfg.default_ppqn, 24);
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn load_ppqn_only() {
        let path = write_tmp("midi_daemon_test_ppqn.toml", "default_ppqn = 96\n");
        let cfg = Config::load(&path).unwrap();
        assert_eq!(cfg.default_bpm, 120.0);
        assert_eq!(cfg.default_ppqn, 96);
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn load_custom_routes_dir() {
        let path = write_tmp(
            "midi_daemon_test_routes_dir.toml",
            "routes_dir = \"/custom/routes\"\n",
        );
        let cfg = Config::load(&path).unwrap();
        assert_eq!(cfg.routes_dir, PathBuf::from("/custom/routes"));
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn routes_dir_defaults_to_parent_of_config() {
        let path = write_tmp("midi_daemon_test_routes_default.toml", "");
        let cfg = Config::load(&path).unwrap();
        let expected = path.parent().unwrap().join("routes.d");
        assert_eq!(cfg.routes_dir, expected);
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn invalid_toml_returns_error() {
        let path = write_tmp("midi_daemon_test_invalid.toml", "not valid toml ][[\n");
        let result = Config::load(&path);
        assert!(result.is_err());
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn default_config_path_ends_with_config_toml() {
        let p = default_config_path();
        assert_eq!(p.file_name().unwrap(), "config.toml");
    }

    // ── find_and_load_with_overrides ──────────────────────────────────────────

    #[test]
    fn explicit_config_path_loads_correctly() {
        let path = write_tmp("midi_daemon_test_explicit_config.toml", "default_bpm = 99.0\n");
        let cfg = Config::find_and_load_with_overrides(Some(&path), None).unwrap();
        assert!((cfg.default_bpm - 99.0).abs() < 1e-9);
        assert_eq!(cfg.config_path, Some(path.clone()));
        assert!(cfg.routes_dir_override.is_none());
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn explicit_config_path_missing_returns_error() {
        let path = PathBuf::from("/tmp/midi_daemon_nonexistent_explicit_xyz.toml");
        let _ = std::fs::remove_file(&path);
        let result = Config::find_and_load_with_overrides(Some(&path), None);
        assert!(result.is_err());
    }

    #[test]
    fn routes_override_wins_over_config_file() {
        let path = write_tmp(
            "midi_daemon_test_routes_override.toml",
            "routes_dir = \"/config/routes\"\n",
        );
        let override_dir = PathBuf::from("/override/routes");
        let cfg = Config::find_and_load_with_overrides(Some(&path), Some(&override_dir)).unwrap();
        assert_eq!(cfg.routes_dir, override_dir);
        assert_eq!(cfg.routes_dir_override, Some(override_dir));
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn routes_override_survives_reload() {
        let path = write_tmp(
            "midi_daemon_test_routes_reload.toml",
            "routes_dir = \"/config/routes\"\n",
        );
        let override_dir = PathBuf::from("/override/routes");
        let cfg = Config::find_and_load_with_overrides(Some(&path), Some(&override_dir)).unwrap();
        let reloaded = cfg.reload().unwrap();
        assert_eq!(reloaded.routes_dir, override_dir);
        assert_eq!(reloaded.routes_dir_override, Some(override_dir));
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn no_overrides_leaves_routes_dir_override_none() {
        // find_and_load_with_overrides(None, None) should behave like find_and_load
        // and not set routes_dir_override.
        let cfg = Config::find_and_load_with_overrides(None, None).unwrap();
        assert!(cfg.routes_dir_override.is_none());
    }

    #[test]
    fn routes_only_override_with_no_config_override() {
        let override_dir = PathBuf::from("/cli/routes");
        let cfg = Config::find_and_load_with_overrides(None, Some(&override_dir)).unwrap();
        assert_eq!(cfg.routes_dir, override_dir);
        assert_eq!(cfg.routes_dir_override, Some(override_dir));
    }

    // ── default_connect_input / default_connect_output ────────────────────────

    #[test]
    fn connect_fields_absent_returns_none() {
        let path = write_tmp("midi_daemon_test_no_connect.toml", "default_bpm = 120.0\n");
        let cfg = Config::load(&path).unwrap();
        assert!(cfg.default_connect_input.is_none());
        assert!(cfg.default_connect_output.is_none());
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn connect_input_only_parses() {
        let path = write_tmp(
            "midi_daemon_test_connect_in.toml",
            "default_connect_input = \".*KeyLab.*\"\n",
        );
        let cfg = Config::load(&path).unwrap();
        assert_eq!(cfg.default_connect_input.as_deref(), Some(".*KeyLab.*"));
        assert!(cfg.default_connect_output.is_none());
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn connect_output_only_parses() {
        let path = write_tmp(
            "midi_daemon_test_connect_out.toml",
            "default_connect_output = \".*Surge.*\"\n",
        );
        let cfg = Config::load(&path).unwrap();
        assert!(cfg.default_connect_input.is_none());
        assert_eq!(cfg.default_connect_output.as_deref(), Some(".*Surge.*"));
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn connect_both_fields_parse() {
        let path = write_tmp(
            "midi_daemon_test_connect_both.toml",
            "default_connect_input = \".*KeyLab.*\"\ndefault_connect_output = \".*Surge.*\"\n",
        );
        let cfg = Config::load(&path).unwrap();
        assert_eq!(cfg.default_connect_input.as_deref(), Some(".*KeyLab.*"));
        assert_eq!(cfg.default_connect_output.as_deref(), Some(".*Surge.*"));
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn connect_fields_survive_missing_file_fallback() {
        let path = PathBuf::from("/tmp/midi_daemon_nonexistent_connect_xyz.toml");
        let _ = std::fs::remove_file(&path);
        let cfg = Config::load(&path).unwrap();
        assert!(cfg.default_connect_input.is_none());
        assert!(cfg.default_connect_output.is_none());
    }

    // ── state_dir / lua_state_dir ──────────────────────────────────────────────

    #[test]
    fn state_dir_absent_falls_back_to_cache_dir() {
        let path = write_tmp("midi_daemon_test_no_state_dir.toml", "default_bpm = 120.0\n");
        let cfg = Config::load(&path).unwrap();
        assert!(cfg.state_dir.is_none());
        assert_eq!(cfg.lua_state_dir(), cfg.cache_dir().join("lua-state"));
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn state_dir_configured_wins_over_cache_dir() {
        let path = write_tmp(
            "midi_daemon_test_state_dir.toml",
            "state_dir = \"/custom/lua-state\"\n",
        );
        let cfg = Config::load(&path).unwrap();
        assert_eq!(cfg.lua_state_dir(), PathBuf::from("/custom/lua-state"));
        let _ = std::fs::remove_file(&path);
    }

    // ── obs connections ────────────────────────────────────────────────────────

    #[test]
    fn obs_section_absent_returns_empty_map() {
        let path = write_tmp("midi_daemon_test_no_obs.toml", "default_bpm = 120.0\n");
        let cfg = Config::load(&path).unwrap();
        assert!(cfg.obs.is_empty());
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn single_obs_connection_parses() {
        let path = write_tmp(
            "midi_daemon_test_obs_single.toml",
            "[obs.main]\nhost = \"127.0.0.1\"\nport = 4455\npassword = \"secret\"\n",
        );
        let cfg = Config::load(&path).unwrap();
        let main = cfg.obs.get("main").unwrap();
        assert_eq!(main.host, "127.0.0.1");
        assert_eq!(main.port, 4455);
        assert_eq!(main.password.as_deref(), Some("secret"));
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn obs_connection_without_password_parses() {
        let path = write_tmp(
            "midi_daemon_test_obs_no_pw.toml",
            "[obs.main]\nhost = \"127.0.0.1\"\nport = 4455\n",
        );
        let cfg = Config::load(&path).unwrap();
        assert!(cfg.obs.get("main").unwrap().password.is_none());
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn multiple_obs_connections_parse_independently() {
        let path = write_tmp(
            "midi_daemon_test_obs_multi.toml",
            "[obs.main]\nhost = \"127.0.0.1\"\nport = 4455\n\n[obs.backup]\nhost = \"192.168.1.50\"\nport = 4456\npassword = \"other\"\n",
        );
        let cfg = Config::load(&path).unwrap();
        assert_eq!(cfg.obs.len(), 2);
        assert_eq!(cfg.obs.get("main").unwrap().port, 4455);
        assert_eq!(cfg.obs.get("backup").unwrap().password.as_deref(), Some("other"));
        let _ = std::fs::remove_file(&path);
    }
}