use bevy::prelude::*;
use clap::{Parser, Subcommand};

use crate::debug::DebugEvent;

use super::ConsoleLog;

pub(super) fn respond(line: &str) -> Result<DebugEvent, String> {
    let args = shlex::split(line).ok_or("Invalid Quoting")?;
    let cli = Cli::try_parse_from(args).map_err(|e| e.to_string());

    // help detection
    let command_contains_help = line.contains("help") || line.contains("-h");
    let some_line_starts_with_usage = cli
        .as_ref()
        .is_err_and(|item| item.lines().any(|line| line.starts_with("Usage: ")));

    if command_contains_help && some_line_starts_with_usage {
        let Err(text) = cli else { unreachable!() };
        return Ok(DebugEvent::PrintToConsole { text, error: false });
    }

    Ok(cli?.cmd)
}

#[derive(Debug, Parser)]
#[command(multicall = true)]
struct Cli {
    #[command(subcommand)]
    cmd: DebugEvent,
}
