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")
239 .map_err(|e| BridgeError::Python(format!("Failed to create filename: {}", e)))?;
240 let module_name = std::ffi::CString::new("r2x_cache_patch")
241 .map_err(|e| BridgeError::Python(format!("Failed to create module name: {}", e)))?;
242 let patch_module = PyModule::from_code(
243 py,
244 code_cstr.as_c_str(),
245 filename.as_c_str(),
246 module_name.as_c_str(),
247 )
248 .map_err(|e| BridgeError::Python(format!("Failed to build cache override: {}", e)))?;
249
250 let override_fn = patch_module
251 .getattr("_r2x_cache_path_override")
252 .map_err(|e| {
253 BridgeError::Python(format!("Failed to obtain cache override function: {}", e))
254 })?;
255
256 let file_ops = PyModule::import(py, "r2x_core.utils.file_operations").map_err(|e| {
257 BridgeError::Python(format!(
258 "Failed to import r2x_core.utils.file_operations: {}",
259 e
260 ))
261 })?;
262
263 file_ops
264 .setattr("get_r2x_cache_path", override_fn)
265 .map_err(|e| {
266 BridgeError::Python(format!("Failed to override cache path: {}", e))
267 })?;
268
269 Ok::<(), BridgeError>(())
270 })?;
271
272 Ok(())
273 }
274
275 fn configure_python_logging() -> Result<(), BridgeError> {
277 let log_python = logger::get_log_python();
278 if !log_python {
279 return Ok(());
280 }
281
282 let verbosity = logger::get_verbosity();
283 logger::debug(&format!(
284 "Configuring Python logging with verbosity={}",
285 verbosity
286 ));
287
288 pyo3::Python::attach(|py| {
289 let logger_module = PyModule::import(py, "r2x_core.logger").map_err(|e| {
290 logger::warn(&format!("Failed to import r2x_core.logger: {}", e));
291 BridgeError::Import("r2x_core.logger".to_string(), format!("{}", e))
292 })?;
293 let setup_logging = logger_module.getattr("setup_logging").map_err(|e| {
294 logger::warn(&format!("Failed to get setup_logging function: {}", e));
295 BridgeError::Python(format!("setup_logging not found: {}", e))
296 })?;
297 setup_logging.call1((verbosity,))?;
298
299 let loguru = PyModule::import(py, "loguru")?;
300 let logger_obj = loguru.getattr("logger")?;
301 logger_obj.call_method1("enable", ("r2x_core",))?;
302 logger_obj.call_method1("enable", ("r2x_reeds",))?;
303 logger_obj.call_method1("enable", ("r2x_plexos",))?;
304 logger_obj.call_method1("enable", ("r2x_sienna",))?;
305
306 Ok::<(), BridgeError>(())
307 })
308 }
309
310 pub fn reconfigure_logging_for_plugin(_plugin_name: &str) -> Result<(), BridgeError> {
312 Self::configure_python_logging()
313 }
314}
315
316fn resolve_python_home(venv_path: &Path) -> Result<PathBuf, BridgeError> {
328 let pyvenv_cfg = venv_path.join("pyvenv.cfg");
329
330 if !pyvenv_cfg.exists() {
331 return Err(BridgeError::Initialization(format!(
332 "pyvenv.cfg not found in venv: {}",
333 venv_path.display()
334 )));
335 }
336
337 let content = fs::read_to_string(&pyvenv_cfg)
338 .map_err(|e| BridgeError::Initialization(format!("Failed to read pyvenv.cfg: {}", e)))?;
339
340 for line in content.lines() {
341 let line = line.trim();
342 if line.starts_with("home") {
343 if let Some((_key, value)) = line.split_once('=') {
344 let home_bin = PathBuf::from(value.trim());
345 if let Some(parent) = home_bin.parent() {
347 logger::debug(&format!(
348 "Resolved PYTHONHOME from pyvenv.cfg: {}",
349 parent.display()
350 ));
351 return Ok(parent.to_path_buf());
352 }
353 return Ok(home_bin);
355 }
356 }
357 }
358
359 Err(BridgeError::Initialization(format!(
360 "Could not find 'home' in pyvenv.cfg: {}",
361 pyvenv_cfg.display()
362 )))
363}
364
365fn get_compiled_python_version() -> String {
370 "3.12".to_string()
374}
375
376fn check_python_library_available() -> Result<(), BridgeError> {
381 #[cfg(any(target_os = "macos", target_os = "linux"))]
382 {
383 let python_version = get_compiled_python_version();
384
385 #[cfg(target_os = "macos")]
386 let (lib_names, search_paths, env_var) = (
387 vec![format!("libpython{}.dylib", python_version)],
388 &[
389 "/opt/homebrew/lib",
390 "/usr/local/lib",
391 "/Library/Frameworks/Python.framework/Versions/Current/lib",
392 ][..],
393 "DYLD_LIBRARY_PATH",
394 );
395
396 #[cfg(target_os = "linux")]
397 let (lib_names, search_paths, env_var) = (
398 vec![
399 format!("libpython{}.so", python_version),
400 format!("libpython{}.so.1.0", python_version),
401 ],
402 &[
403 "/usr/lib",
404 "/usr/lib64",
405 "/usr/local/lib",
406 "/usr/local/lib64",
407 ][..],
408 "LD_LIBRARY_PATH",
409 );
410
411 if let Ok(paths) = env::var(env_var) {
413 if find_lib_in_paths(paths.split(':'), &lib_names) {
414 return Ok(());
415 }
416 }
417
418 if find_lib_in_paths(search_paths.iter().copied(), &lib_names) {
420 return Ok(());
421 }
422
423 if let Some(lib_dir) = find_python_lib_via_uv(&python_version, &lib_names) {
425 prepend_to_env_path(env_var, &lib_dir);
426 logger::debug(&format!(
427 "Set {} to include: {}",
428 env_var,
429 lib_dir.display()
430 ));
431 return Ok(());
432 }
433
434 logger::debug("Python library not found in standard locations, relying on rpath");
437 Ok(())
438 }
439
440 #[cfg(target_os = "windows")]
441 {
442 if let Err(e) = setup_windows_dll_path() {
444 logger::debug(&format!("Windows DLL path setup note: {}", e));
445 }
446 Ok(())
447 }
448
449 #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
450 {
451 Ok(())
453 }
454}
455
456#[cfg(any(target_os = "macos", target_os = "linux"))]
459fn find_lib_in_paths<I, S>(paths: I, lib_names: &[String]) -> bool
460where
461 I: Iterator<Item = S>,
462 S: AsRef<str>,
463{
464 for path in paths {
465 for lib_name in lib_names {
466 let lib_path = PathBuf::from(path.as_ref()).join(lib_name);
467 if lib_path.exists() {
468 logger::debug(&format!("Found Python library at: {}", lib_path.display()));
469 return true;
470 }
471 }
472 }
473 false
474}
475
476#[cfg(any(target_os = "macos", target_os = "linux"))]
479fn find_python_lib_via_uv(python_version: &str, lib_names: &[String]) -> Option<PathBuf> {
480 let output = Command::new("uv")
481 .args(["python", "find", python_version])
482 .output()
483 .ok()?;
484
485 if !output.status.success() {
486 return None;
487 }
488
489 let python_path = String::from_utf8_lossy(&output.stdout);
490 let python_path = python_path.trim();
491
492 let lib_dir = PathBuf::from(python_path).parent()?.parent()?.join("lib");
494
495 for lib_name in lib_names {
496 let lib_path = lib_dir.join(lib_name);
497 if lib_path.exists() {
498 logger::debug(&format!(
499 "Found Python library via uv: {}",
500 lib_path.display()
501 ));
502 return Some(lib_dir);
503 }
504 }
505
506 None
507}
508
509#[cfg(any(target_os = "macos", target_os = "linux"))]
511fn prepend_to_env_path(env_var: &str, dir: &Path) {
512 if let Some(existing) = env::var_os(env_var) {
513 let mut paths = env::split_paths(&existing).collect::<Vec<_>>();
514 paths.insert(0, dir.to_path_buf());
515 if let Ok(new_path) = env::join_paths(&paths) {
516 env::set_var(env_var, new_path);
517 }
518 } else {
519 env::set_var(env_var, dir);
520 }
521}
522
523#[cfg(target_os = "windows")]
525fn setup_windows_dll_path() -> Result<(), BridgeError> {
526 let python_version = get_compiled_python_version();
527 let dll_name = format!("python{}.dll", python_version.replace(".", ""));
528
529 let output = Command::new("uv")
531 .args(["python", "find", &python_version])
532 .output();
533
534 if let Ok(output) = output {
535 if output.status.success() {
536 let python_path = String::from_utf8_lossy(&output.stdout);
537 let python_path = python_path.trim();
538 if let Some(parent) = PathBuf::from(python_path).parent() {
539 let dll_path = parent.join(&dll_name);
541 if dll_path.exists() {
542 if let Ok(current_path) = env::var("PATH") {
544 let new_path = format!("{};{}", parent.display(), current_path);
545 env::set_var("PATH", &new_path);
546 logger::debug(&format!(
547 "Added {} to PATH for Python DLL discovery",
548 parent.display()
549 ));
550 return Ok(());
551 }
552 }
553 }
554 }
555 }
556
557 if let Ok(output) = Command::new("where").arg("python").output() {
559 if output.status.success() {
560 let python_path = String::from_utf8_lossy(&output.stdout);
561 if let Some(first_line) = python_path.lines().next() {
562 if let Some(parent) = PathBuf::from(first_line.trim()).parent() {
563 let dll_path = parent.join(&dll_name);
564 if dll_path.exists() {
565 logger::debug(&format!("Found Python DLL at: {}", dll_path.display()));
566 return Ok(());
567 }
568 }
569 }
570 }
571 }
572
573 Err(BridgeError::PythonLibraryNotFound(format!(
574 "Could not find {}.\n\n\
575 This binary requires Python {} to be installed.\n\n\
576 To fix this on Windows:\n\
577 1. Install Python via uv: uv python install {}\n\
578 2. Or download from https://www.python.org/downloads/\n\
579 3. Ensure Python is in your PATH\n\n\
580 If you installed Python via uv, try running:\n\
581 uv python find {}",
582 dll_name, python_version, python_version, python_version
583 )))
584}
585
586pub fn configure_python_venv() -> Result<PythonEnvCompat, BridgeError> {
588 let config = Config::load()
589 .map_err(|e| BridgeError::Initialization(format!("Failed to load config: {}", e)))?;
590
591 let venv_path = PathBuf::from(config.get_venv_path());
592
593 let interpreter = resolve_python_path(&venv_path)?;
594 let python_home = resolve_python_home(&venv_path).ok();
595
596 Ok(PythonEnvCompat {
597 interpreter,
598 python_home,
599 })
600}
601
602#[derive(Debug, Clone)]
604pub struct PythonEnvCompat {
605 pub interpreter: PathBuf,
606 pub python_home: Option<PathBuf>,
607}
608
609#[cfg(test)]
610mod tests {
611 use crate::python_bridge::*;
612
613 #[test]
614 fn test_bridge_struct() {
615 let _bridge = Bridge { _marker: () };
617 }
618
619 #[test]
620 fn test_get_compiled_python_version() {
621 let version = get_compiled_python_version();
622 assert!(version.starts_with("3."));
623 }
624}