use crate::core::backend::GeneratedFile;
use crate::core::ir::ApiSurface;
use std::path::Path;

/// Emit service-API callback registration functions into a sibling Rust source file.
///
/// swift-bridge 0.1.59 parses `src/lib.rs` through syn 1.x and rejects the Rust 2024
/// `#[unsafe(no_mangle)]` attribute form. Keeping these functions out of `src/lib.rs`
/// prevents swift-bridge from parsing them while still compiling them as Rust code.
pub(super) fn emit_callback_registration_file(api: &ApiSurface, base: &Path) -> Option<GeneratedFile> {
    let extern_callbacks =
        crate::backends::swift::gen_bindings::service_api::generate_rust_callback_c_functions(api).unwrap_or_default();
    if extern_callbacks.is_empty() {
        return None;
    }

    let mut body = String::new();
    body.push_str("// Generated by alef. Do not edit by hand.\n");
    body.push_str("//\n");
    body.push_str("// Callback registration functions for service-API entrypoints.\n");
    body.push_str("// Kept out of src/lib.rs because swift-bridge 0.1.59 uses syn 1.x,\n");
    body.push_str("// which rejects the Rust 2024 `#[unsafe(no_mangle)]` attribute form.\n");
    body.push_str("// swift-bridge only parses src/lib.rs, so this file is invisible to it.\n\n");
    body.push_str("#![allow(unused_variables, unreachable_code, unreachable_patterns)]\n\n");
    body.push_str("use super::*;\n\n");
    for func_block in &extern_callbacks {
        body.push_str(func_block);
        body.push('\n');
    }

    Some(GeneratedFile {
        path: base.join("src/extern_callbacks.rs"),
        content: body,
        generated_header: false,
    })
}
