//! Native Runtime: kein IDE- oder BASIC-Quellcompiler-Einstieg.
use std::process::ExitCode;
#[used]
static MARKER: [u8; 32] = tb_export::runtime_marker(if cfg!(target_os = "windows") {
    tb_export::Target::WindowsAmd64
} else if cfg!(target_os = "macos") {
    tb_export::Target::MacosArm64
} else if cfg!(target_arch = "aarch64") {
    tb_export::Target::LinuxArm64
} else {
    tb_export::Target::LinuxAmd64
});
fn main() -> ExitCode {
    std::hint::black_box(&MARKER);
    let path = match std::env::current_exe() {
        Ok(p) => p,
        Err(e) => {
            eprintln!("Executable nicht auffindbar: {e}");
            return ExitCode::from(1);
        }
    };
    let bytes = match std::fs::read(&path) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("Executable nicht lesbar: {e}");
            return ExitCode::from(1);
        }
    };
    let target = match tb_export::Target::host() {
        Ok(t) => t,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(1);
        }
    };
    if let Err(e) = tb_export::embedded(&bytes, target) {
        eprintln!("Ladefehler: {e:#}");
        return ExitCode::from(1);
    }
    let command = std::env::args().skip(1).collect::<Vec<_>>().join(" ");
    tb_runner::run(&path, &command, |current| {
        let result = if current == path {
            tb_export::embedded(&bytes, target).map_err(|e| format!("{e:#}"))
        } else if tb_vm::project_io::has_extension(current, "tbc") {
            std::fs::read(current)
                .map_err(|e| e.to_string())
                .and_then(|b| {
                    tb_vm::bytecode::CompiledModule::from_tbc(&b).map_err(|e| e.to_string())
                })
        } else {
            Err("tbrt benötigt ein vorkompiliertes externes RUN-Ziel (.tbc); kein BASIC-Quellcompiler enthalten".into())
        };
        result.map_err(|e| {
            eprintln!("{}: Ladefehler: {e}", current.display());
            ExitCode::from(1)
        })
    })
}
