1use crate::errors::BridgeError;
14use crate::utils::{resolve_python_path, resolve_site_package_path};
15use once_cell::sync::OnceCell;
16use pyo3::prelude::*;
17use pyo3::types::PyModule;
18use r2x_config::Config;
19use r2x_logger as logger;
20use std::env;
21use std::fs;
22use std::path::{Path, PathBuf};
23use std::process::Command;
24
25pub struct Bridge {
27 _marker: (),
29}
30
31static BRIDGE_INSTANCE: OnceCell<Result<Bridge, BridgeError>> = OnceCell::new();
33
34impl Bridge {
35 pub fn get() -> Result<&'static Bridge, BridgeError> {
37 match BRIDGE_INSTANCE.get_or_init(Bridge::initialize) {
38 Ok(bridge) => Ok(bridge),
39 Err(e) => Err(BridgeError::Initialization(format!("{}", e))),
40 }
41 }
42
43 pub fn is_python_available() -> bool {
45 let config = match Config::load() {
46 Ok(c) => c,
47 Err(_) => return false,
48 };
49
50 let venv_path = PathBuf::from(config.get_venv_path());
52 venv_path.join("pyvenv.cfg").exists()
53 }
54
55 fn initialize() -> Result<Bridge, BridgeError> {
63 let start_time = std::time::Instant::now();
64
65 let mut config = Config::load()
66 .map_err(|e| BridgeError::Initialization(format!("Failed to load config: {}", e)))?;
67
68 let venv_path = PathBuf::from(config.get_venv_path());
70
71 if !venv_path.exists() {
72 Self::create_venv(&config, &venv_path)?;
74 }
75
76 let python_home = resolve_python_home(&venv_path)?;
78 env::set_var("PYTHONHOME", &python_home);
79 logger::debug(&format!("Set PYTHONHOME={}", python_home.display()));
80
81 let site_packages = resolve_site_package_path(&venv_path)?;
83
84 Self::configure_python_path(&site_packages);
86
87 check_python_library_available()?;
89
90 logger::debug("Initializing PyO3...");
92 let pyo3_start = std::time::Instant::now();
93 pyo3::Python::initialize();
94 logger::debug(&format!(
95 "pyo3::Python::initialize took: {:?}",
96 pyo3_start.elapsed()
97 ));
98
99 pyo3::Python::attach(|py| {
101 let sys = PyModule::import(py, "sys")
102 .map_err(|e| BridgeError::Python(format!("Failed to import sys module: {}", e)))?;
103 sys.setattr("dont_write_bytecode", false).map_err(|e| {
104 BridgeError::Python(format!("Failed to enable bytecode generation: {}", e))
105 })?;
106 Ok::<(), BridgeError>(())
107 })?;
108 logger::debug("Enabled Python bytecode generation");
109
110 pyo3::Python::attach(|py| {
112 let site = PyModule::import(py, "site")
113 .map_err(|e| BridgeError::Python(format!("Failed to import site module: {}", e)))?;
114 site.call_method1("addsitedir", (site_packages.to_string_lossy().as_ref(),))
115 .map_err(|e| BridgeError::Python(format!("Failed to add site directory: {}", e)))?;
116 Ok::<(), BridgeError>(())
117 })?;
118
119 let cache_path = config.ensure_cache_path().map_err(|e| {
121 BridgeError::Initialization(format!("Failed to ensure cache path: {}", e))
122 })?;
123 Self::configure_python_cache(&cache_path)?;
124
125 if let Err(e) = Self::configure_python_logging() {
127 logger::warn(&format!("Python logging configuration failed: {}", e));
128 }
129
130 logger::debug(&format!(
131 "Total bridge initialization took: {:?}",
132 start_time.elapsed()
133 ));
134
135 Ok(Bridge { _marker: () })
136 }
137
138 fn create_venv(config: &Config, venv_path: &PathBuf) -> Result<(), BridgeError> {
142 logger::step(&format!(
143 "Creating Python virtual environment at: {}",
144 venv_path.display()
145 ));
146
147 let python_version = get_compiled_python_version();
148
149 if let Some(ref uv_path) = config.uv_path {
151 let output = Command::new(uv_path)
152 .arg("venv")
153 .arg(venv_path)
154 .arg("--python")
155 .arg(&python_version)
156 .output()?;
157
158 if output.status.success() {
159 logger::success("Virtual environment created successfully");
160 return Ok(());
161 }
162
163 let stderr = String::from_utf8_lossy(&output.stderr);
164 logger::debug(&format!("uv venv failed: {}", stderr));
165 }
166
167 let python_cmd = format!("python{}", python_version);
169 let output = Command::new(&python_cmd)
170 .args(["-m", "venv"])
171 .arg(venv_path)
172 .output();
173
174 if let Ok(output) = output {
175 if output.status.success() {
176 logger::success("Virtual environment created successfully");
177 return Ok(());
178 }
179 }
180
181 let output = Command::new("python3")
183 .args(["-m", "venv"])
184 .arg(venv_path)
185 .output()?;
186
187 if !output.status.success() {
188 let stderr = String::from_utf8_lossy(&output.stderr);
189 return Err(BridgeError::Initialization(format!(
190 "Failed to create virtual environment: {}",
191 stderr
192 )));
193 }
194
195 logger::success("Virtual environment created successfully");
196 Ok(())
197 }
198
199 fn configure_python_path(site_packages: &Path) {
201 let mut paths = vec![site_packages.to_path_buf()];
202 if let Some(existing) = env::var_os("PYTHONPATH") {
203 if !existing.is_empty() {
204 paths.extend(env::split_paths(&existing));
205 }
206 }
207 if let Ok(joined) = env::join_paths(paths) {
208 env::set_var("PYTHONPATH", &joined);
209 logger::debug(&format!(
210 "Updated PYTHONPATH to include {}",
211 site_packages.display()
212 ));
213 }
214 }
215
216 fn configure_python_cache(cache_path: &str) -> Result<(), BridgeError> {
218 std::fs::create_dir_all(cache_path).map_err(|e| {
219 BridgeError::Initialization(format!("Failed to create cache directory: {}", e))
220 })?;
221 env::set_var("R2X_CACHE_PATH", cache_path);
222
223 let cache_path_escaped = cache_path.replace('\\', "\\\\");
224 pyo3::Python::attach(|py| {
225 let patch_code = format!(
226 r#"from pathlib import Path
227_R2X_CACHE_PATH = Path(r"{cache}")
228
229def _r2x_cache_path_override():
230 return _R2X_CACHE_PATH
231"#,
232 cache = cache_path_escaped
233 );
234
235 let code_cstr = std::ffi::CString::new(patch_code).map_err(|e| {
236 BridgeError::Python(format!("Failed to prepare cache override script: {}", e))
237 })?;
238 let filename = std::ffi::CString::new("r2x_cache_patch.py").map_err(|e| {
239 BridgeError::Python(format!("Failed to create filename: {}", e))
240 })?;
241 let module_name = std::ffi::CString::new("r2x_cache_patch").map_err(|e| {
242 BridgeError::Python(format!("Failed to create module name: {}", e))
243 })?;
244 let patch_module = PyModule::from_code(
245 py,
246 code_cstr.as_c_str(),
247 filename.as_c_str(),
248 module_name.as_c_str(),
249 )
250 .map_err(|e| BridgeError::Python(format!("Failed to build cache override: {}", e)))?;
251
252 let override_fn = patch_module
253 .getattr("_r2x_cache_path_override")
254 .map_err(|e| {
255 BridgeError::Python(format!("Failed to obtain cache override function: {}", e))
256 })?;
257
258 let file_ops = PyModule::import(py, "r2x_core.utils.file_operations").map_err(|e| {
259 BridgeError::Python(format!(
260 "Failed to import r2x_core.utils.file_operations: {}",
261 e
262 ))
263 })?;
264
265 file_ops
266 .setattr("get_r2x_cache_path", override_fn)
267 .map_err(|e| {
268 BridgeError::Python(format!("Failed to override cache path: {}", e))
269 })?;
270
271 Ok::<(), BridgeError>(())
272 })?;
273
274 Ok(())
275 }
276
277 fn configure_python_logging() -> Result<(), BridgeError> {
279 let log_python = logger::get_log_python();
280 if !log_python {
281 return Ok(());
282 }
283
284 let verbosity = logger::get_verbosity();
285 logger::debug(&format!(
286 "Configuring Python logging with verbosity={}",
287 verbosity
288 ));
289
290 pyo3::Python::attach(|py| {
291 let logger_module = PyModule::import(py, "r2x_core.logger").map_err(|e| {
292 logger::warn(&format!("Failed to import r2x_core.logger: {}", e));
293 BridgeError::Import("r2x_core.logger".to_string(), format!("{}", e))
294 })?;
295 let setup_logging = logger_module.getattr("setup_logging").map_err(|e| {
296 logger::warn(&format!("Failed to get setup_logging function: {}", e));
297 BridgeError::Python(format!("setup_logging not found: {}", e))
298 })?;
299 setup_logging.call1((verbosity,))?;
300
301 let loguru = PyModule::import(py, "loguru")?;
302 let logger_obj = loguru.getattr("logger")?;
303 logger_obj.call_method1("enable", ("r2x_core",))?;
304 logger_obj.call_method1("enable", ("r2x_reeds",))?;
305 logger_obj.call_method1("enable", ("r2x_plexos",))?;
306 logger_obj.call_method1("enable", ("r2x_sienna",))?;
307
308 Ok::<(), BridgeError>(())
309 })
310 }
311
312 pub fn reconfigure_logging_for_plugin(_plugin_name: &str) -> Result<(), BridgeError> {
314 Self::configure_python_logging()
315 }
316}
317
318fn resolve_python_home(venv_path: &Path) -> Result<PathBuf, BridgeError> {
330 let pyvenv_cfg = venv_path.join("pyvenv.cfg");
331
332 if !pyvenv_cfg.exists() {
333 return Err(BridgeError::Initialization(format!(
334 "pyvenv.cfg not found in venv: {}",
335 venv_path.display()
336 )));
337 }
338
339 let content = fs::read_to_string(&pyvenv_cfg)
340 .map_err(|e| BridgeError::Initialization(format!("Failed to read pyvenv.cfg: {}", e)))?;
341
342 for line in content.lines() {
343 let line = line.trim();
344 if line.starts_with("home") {
345 if let Some((_key, value)) = line.split_once('=') {
346 let home_bin = PathBuf::from(value.trim());
347 if let Some(parent) = home_bin.parent() {
349 logger::debug(&format!(
350 "Resolved PYTHONHOME from pyvenv.cfg: {}",
351 parent.display()
352 ));
353 return Ok(parent.to_path_buf());
354 }
355 return Ok(home_bin);
357 }
358 }
359 }
360
361 Err(BridgeError::Initialization(format!(
362 "Could not find 'home' in pyvenv.cfg: {}",
363 pyvenv_cfg.display()
364 )))
365}
366
367fn get_compiled_python_version() -> String {
372 "3.12".to_string()
376}
377
378fn check_python_library_available() -> Result<(), BridgeError> {
383 #[cfg(any(target_os = "macos", target_os = "linux"))]
384 {
385 let python_version = get_compiled_python_version();
386
387 #[cfg(target_os = "macos")]
388 let (lib_names, search_paths, env_var) = (
389 vec![format!("libpython{}.dylib", python_version)],
390 &[
391 "/opt/homebrew/lib",
392 "/usr/local/lib",
393 "/Library/Frameworks/Python.framework/Versions/Current/lib",
394 ][..],
395 "DYLD_LIBRARY_PATH",
396 );
397
398 #[cfg(target_os = "linux")]
399 let (lib_names, search_paths, env_var) = (
400 vec![
401 format!("libpython{}.so", python_version),
402 format!("libpython{}.so.1.0", python_version),
403 ],
404 &[
405 "/usr/lib",
406 "/usr/lib64",
407 "/usr/local/lib",
408 "/usr/local/lib64",
409 ][..],
410 "LD_LIBRARY_PATH",
411 );
412
413 if let Ok(paths) = env::var(env_var) {
415 if find_lib_in_paths(paths.split(':'), &lib_names) {
416 return Ok(());
417 }
418 }
419
420 if find_lib_in_paths(search_paths.iter().copied(), &lib_names) {
422 return Ok(());
423 }
424
425 if let Some(lib_dir) = find_python_lib_via_uv(&python_version, &lib_names) {
427 prepend_to_env_path(env_var, &lib_dir);
428 logger::debug(&format!(
429 "Set {} to include: {}",
430 env_var,
431 lib_dir.display()
432 ));
433 return Ok(());
434 }
435
436 logger::debug("Python library not found in standard locations, relying on rpath");
439 Ok(())
440 }
441
442 #[cfg(target_os = "windows")]
443 {
444 if let Err(e) = setup_windows_dll_path() {
446 logger::debug(&format!("Windows DLL path setup note: {}", e));
447 }
448 Ok(())
449 }
450
451 #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
452 {
453 Ok(())
455 }
456}
457
458#[cfg(any(target_os = "macos", target_os = "linux"))]
461fn find_lib_in_paths<I, S>(paths: I, lib_names: &[String]) -> bool
462where
463 I: Iterator<Item = S>,
464 S: AsRef<str>,
465{
466 for path in paths {
467 for lib_name in lib_names {
468 let lib_path = PathBuf::from(path.as_ref()).join(lib_name);
469 if lib_path.exists() {
470 logger::debug(&format!("Found Python library at: {}", lib_path.display()));
471 return true;
472 }
473 }
474 }
475 false
476}
477
478#[cfg(any(target_os = "macos", target_os = "linux"))]
481fn find_python_lib_via_uv(python_version: &str, lib_names: &[String]) -> Option<PathBuf> {
482 let output = Command::new("uv")
483 .args(["python", "find", python_version])
484 .output()
485 .ok()?;
486
487 if !output.status.success() {
488 return None;
489 }
490
491 let python_path = String::from_utf8_lossy(&output.stdout);
492 let python_path = python_path.trim();
493
494 let lib_dir = PathBuf::from(python_path).parent()?.parent()?.join("lib");
496
497 for lib_name in lib_names {
498 let lib_path = lib_dir.join(lib_name);
499 if lib_path.exists() {
500 logger::debug(&format!(
501 "Found Python library via uv: {}",
502 lib_path.display()
503 ));
504 return Some(lib_dir);
505 }
506 }
507
508 None
509}
510
511#[cfg(any(target_os = "macos", target_os = "linux"))]
513fn prepend_to_env_path(env_var: &str, dir: &Path) {
514 if let Some(existing) = env::var_os(env_var) {
515 let mut paths = env::split_paths(&existing).collect::<Vec<_>>();
516 paths.insert(0, dir.to_path_buf());
517 if let Ok(new_path) = env::join_paths(&paths) {
518 env::set_var(env_var, new_path);
519 }
520 } else {
521 env::set_var(env_var, dir);
522 }
523}
524
525#[cfg(target_os = "windows")]
527fn setup_windows_dll_path() -> Result<(), BridgeError> {
528 let python_version = get_compiled_python_version();
529 let dll_name = format!("python{}.dll", python_version.replace(".", ""));
530
531 let output = Command::new("uv")
533 .args(["python", "find", &python_version])
534 .output();
535
536 if let Ok(output) = output {
537 if output.status.success() {
538 let python_path = String::from_utf8_lossy(&output.stdout);
539 let python_path = python_path.trim();
540 if let Some(parent) = PathBuf::from(python_path).parent() {
541 let dll_path = parent.join(&dll_name);
543 if dll_path.exists() {
544 if let Ok(current_path) = env::var("PATH") {
546 let new_path = format!("{};{}", parent.display(), current_path);
547 env::set_var("PATH", &new_path);
548 logger::debug(&format!(
549 "Added {} to PATH for Python DLL discovery",
550 parent.display()
551 ));
552 return Ok(());
553 }
554 }
555 }
556 }
557 }
558
559 if let Ok(output) = Command::new("where").arg("python").output() {
561 if output.status.success() {
562 let python_path = String::from_utf8_lossy(&output.stdout);
563 if let Some(first_line) = python_path.lines().next() {
564 if let Some(parent) = PathBuf::from(first_line.trim()).parent() {
565 let dll_path = parent.join(&dll_name);
566 if dll_path.exists() {
567 logger::debug(&format!("Found Python DLL at: {}", dll_path.display()));
568 return Ok(());
569 }
570 }
571 }
572 }
573 }
574
575 Err(BridgeError::PythonLibraryNotFound(format!(
576 "Could not find {}.\n\n\
577 This binary requires Python {} to be installed.\n\n\
578 To fix this on Windows:\n\
579 1. Install Python via uv: uv python install {}\n\
580 2. Or download from https://www.python.org/downloads/\n\
581 3. Ensure Python is in your PATH\n\n\
582 If you installed Python via uv, try running:\n\
583 uv python find {}",
584 dll_name, python_version, python_version, python_version
585 )))
586}
587
588pub fn configure_python_venv() -> Result<PythonEnvCompat, BridgeError> {
590 let config = Config::load()
591 .map_err(|e| BridgeError::Initialization(format!("Failed to load config: {}", e)))?;
592
593 let venv_path = PathBuf::from(config.get_venv_path());
594
595 let interpreter = resolve_python_path(&venv_path)?;
596 let python_home = resolve_python_home(&venv_path).ok();
597
598 Ok(PythonEnvCompat {
599 interpreter,
600 python_home,
601 })
602}
603
604#[derive(Debug, Clone)]
606pub struct PythonEnvCompat {
607 pub interpreter: PathBuf,
608 pub python_home: Option<PathBuf>,
609}
610
611#[cfg(test)]
612mod tests {
613 use super::*;
614
615 #[test]
616 fn test_bridge_struct() {
617 let _bridge = Bridge { _marker: () };
619 }
620
621 #[test]
622 fn test_get_compiled_python_version() {
623 let version = get_compiled_python_version();
624 assert!(version.starts_with("3."));
625 }
626}