use std::io::IsTerminal;
use std::str::FromStr;

/// Output format for CLI command results, controlling whether data is rendered
/// as a human-readable table, structured JSON for scripting, or CSV for spreadsheets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
    /// Colored, aligned columns optimized for terminal readability
    Table,
    /// Schema-stable JSON for piping into jq or other processing tools
    Json,
    /// Comma-separated values for spreadsheet import and simple text processing
    Csv,
}

/// Automatic detection and explicit override for output format selection
impl OutputFormat {
    /// Selects the appropriate format based on whether stdout is a TTY.
    /// Returns Table for interactive terminals (human reading output)
    /// and Json when piped (script consuming output).
    pub fn detect_from_terminal() -> Self {
        match std::io::stdout().is_terminal() {
            true => Self::Table,
            false => Self::Json,
        }
    }
}

impl FromStr for OutputFormat {
    type Err = anyhow::Error;

    fn from_str(raw_format: &str) -> anyhow::Result<Self> {
        match raw_format.to_lowercase().as_str() {
            "table" => Ok(Self::Table),
            "json" => Ok(Self::Json),
            "csv" => Ok(Self::Csv),
            _ => anyhow::bail!(
                "unknown output format '{}': expected one of table, json, csv",
                raw_format
            ),
        }
    }
}
