use night_fury_core::BrowserSession;
use serde_json::json;

use night_fury_cli_core::output::{output_err, output_ok, OutputMode};

pub async fn run(session: &BrowserSession, parts: &[&str], mode: OutputMode) {
    let method = parts.first().copied().unwrap_or("").trim();
    if method.is_empty() {
        output_err(mode, "Usage: cdp <method> [params_json]");
        return;
    }
    let params = if let Some(raw) = parts.get(1) {
        match serde_json::from_str::<serde_json::Value>(raw) {
            Ok(v) => v,
            Err(e) => {
                output_err(mode, &format!("Invalid JSON params: {e}"));
                return;
            }
        }
    } else {
        json!({})
    };
    match session.cdp_command(method, params).await {
        Ok(result) => {
            let human = result.to_string();
            output_ok(mode, &human, json!({"method": method, "result": result}));
        }
        Err(e) => output_err(mode, &e.to_string()),
    }
}
