use std::process::Command;
use crate::config::{AppConfig, GlobalConfig};
use crate::db;

pub fn run(note_identifier: String, no_edit: bool) {
    let global = GlobalConfig::load();
    let Some(notebook_path) = global.notebook_path() else {
        eprintln!("Notebook not initialized");
        std::process::exit(1);
    };

    let config = AppConfig::load();

    // 1. Resolve path. 
    // First, check if it's a direct file path relative to notebook root.
    let mut file_path = notebook_path.join(&note_identifier);
    
    // If it's not a direct file, search for it as a title in the database.
    if !file_path.exists() {
        match db::list_notes(&notebook_path) {
            Ok(notes) => {
                if let Some(note) = notes.iter().find(|n| n.title == note_identifier || n.filename == note_identifier) {
                    file_path = notebook_path.join(&note.filename);
                } else {
                    eprintln!("Note not found: {}", note_identifier);
                    std::process::exit(1);
                }
            }
            Err(e) => {
                eprintln!("Database error: {}", e);
                std::process::exit(1);
            }
        }
    }

    if !no_edit {
        // 2. Launch Editor
        let status = Command::new(&config.smarana.editor)
            .arg(&file_path)
            .status();

        match status {
            Ok(s) if !s.success() => {
                eprintln!("Editor exited with non-zero status");
            }
            Err(e) => {
                eprintln!("Failed to open editor '{}': {}", config.smarana.editor, e);
            }
            _ => {}
        }
    }

    // 3. Sync Database
    db::sync(&notebook_path);
}
