#!/usr/bin/env nu
# Syntaxis CLI wrapper script
# This script sets up the environment and forwards arguments to the real binary

# Source shared libraries - they should be in NU_LIB_DIRS
source syntaxis-lib.nu
source syntaxis-cli-lib.nu

$env.SYNTAXIS_CONFIG_DIR = ($env.HOME | path join ".config/syntaxis")

let real_binary = $"($env.HOME)/.cargo/bin/syntaxis-cli.real"
# Setup environment for auto-discovery config loading
$env.SYNTAXIS_DATA_DIR = $"($env.HOME)/.local/share/syntaxis"
$env.SYNTAXIS_PUBLIC_DIR = $"($env.HOME)/.config/syntaxis/public"

let config_file = (
    if (($env.SYNTAXIS_CONFIG_DIR | path join "config.toml") | path exists) {
        $env.SYNTAXIS_CONFIG_DIR | path join "config.toml"
    } else if (($env.SYNTAXIS_CONFIG_DIR | path join "syntaxis-cli.toml") | path exists) {
        $env.SYNTAXIS_CONFIG_DIR | path join "syntaxis-cli.toml"
    } else {
        print $"🛑 Config path not found in ($env.SYNTAXIS_CONFIG_DIR) "
        exit 0
    }
)
let config = (open $config_file)
 # Read UI configuration
let show_logo = match ($config | get -o ui.show_logo) {
    "true" | true => true,
    _ => false,
}
$env.RUN_NAME = ($config | get -o ui.run_name)

# Forward all arguments to the real binary with --config flag
# Arguments come from the command line that invoked this script
def main [...args] {
    # Detect if user provided --config flag or is asking for help
    let has_user_config = ($args | any {|arg| ($arg == "--config") or ($arg == "-c")})
    let asking_for_help = ($args | any {|arg| ($arg == "--help") or ($arg == "-h")})

    if ($args | length) == 0 {
        # No arguments provided
        if $show_logo {
            # Show logo and usage
            show_logo
        }
        cli_usage
    } else if $asking_for_help {
        # User asking for help - pass --help to binary without config
        if $show_logo { show_logo }
        ^$real_binary ...$args
    } else {
        if $show_logo { show_logo }
        # Forward all arguments to real binary with conditional config injection
        if $has_user_config {
            # User provided --config, forward as-is
            ^$real_binary ...$args
        } else {
            # Inject auto-discovered config
            ^$real_binary --config $config_file ...$args
        }
    }
}
